Debian Codegraph @

beanie/odm/actions.py

raw
1 import asyncio
2 import inspect
3 from collections.abc import Callable
4 from enum import Enum
5 from functools import wraps
6 from typing import (
7 TYPE_CHECKING,
8 Any,
9 TypeVar,
10 cast,
11 )
12
13 from typing_extensions import ParamSpec
14
15 if TYPE_CHECKING:
16 from beanie.odm.documents import AsyncDocMethod, Document
17
18 P = ParamSpec("P")
19 R = TypeVar("R")
20
21
22 class EventTypes(str, Enum):
23 INSERT = "INSERT"
24 REPLACE = "REPLACE"
25 SAVE = "SAVE"
26 SAVE_CHANGES = "SAVE_CHANGES"
27 VALIDATE_ON_SAVE = "VALIDATE_ON_SAVE"
28 DELETE = "DELETE"
29 UPDATE = "UPDATE"
30
31
32 Insert = EventTypes.INSERT
33 Replace = EventTypes.REPLACE
34 Save = EventTypes.SAVE
35 SaveChanges = EventTypes.SAVE_CHANGES
36 ValidateOnSave = EventTypes.VALIDATE_ON_SAVE
37 Delete = EventTypes.DELETE
38 Update = EventTypes.UPDATE
39
40
41 class ActionDirections(str, Enum): # TODO think about this name
42 BEFORE = "BEFORE"
43 AFTER = "AFTER"
44
45
46 Before = ActionDirections.BEFORE
47 After = ActionDirections.AFTER
48
49
50 class ActionRegistry:
51 _actions: dict[
52 type["Document"],
53 dict[EventTypes, dict[ActionDirections, list[Callable[..., Any]]]],
54 ] = {}
55
56 @classmethod
57 def clean_actions(cls, document_class: type["Document"]):
58 if cls._actions.get(document_class) is not None:
59 del cls._actions[document_class]
60
61 @classmethod
62 def add_action(
63 cls,
64 document_class: type["Document"],
65 event_types: list[EventTypes],
66 action_direction: ActionDirections,
67 funct: Callable,
68 ):
69 """
70 Add action to the action registry
71 :param document_class: document class
72 :param event_types: List[EventTypes]
73 :param action_direction: ActionDirections - before or after
74 :param funct: Callable - function
75 """
76 if cls._actions.get(document_class) is None:
77 cls._actions[document_class] = {
78 action_type: {
79 action_direction: []
80 for action_direction in ActionDirections
81 }
82 for action_type in EventTypes
83 }
84 for event_type in event_types:
85 cls._actions[document_class][event_type][action_direction].append(
86 funct
87 )
88
89 @classmethod
90 def get_action_list(
91 cls,
92 document_class: type["Document"],
93 event_type: EventTypes,
94 action_direction: ActionDirections,
95 ) -> list[Callable]:
96 """
97 Get stored action list
98 :param document_class: Type - document class
99 :param event_type: EventTypes - type of needed event
100 :param action_direction: ActionDirections - before or after
101 :return: List[Callable] - list of stored methods
102 """
103 if document_class not in cls._actions:
104 return []
105 return cls._actions[document_class][event_type][action_direction]
106
107 @classmethod
108 async def run_actions(
109 cls,
110 instance: "Document",
111 event_type: EventTypes,
112 action_direction: ActionDirections,
113 exclude: list[ActionDirections | str],
114 ):
115 """
116 Run actions
117 :param instance: Document - object of the Document subclass
118 :param event_type: EventTypes - event types
119 :param action_direction: ActionDirections - before or after
120 """
121 if action_direction in exclude:
122 return
123
124 document_class = instance.__class__
125 actions_list = cls.get_action_list(
126 document_class, event_type, action_direction
127 )
128 coros = []
129 for action in actions_list:
130 if action.__name__ in exclude:
131 continue
132
133 if inspect.iscoroutinefunction(action):
134 coros.append(action(instance))
135 elif inspect.isfunction(action):
136 action(instance)
137 await asyncio.gather(*coros)
138
139
140 # `Any` because there is arbitrary attribute assignment on this type
141 F = TypeVar("F", bound=Any)
142
143
144 def register_action(
145 event_types: tuple[list[EventTypes] | EventTypes, ...],
146 action_direction: ActionDirections,
147 ) -> Callable[[F], F]:
148 """
149 Decorator. Base registration method.
150 Used inside `before_event` and `after_event`
151 :param event_types: Union[List[EventTypes], EventTypes] - event types
152 :param action_direction: ActionDirections - before or after
153 :return:
154 """
155 final_event_types = []
156 for event_type in event_types:
157 if isinstance(event_type, list):
158 final_event_types.extend(event_type)
159 else:
160 final_event_types.append(event_type)
161
162 def decorator(f: F) -> F:
163 f.has_action = True
164 f.event_types = final_event_types
165 f.action_direction = action_direction
166 return f
167
168 return decorator
169
170
171 def before_event(
172 *args: list[EventTypes] | EventTypes,
173 ) -> Callable[[F], F]:
174 """
175 Decorator. It adds action, which should run before mentioned one
176 or many events happen
177
178 :param args: Union[List[EventTypes], EventTypes] - event types
179 :return: None
180 """
181 return register_action(
182 action_direction=ActionDirections.BEFORE, event_types=args
183 )
184
185
186 def after_event(
187 *args: list[EventTypes] | EventTypes,
188 ) -> Callable[[F], F]:
189 """
190 Decorator. It adds action, which should run after mentioned one
191 or many events happen
192
193 :param args: Union[List[EventTypes], EventTypes] - event types
194 :return: None
195 """
196
197 return register_action(
198 action_direction=ActionDirections.AFTER, event_types=args
199 )
200
201
202 def wrap_with_actions(
203 event_type: EventTypes,
204 ) -> Callable[["AsyncDocMethod[P, R]"], "AsyncDocMethod[P, R]"]:
205 """
206 Helper function to wrap Document methods with
207 before and after event listeners
208 :param event_type: EventTypes - event types
209 :return: None
210 """
211
212 def decorator(
213 f: "AsyncDocMethod[P, R]",
214 ) -> "AsyncDocMethod[P, R]":
215 @wraps(f)
216 async def wrapper(
217 *args: P.args,
218 **kwargs: P.kwargs,
219 ) -> R:
220 skip_actions: list[ActionDirections | str] = (
221 kwargs.get("skip_actions") or [] # type: ignore[assignment]
222 )
223
224 self = cast("Document", args[0])
225
226 await ActionRegistry.run_actions(
227 self,
228 event_type=event_type,
229 action_direction=ActionDirections.BEFORE,
230 exclude=skip_actions,
231 )
232
233 result = await f(*args, **kwargs)
234
235 await ActionRegistry.run_actions(
236 self,
237 event_type=event_type,
238 action_direction=ActionDirections.AFTER,
239 exclude=skip_actions,
240 )
241
242 return result
243
244 return wrapper
245
246 return decorator