registry.py 25 KB

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