Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

registry.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2006 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Basic components support
  15. """
  16. from collections import defaultdict
  17. try:
  18. from zope.event import notify
  19. except ImportError: # pragma: no cover
  20. def notify(*arg, **kw): pass
  21. from zope.interface.interfaces import ISpecification
  22. from zope.interface.interfaces import ComponentLookupError
  23. from zope.interface.interfaces import IAdapterRegistration
  24. from zope.interface.interfaces import IComponents
  25. from zope.interface.interfaces import IHandlerRegistration
  26. from zope.interface.interfaces import ISubscriptionAdapterRegistration
  27. from zope.interface.interfaces import IUtilityRegistration
  28. from zope.interface.interfaces import Registered
  29. from zope.interface.interfaces import Unregistered
  30. from zope.interface.interface import Interface
  31. from zope.interface.declarations import implementedBy
  32. from zope.interface.declarations import implementer
  33. from zope.interface.declarations import implementer_only
  34. from zope.interface.declarations import providedBy
  35. from zope.interface.adapter import AdapterRegistry
  36. __all__ = [
  37. # Components is public API, but
  38. # the *Registration classes are just implementations
  39. # of public interfaces.
  40. 'Components',
  41. ]
  42. class _UnhashableComponentCounter:
  43. # defaultdict(int)-like object for unhashable components
  44. def __init__(self, otherdict):
  45. # [(component, count)]
  46. self._data = [item for item in otherdict.items()]
  47. def __getitem__(self, key):
  48. for component, count in self._data:
  49. if component == key:
  50. return count
  51. return 0
  52. def __setitem__(self, component, count):
  53. for i, data in enumerate(self._data):
  54. if data[0] == component:
  55. self._data[i] = component, count
  56. return
  57. self._data.append((component, count))
  58. def __delitem__(self, component):
  59. for i, data in enumerate(self._data):
  60. if data[0] == component:
  61. del self._data[i]
  62. return
  63. raise KeyError(component) # pragma: no cover
  64. def _defaultdict_int():
  65. return defaultdict(int)
  66. class _UtilityRegistrations:
  67. def __init__(self, utilities, utility_registrations):
  68. # {provided -> {component: count}}
  69. self._cache = defaultdict(_defaultdict_int)
  70. self._utilities = utilities
  71. self._utility_registrations = utility_registrations
  72. self.__populate_cache()
  73. def __populate_cache(self):
  74. for ((p, _), data) in iter(self._utility_registrations.items()):
  75. component = data[0]
  76. self.__cache_utility(p, component)
  77. def __cache_utility(self, provided, component):
  78. try:
  79. self._cache[provided][component] += 1
  80. except TypeError:
  81. # The component is not hashable, and we have a dict. Switch to a strategy
  82. # that doesn't use hashing.
  83. prov = self._cache[provided] = _UnhashableComponentCounter(self._cache[provided])
  84. prov[component] += 1
  85. def __uncache_utility(self, provided, component):
  86. provided = self._cache[provided]
  87. # It seems like this line could raise a TypeError if component isn't
  88. # hashable and we haven't yet switched to _UnhashableComponentCounter. However,
  89. # we can't actually get in that situation. In order to get here, we would
  90. # have had to cache the utility already which would have switched
  91. # the datastructure if needed.
  92. count = provided[component]
  93. count -= 1
  94. if count == 0:
  95. del provided[component]
  96. else:
  97. provided[component] = count
  98. return count > 0
  99. def _is_utility_subscribed(self, provided, component):
  100. try:
  101. return self._cache[provided][component] > 0
  102. except TypeError:
  103. # Not hashable and we're still using a dict
  104. return False
  105. def registerUtility(self, provided, name, component, info, factory):
  106. subscribed = self._is_utility_subscribed(provided, component)
  107. self._utility_registrations[(provided, name)] = component, info, factory
  108. self._utilities.register((), provided, name, component)
  109. if not subscribed:
  110. self._utilities.subscribe((), provided, component)
  111. self.__cache_utility(provided, component)
  112. def unregisterUtility(self, provided, name, component):
  113. del self._utility_registrations[(provided, name)]
  114. self._utilities.unregister((), provided, name)
  115. subscribed = self.__uncache_utility(provided, component)
  116. if not subscribed:
  117. self._utilities.unsubscribe((), provided, component)
  118. @implementer(IComponents)
  119. class Components:
  120. _v_utility_registrations_cache = None
  121. def __init__(self, name='', bases=()):
  122. # __init__ is used for test cleanup as well as initialization.
  123. # XXX add a separate API for test cleanup.
  124. assert isinstance(name, str)
  125. self.__name__ = name
  126. self._init_registries()
  127. self._init_registrations()
  128. self.__bases__ = tuple(bases)
  129. self._v_utility_registrations_cache = None
  130. def __repr__(self):
  131. return "<{} {}>".format(self.__class__.__name__, self.__name__)
  132. def __reduce__(self):
  133. # Mimic what a persistent.Persistent object does and elide
  134. # _v_ attributes so that they don't get saved in ZODB.
  135. # This allows us to store things that cannot be pickled in such
  136. # attributes.
  137. reduction = super().__reduce__()
  138. # (callable, args, state, listiter, dictiter)
  139. # We assume the state is always a dict; the last three items
  140. # are technically optional and can be missing or None.
  141. filtered_state = {k: v for k, v in reduction[2].items()
  142. if not k.startswith('_v_')}
  143. reduction = list(reduction)
  144. reduction[2] = filtered_state
  145. return tuple(reduction)
  146. def _init_registries(self):
  147. # Subclasses have never been required to call this method
  148. # if they override it, merely to fill in these two attributes.
  149. self.adapters = AdapterRegistry()
  150. self.utilities = AdapterRegistry()
  151. def _init_registrations(self):
  152. self._utility_registrations = {}
  153. self._adapter_registrations = {}
  154. self._subscription_registrations = []
  155. self._handler_registrations = []
  156. @property
  157. def _utility_registrations_cache(self):
  158. # We use a _v_ attribute internally so that data aren't saved in ZODB,
  159. # because this object cannot be pickled.
  160. cache = self._v_utility_registrations_cache
  161. if (cache is None
  162. or cache._utilities is not self.utilities
  163. or cache._utility_registrations is not self._utility_registrations):
  164. cache = self._v_utility_registrations_cache = _UtilityRegistrations(
  165. self.utilities,
  166. self._utility_registrations)
  167. return cache
  168. def _getBases(self):
  169. # Subclasses might override
  170. return self.__dict__.get('__bases__', ())
  171. def _setBases(self, bases):
  172. # Subclasses might override
  173. self.adapters.__bases__ = tuple([
  174. base.adapters for base in bases])
  175. self.utilities.__bases__ = tuple([
  176. base.utilities for base in bases])
  177. self.__dict__['__bases__'] = tuple(bases)
  178. __bases__ = property(
  179. lambda self: self._getBases(),
  180. lambda self, bases: self._setBases(bases),
  181. )
  182. def registerUtility(self, component=None, provided=None, name='',
  183. info='', event=True, factory=None):
  184. if factory:
  185. if component:
  186. raise TypeError("Can't specify factory and component.")
  187. component = factory()
  188. if provided is None:
  189. provided = _getUtilityProvided(component)
  190. if name == '':
  191. name = _getName(component)
  192. reg = self._utility_registrations.get((provided, name))
  193. if reg is not None:
  194. if reg[:2] == (component, info):
  195. # already registered
  196. return
  197. self.unregisterUtility(reg[0], provided, name)
  198. self._utility_registrations_cache.registerUtility(
  199. provided, name, component, info, factory)
  200. if event:
  201. notify(Registered(
  202. UtilityRegistration(self, provided, name, component, info,
  203. factory)
  204. ))
  205. def unregisterUtility(self, component=None, provided=None, name='',
  206. factory=None):
  207. if factory:
  208. if component:
  209. raise TypeError("Can't specify factory and component.")
  210. component = factory()
  211. if provided is None:
  212. if component is None:
  213. raise TypeError("Must specify one of component, factory and "
  214. "provided")
  215. provided = _getUtilityProvided(component)
  216. old = self._utility_registrations.get((provided, name))
  217. if (old is None) or ((component is not None) and
  218. (component != old[0])):
  219. return False
  220. if component is None:
  221. component = old[0]
  222. # Note that component is now the old thing registered
  223. self._utility_registrations_cache.unregisterUtility(
  224. provided, name, component)
  225. notify(Unregistered(
  226. UtilityRegistration(self, provided, name, component, *old[1:])
  227. ))
  228. return True
  229. def registeredUtilities(self):
  230. for ((provided, name), data
  231. ) in iter(self._utility_registrations.items()):
  232. yield UtilityRegistration(self, provided, name, *data)
  233. def queryUtility(self, provided, name='', default=None):
  234. return self.utilities.lookup((), provided, name, default)
  235. def getUtility(self, provided, name=''):
  236. utility = self.utilities.lookup((), provided, name)
  237. if utility is None:
  238. raise ComponentLookupError(provided, name)
  239. return utility
  240. def getUtilitiesFor(self, interface):
  241. yield from self.utilities.lookupAll((), interface)
  242. def getAllUtilitiesRegisteredFor(self, interface):
  243. return self.utilities.subscriptions((), interface)
  244. def registerAdapter(self, factory, required=None, provided=None,
  245. name='', info='', event=True):
  246. if provided is None:
  247. provided = _getAdapterProvided(factory)
  248. required = _getAdapterRequired(factory, required)
  249. if name == '':
  250. name = _getName(factory)
  251. self._adapter_registrations[(required, provided, name)
  252. ] = factory, info
  253. self.adapters.register(required, provided, name, factory)
  254. if event:
  255. notify(Registered(
  256. AdapterRegistration(self, required, provided, name,
  257. factory, info)
  258. ))
  259. def unregisterAdapter(self, factory=None,
  260. required=None, provided=None, name='',
  261. ):
  262. if provided is None:
  263. if factory is None:
  264. raise TypeError("Must specify one of factory and provided")
  265. provided = _getAdapterProvided(factory)
  266. if (required is None) and (factory is None):
  267. raise TypeError("Must specify one of factory and required")
  268. required = _getAdapterRequired(factory, required)
  269. old = self._adapter_registrations.get((required, provided, name))
  270. if (old is None) or ((factory is not None) and
  271. (factory != old[0])):
  272. return False
  273. del self._adapter_registrations[(required, provided, name)]
  274. self.adapters.unregister(required, provided, name)
  275. notify(Unregistered(
  276. AdapterRegistration(self, required, provided, name,
  277. *old)
  278. ))
  279. return True
  280. def registeredAdapters(self):
  281. for ((required, provided, name), (component, info)
  282. ) in iter(self._adapter_registrations.items()):
  283. yield AdapterRegistration(self, required, provided, name,
  284. component, info)
  285. def queryAdapter(self, object, interface, name='', default=None):
  286. return self.adapters.queryAdapter(object, interface, name, default)
  287. def getAdapter(self, object, interface, name=''):
  288. adapter = self.adapters.queryAdapter(object, interface, name)
  289. if adapter is None:
  290. raise ComponentLookupError(object, interface, name)
  291. return adapter
  292. def queryMultiAdapter(self, objects, interface, name='',
  293. default=None):
  294. return self.adapters.queryMultiAdapter(
  295. objects, interface, name, default)
  296. def getMultiAdapter(self, objects, interface, name=''):
  297. adapter = self.adapters.queryMultiAdapter(objects, interface, name)
  298. if adapter is None:
  299. raise ComponentLookupError(objects, interface, name)
  300. return adapter
  301. def getAdapters(self, objects, provided):
  302. for name, factory in self.adapters.lookupAll(
  303. list(map(providedBy, objects)),
  304. provided):
  305. adapter = factory(*objects)
  306. if adapter is not None:
  307. yield name, adapter
  308. def registerSubscriptionAdapter(self,
  309. factory, required=None, provided=None,
  310. name='', info='',
  311. event=True):
  312. if name:
  313. raise TypeError("Named subscribers are not yet supported")
  314. if provided is None:
  315. provided = _getAdapterProvided(factory)
  316. required = _getAdapterRequired(factory, required)
  317. self._subscription_registrations.append(
  318. (required, provided, name, factory, info)
  319. )
  320. self.adapters.subscribe(required, provided, factory)
  321. if event:
  322. notify(Registered(
  323. SubscriptionRegistration(self, required, provided, name,
  324. factory, info)
  325. ))
  326. def registeredSubscriptionAdapters(self):
  327. for data in self._subscription_registrations:
  328. yield SubscriptionRegistration(self, *data)
  329. def unregisterSubscriptionAdapter(self, factory=None,
  330. required=None, provided=None, name='',
  331. ):
  332. if name:
  333. raise TypeError("Named subscribers are not yet supported")
  334. if provided is None:
  335. if factory is None:
  336. raise TypeError("Must specify one of factory and provided")
  337. provided = _getAdapterProvided(factory)
  338. if (required is None) and (factory is None):
  339. raise TypeError("Must specify one of factory and required")
  340. required = _getAdapterRequired(factory, required)
  341. if factory is None:
  342. new = [(r, p, n, f, i)
  343. for (r, p, n, f, i)
  344. in self._subscription_registrations
  345. if not (r == required and p == provided)
  346. ]
  347. else:
  348. new = [(r, p, n, f, i)
  349. for (r, p, n, f, i)
  350. in self._subscription_registrations
  351. if not (r == required and p == provided and f == factory)
  352. ]
  353. if len(new) == len(self._subscription_registrations):
  354. return False
  355. self._subscription_registrations[:] = new
  356. self.adapters.unsubscribe(required, provided, factory)
  357. notify(Unregistered(
  358. SubscriptionRegistration(self, required, provided, name,
  359. factory, '')
  360. ))
  361. return True
  362. def subscribers(self, objects, provided):
  363. return self.adapters.subscribers(objects, provided)
  364. def registerHandler(self,
  365. factory, required=None,
  366. name='', info='',
  367. event=True):
  368. if name:
  369. raise TypeError("Named handlers are not yet supported")
  370. required = _getAdapterRequired(factory, required)
  371. self._handler_registrations.append(
  372. (required, name, factory, info)
  373. )
  374. self.adapters.subscribe(required, None, factory)
  375. if event:
  376. notify(Registered(
  377. HandlerRegistration(self, required, name, factory, info)
  378. ))
  379. def registeredHandlers(self):
  380. for data in self._handler_registrations:
  381. yield HandlerRegistration(self, *data)
  382. def unregisterHandler(self, factory=None, required=None, name=''):
  383. if name:
  384. raise TypeError("Named subscribers are not yet supported")
  385. if (required is None) and (factory is None):
  386. raise TypeError("Must specify one of factory and required")
  387. required = _getAdapterRequired(factory, required)
  388. if factory is None:
  389. new = [(r, n, f, i)
  390. for (r, n, f, i)
  391. in self._handler_registrations
  392. if r != required
  393. ]
  394. else:
  395. new = [(r, n, f, i)
  396. for (r, n, f, i)
  397. in self._handler_registrations
  398. if not (r == required and f == factory)
  399. ]
  400. if len(new) == len(self._handler_registrations):
  401. return False
  402. self._handler_registrations[:] = new
  403. self.adapters.unsubscribe(required, None, factory)
  404. notify(Unregistered(
  405. HandlerRegistration(self, required, name, factory, '')
  406. ))
  407. return True
  408. def handle(self, *objects):
  409. self.adapters.subscribers(objects, None)
  410. def rebuildUtilityRegistryFromLocalCache(self, rebuild=False):
  411. """
  412. Emergency maintenance method to rebuild the ``.utilities``
  413. registry from the local copy maintained in this object, or
  414. detect the need to do so.
  415. Most users will never need to call this, but it can be helpful
  416. in the event of suspected corruption.
  417. By default, this method only checks for corruption. To make it
  418. actually rebuild the registry, pass `True` for *rebuild*.
  419. :param bool rebuild: If set to `True` (not the default),
  420. this method will actually register and subscribe utilities
  421. in the registry as needed to synchronize with the local cache.
  422. :return: A dictionary that's meant as diagnostic data. The keys
  423. and values may change over time. When called with a false *rebuild*,
  424. the keys ``"needed_registered"`` and ``"needed_subscribed"`` will be
  425. non-zero if any corruption was detected, but that will not be corrected.
  426. .. versionadded:: 5.3.0
  427. """
  428. regs = dict(self._utility_registrations)
  429. utils = self.utilities
  430. needed_registered = 0
  431. did_not_register = 0
  432. needed_subscribed = 0
  433. did_not_subscribe = 0
  434. # Avoid the expensive change process during this; we'll call
  435. # it once at the end if needed.
  436. assert 'changed' not in utils.__dict__
  437. utils.changed = lambda _: None
  438. if rebuild:
  439. register = utils.register
  440. subscribe = utils.subscribe
  441. else:
  442. register = subscribe = lambda *args: None
  443. try:
  444. for (provided, name), (value, _info, _factory) in regs.items():
  445. if utils.registered((), provided, name) != value:
  446. register((), provided, name, value)
  447. needed_registered += 1
  448. else:
  449. did_not_register += 1
  450. if utils.subscribed((), provided, value) is None:
  451. needed_subscribed += 1
  452. subscribe((), provided, value)
  453. else:
  454. did_not_subscribe += 1
  455. finally:
  456. del utils.changed
  457. if rebuild and (needed_subscribed or needed_registered):
  458. utils.changed(utils)
  459. return {
  460. 'needed_registered': needed_registered,
  461. 'did_not_register': did_not_register,
  462. 'needed_subscribed': needed_subscribed,
  463. 'did_not_subscribe': did_not_subscribe
  464. }
  465. def _getName(component):
  466. try:
  467. return component.__component_name__
  468. except AttributeError:
  469. return ''
  470. def _getUtilityProvided(component):
  471. provided = list(providedBy(component))
  472. if len(provided) == 1:
  473. return provided[0]
  474. raise TypeError(
  475. "The utility doesn't provide a single interface "
  476. "and no provided interface was specified.")
  477. def _getAdapterProvided(factory):
  478. provided = list(implementedBy(factory))
  479. if len(provided) == 1:
  480. return provided[0]
  481. raise TypeError(
  482. "The adapter factory doesn't implement a single interface "
  483. "and no provided interface was specified.")
  484. def _getAdapterRequired(factory, required):
  485. if required is None:
  486. try:
  487. required = factory.__component_adapts__
  488. except AttributeError:
  489. raise TypeError(
  490. "The adapter factory doesn't have a __component_adapts__ "
  491. "attribute and no required specifications were specified"
  492. )
  493. elif ISpecification.providedBy(required):
  494. raise TypeError("the required argument should be a list of "
  495. "interfaces, not a single interface")
  496. result = []
  497. for r in required:
  498. if r is None:
  499. r = Interface
  500. elif not ISpecification.providedBy(r):
  501. if isinstance(r, type):
  502. r = implementedBy(r)
  503. else:
  504. raise TypeError("Required specification must be a "
  505. "specification or class, not %r" % type(r)
  506. )
  507. result.append(r)
  508. return tuple(result)
  509. @implementer(IUtilityRegistration)
  510. class UtilityRegistration:
  511. def __init__(self, registry, provided, name, component, doc, factory=None):
  512. (self.registry, self.provided, self.name, self.component, self.info,
  513. self.factory
  514. ) = registry, provided, name, component, doc, factory
  515. def __repr__(self):
  516. return '{}({!r}, {}, {!r}, {}, {!r}, {!r})'.format(
  517. self.__class__.__name__,
  518. self.registry,
  519. getattr(self.provided, '__name__', None), self.name,
  520. getattr(self.component, '__name__', repr(self.component)),
  521. self.factory, self.info,
  522. )
  523. def __hash__(self):
  524. return id(self)
  525. def __eq__(self, other):
  526. return repr(self) == repr(other)
  527. def __ne__(self, other):
  528. return repr(self) != repr(other)
  529. def __lt__(self, other):
  530. return repr(self) < repr(other)
  531. def __le__(self, other):
  532. return repr(self) <= repr(other)
  533. def __gt__(self, other):
  534. return repr(self) > repr(other)
  535. def __ge__(self, other):
  536. return repr(self) >= repr(other)
  537. @implementer(IAdapterRegistration)
  538. class AdapterRegistration:
  539. def __init__(self, registry, required, provided, name, component, doc):
  540. (self.registry, self.required, self.provided, self.name,
  541. self.factory, self.info
  542. ) = registry, required, provided, name, component, doc
  543. def __repr__(self):
  544. return '{}({!r}, {}, {}, {!r}, {}, {!r})'.format(
  545. self.__class__.__name__,
  546. self.registry,
  547. '[' + ", ".join([r.__name__ for r in self.required]) + ']',
  548. getattr(self.provided, '__name__', None), self.name,
  549. getattr(self.factory, '__name__', repr(self.factory)), self.info,
  550. )
  551. def __hash__(self):
  552. return id(self)
  553. def __eq__(self, other):
  554. return repr(self) == repr(other)
  555. def __ne__(self, other):
  556. return repr(self) != repr(other)
  557. def __lt__(self, other):
  558. return repr(self) < repr(other)
  559. def __le__(self, other):
  560. return repr(self) <= repr(other)
  561. def __gt__(self, other):
  562. return repr(self) > repr(other)
  563. def __ge__(self, other):
  564. return repr(self) >= repr(other)
  565. @implementer_only(ISubscriptionAdapterRegistration)
  566. class SubscriptionRegistration(AdapterRegistration):
  567. pass
  568. @implementer_only(IHandlerRegistration)
  569. class HandlerRegistration(AdapterRegistration):
  570. def __init__(self, registry, required, name, handler, doc):
  571. (self.registry, self.required, self.name, self.handler, self.info
  572. ) = registry, required, name, handler, doc
  573. @property
  574. def factory(self):
  575. return self.handler
  576. provided = None
  577. def __repr__(self):
  578. return '{}({!r}, {}, {!r}, {}, {!r})'.format(
  579. self.__class__.__name__,
  580. self.registry,
  581. '[' + ", ".join([r.__name__ for r in self.required]) + ']',
  582. self.name,
  583. getattr(self.factory, '__name__', repr(self.factory)), self.info,
  584. )