You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

469 lines
14KB

  1. # event/attr.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Attribute implementation for _Dispatch classes.
  8. The various listener targets for a particular event class are represented
  9. as attributes, which refer to collections of listeners to be fired off.
  10. These collections can exist at the class level as well as at the instance
  11. level. An event is fired off using code like this::
  12. some_object.dispatch.first_connect(arg1, arg2)
  13. Above, ``some_object.dispatch`` would be an instance of ``_Dispatch`` and
  14. ``first_connect`` is typically an instance of ``_ListenerCollection``
  15. if event listeners are present, or ``_EmptyListener`` if none are present.
  16. The attribute mechanics here spend effort trying to ensure listener functions
  17. are available with a minimum of function call overhead, that unnecessary
  18. objects aren't created (i.e. many empty per-instance listener collections),
  19. as well as that everything is garbage collectable when owning references are
  20. lost. Other features such as "propagation" of listener functions across
  21. many ``_Dispatch`` instances, "joining" of multiple ``_Dispatch`` instances,
  22. as well as support for subclass propagation (e.g. events assigned to
  23. ``Pool`` vs. ``QueuePool``) are all implemented here.
  24. """
  25. from __future__ import absolute_import
  26. from __future__ import with_statement
  27. import collections
  28. from itertools import chain
  29. import weakref
  30. from . import legacy
  31. from . import registry
  32. from .. import exc
  33. from .. import util
  34. from ..util import threading
  35. from ..util.concurrency import AsyncAdaptedLock
  36. class RefCollection(util.MemoizedSlots):
  37. __slots__ = ("ref",)
  38. def _memoized_attr_ref(self):
  39. return weakref.ref(self, registry._collection_gced)
  40. class _empty_collection(object):
  41. def append(self, element):
  42. pass
  43. def extend(self, other):
  44. pass
  45. def remove(self, element):
  46. pass
  47. def __iter__(self):
  48. return iter([])
  49. def clear(self):
  50. pass
  51. class _ClsLevelDispatch(RefCollection):
  52. """Class-level events on :class:`._Dispatch` classes."""
  53. __slots__ = (
  54. "clsname",
  55. "name",
  56. "arg_names",
  57. "has_kw",
  58. "legacy_signatures",
  59. "_clslevel",
  60. "__weakref__",
  61. )
  62. def __init__(self, parent_dispatch_cls, fn):
  63. self.name = fn.__name__
  64. self.clsname = parent_dispatch_cls.__name__
  65. argspec = util.inspect_getfullargspec(fn)
  66. self.arg_names = argspec.args[1:]
  67. self.has_kw = bool(argspec.varkw)
  68. self.legacy_signatures = list(
  69. reversed(
  70. sorted(
  71. getattr(fn, "_legacy_signatures", []), key=lambda s: s[0]
  72. )
  73. )
  74. )
  75. fn.__doc__ = legacy._augment_fn_docs(self, parent_dispatch_cls, fn)
  76. self._clslevel = weakref.WeakKeyDictionary()
  77. def _adjust_fn_spec(self, fn, named):
  78. if named:
  79. fn = self._wrap_fn_for_kw(fn)
  80. if self.legacy_signatures:
  81. try:
  82. argspec = util.get_callable_argspec(fn, no_self=True)
  83. except TypeError:
  84. pass
  85. else:
  86. fn = legacy._wrap_fn_for_legacy(self, fn, argspec)
  87. return fn
  88. def _wrap_fn_for_kw(self, fn):
  89. def wrap_kw(*args, **kw):
  90. argdict = dict(zip(self.arg_names, args))
  91. argdict.update(kw)
  92. return fn(**argdict)
  93. return wrap_kw
  94. def insert(self, event_key, propagate):
  95. target = event_key.dispatch_target
  96. assert isinstance(
  97. target, type
  98. ), "Class-level Event targets must be classes."
  99. if not getattr(target, "_sa_propagate_class_events", True):
  100. raise exc.InvalidRequestError(
  101. "Can't assign an event directly to the %s class" % target
  102. )
  103. for cls in util.walk_subclasses(target):
  104. if cls is not target and cls not in self._clslevel:
  105. self.update_subclass(cls)
  106. else:
  107. if cls not in self._clslevel:
  108. self._assign_cls_collection(cls)
  109. self._clslevel[cls].appendleft(event_key._listen_fn)
  110. registry._stored_in_collection(event_key, self)
  111. def append(self, event_key, propagate):
  112. target = event_key.dispatch_target
  113. assert isinstance(
  114. target, type
  115. ), "Class-level Event targets must be classes."
  116. if not getattr(target, "_sa_propagate_class_events", True):
  117. raise exc.InvalidRequestError(
  118. "Can't assign an event directly to the %s class" % target
  119. )
  120. for cls in util.walk_subclasses(target):
  121. if cls is not target and cls not in self._clslevel:
  122. self.update_subclass(cls)
  123. else:
  124. if cls not in self._clslevel:
  125. self._assign_cls_collection(cls)
  126. self._clslevel[cls].append(event_key._listen_fn)
  127. registry._stored_in_collection(event_key, self)
  128. def _assign_cls_collection(self, target):
  129. if getattr(target, "_sa_propagate_class_events", True):
  130. self._clslevel[target] = collections.deque()
  131. else:
  132. self._clslevel[target] = _empty_collection()
  133. def update_subclass(self, target):
  134. if target not in self._clslevel:
  135. self._assign_cls_collection(target)
  136. clslevel = self._clslevel[target]
  137. for cls in target.__mro__[1:]:
  138. if cls in self._clslevel:
  139. clslevel.extend(
  140. [fn for fn in self._clslevel[cls] if fn not in clslevel]
  141. )
  142. def remove(self, event_key):
  143. target = event_key.dispatch_target
  144. for cls in util.walk_subclasses(target):
  145. if cls in self._clslevel:
  146. self._clslevel[cls].remove(event_key._listen_fn)
  147. registry._removed_from_collection(event_key, self)
  148. def clear(self):
  149. """Clear all class level listeners"""
  150. to_clear = set()
  151. for dispatcher in self._clslevel.values():
  152. to_clear.update(dispatcher)
  153. dispatcher.clear()
  154. registry._clear(self, to_clear)
  155. def for_modify(self, obj):
  156. """Return an event collection which can be modified.
  157. For _ClsLevelDispatch at the class level of
  158. a dispatcher, this returns self.
  159. """
  160. return self
  161. class _InstanceLevelDispatch(RefCollection):
  162. __slots__ = ()
  163. def _adjust_fn_spec(self, fn, named):
  164. return self.parent._adjust_fn_spec(fn, named)
  165. class _EmptyListener(_InstanceLevelDispatch):
  166. """Serves as a proxy interface to the events
  167. served by a _ClsLevelDispatch, when there are no
  168. instance-level events present.
  169. Is replaced by _ListenerCollection when instance-level
  170. events are added.
  171. """
  172. propagate = frozenset()
  173. listeners = ()
  174. __slots__ = "parent", "parent_listeners", "name"
  175. def __init__(self, parent, target_cls):
  176. if target_cls not in parent._clslevel:
  177. parent.update_subclass(target_cls)
  178. self.parent = parent # _ClsLevelDispatch
  179. self.parent_listeners = parent._clslevel[target_cls]
  180. self.name = parent.name
  181. def for_modify(self, obj):
  182. """Return an event collection which can be modified.
  183. For _EmptyListener at the instance level of
  184. a dispatcher, this generates a new
  185. _ListenerCollection, applies it to the instance,
  186. and returns it.
  187. """
  188. result = _ListenerCollection(self.parent, obj._instance_cls)
  189. if getattr(obj, self.name) is self:
  190. setattr(obj, self.name, result)
  191. else:
  192. assert isinstance(getattr(obj, self.name), _JoinedListener)
  193. return result
  194. def _needs_modify(self, *args, **kw):
  195. raise NotImplementedError("need to call for_modify()")
  196. exec_once = (
  197. exec_once_unless_exception
  198. ) = insert = append = remove = clear = _needs_modify
  199. def __call__(self, *args, **kw):
  200. """Execute this event."""
  201. for fn in self.parent_listeners:
  202. fn(*args, **kw)
  203. def __len__(self):
  204. return len(self.parent_listeners)
  205. def __iter__(self):
  206. return iter(self.parent_listeners)
  207. def __bool__(self):
  208. return bool(self.parent_listeners)
  209. __nonzero__ = __bool__
  210. class _CompoundListener(_InstanceLevelDispatch):
  211. __slots__ = "_exec_once_mutex", "_exec_once", "_exec_w_sync_once"
  212. def _set_asyncio(self):
  213. self._exec_once_mutex = AsyncAdaptedLock()
  214. def _memoized_attr__exec_once_mutex(self):
  215. return threading.Lock()
  216. def _exec_once_impl(self, retry_on_exception, *args, **kw):
  217. with self._exec_once_mutex:
  218. if not self._exec_once:
  219. try:
  220. self(*args, **kw)
  221. exception = False
  222. except:
  223. exception = True
  224. raise
  225. finally:
  226. if not exception or not retry_on_exception:
  227. self._exec_once = True
  228. def exec_once(self, *args, **kw):
  229. """Execute this event, but only if it has not been
  230. executed already for this collection."""
  231. if not self._exec_once:
  232. self._exec_once_impl(False, *args, **kw)
  233. def exec_once_unless_exception(self, *args, **kw):
  234. """Execute this event, but only if it has not been
  235. executed already for this collection, or was called
  236. by a previous exec_once_unless_exception call and
  237. raised an exception.
  238. If exec_once was already called, then this method will never run
  239. the callable regardless of whether it raised or not.
  240. .. versionadded:: 1.3.8
  241. """
  242. if not self._exec_once:
  243. self._exec_once_impl(True, *args, **kw)
  244. def _exec_w_sync_on_first_run(self, *args, **kw):
  245. """Execute this event, and use a mutex if it has not been
  246. executed already for this collection, or was called
  247. by a previous _exec_w_sync_on_first_run call and
  248. raised an exception.
  249. If _exec_w_sync_on_first_run was already called and didn't raise an
  250. exception, then a mutex is not used.
  251. .. versionadded:: 1.4.11
  252. """
  253. if not self._exec_w_sync_once:
  254. with self._exec_once_mutex:
  255. try:
  256. self(*args, **kw)
  257. except:
  258. raise
  259. else:
  260. self._exec_w_sync_once = True
  261. else:
  262. self(*args, **kw)
  263. def __call__(self, *args, **kw):
  264. """Execute this event."""
  265. for fn in self.parent_listeners:
  266. fn(*args, **kw)
  267. for fn in self.listeners:
  268. fn(*args, **kw)
  269. def __len__(self):
  270. return len(self.parent_listeners) + len(self.listeners)
  271. def __iter__(self):
  272. return chain(self.parent_listeners, self.listeners)
  273. def __bool__(self):
  274. return bool(self.listeners or self.parent_listeners)
  275. __nonzero__ = __bool__
  276. class _ListenerCollection(_CompoundListener):
  277. """Instance-level attributes on instances of :class:`._Dispatch`.
  278. Represents a collection of listeners.
  279. As of 0.7.9, _ListenerCollection is only first
  280. created via the _EmptyListener.for_modify() method.
  281. """
  282. __slots__ = (
  283. "parent_listeners",
  284. "parent",
  285. "name",
  286. "listeners",
  287. "propagate",
  288. "__weakref__",
  289. )
  290. def __init__(self, parent, target_cls):
  291. if target_cls not in parent._clslevel:
  292. parent.update_subclass(target_cls)
  293. self._exec_once = False
  294. self._exec_w_sync_once = False
  295. self.parent_listeners = parent._clslevel[target_cls]
  296. self.parent = parent
  297. self.name = parent.name
  298. self.listeners = collections.deque()
  299. self.propagate = set()
  300. def for_modify(self, obj):
  301. """Return an event collection which can be modified.
  302. For _ListenerCollection at the instance level of
  303. a dispatcher, this returns self.
  304. """
  305. return self
  306. def _update(self, other, only_propagate=True):
  307. """Populate from the listeners in another :class:`_Dispatch`
  308. object."""
  309. existing_listeners = self.listeners
  310. existing_listener_set = set(existing_listeners)
  311. self.propagate.update(other.propagate)
  312. other_listeners = [
  313. l
  314. for l in other.listeners
  315. if l not in existing_listener_set
  316. and not only_propagate
  317. or l in self.propagate
  318. ]
  319. existing_listeners.extend(other_listeners)
  320. to_associate = other.propagate.union(other_listeners)
  321. registry._stored_in_collection_multi(self, other, to_associate)
  322. def insert(self, event_key, propagate):
  323. if event_key.prepend_to_list(self, self.listeners):
  324. if propagate:
  325. self.propagate.add(event_key._listen_fn)
  326. def append(self, event_key, propagate):
  327. if event_key.append_to_list(self, self.listeners):
  328. if propagate:
  329. self.propagate.add(event_key._listen_fn)
  330. def remove(self, event_key):
  331. self.listeners.remove(event_key._listen_fn)
  332. self.propagate.discard(event_key._listen_fn)
  333. registry._removed_from_collection(event_key, self)
  334. def clear(self):
  335. registry._clear(self, self.listeners)
  336. self.propagate.clear()
  337. self.listeners.clear()
  338. class _JoinedListener(_CompoundListener):
  339. __slots__ = "parent", "name", "local", "parent_listeners"
  340. def __init__(self, parent, name, local):
  341. self._exec_once = False
  342. self.parent = parent
  343. self.name = name
  344. self.local = local
  345. self.parent_listeners = self.local
  346. @property
  347. def listeners(self):
  348. return getattr(self.parent, self.name)
  349. def _adjust_fn_spec(self, fn, named):
  350. return self.local._adjust_fn_spec(fn, named)
  351. def for_modify(self, obj):
  352. self.local = self.parent_listeners = self.local.for_modify(obj)
  353. return self
  354. def insert(self, event_key, propagate):
  355. self.local.insert(event_key, propagate)
  356. def append(self, event_key, propagate):
  357. self.local.append(event_key, propagate)
  358. def remove(self, event_key):
  359. self.local.remove(event_key)
  360. def clear(self):
  361. raise NotImplementedError()