Debian Codegraph @

envisage/service_registry.py

raw
1 # (C) Copyright 2007-2025 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10 """ The service registry. """
11
12
13 # Standard library imports.
14 import logging
15
16 # Enthought library imports.
17 from traits.api import Dict, Event, HasTraits, Int, provides
18
19 # Local imports.
20 from .i_service_registry import IServiceRegistry
21 from .import_manager import ImportManager
22
23 # Logging.
24 logger = logging.getLogger(__name__)
25
26
27 class NoSuchServiceError(Exception):
28 """Raised when a required service is not found."""
29
30
31 @provides(IServiceRegistry)
32 class ServiceRegistry(HasTraits):
33 """The service registry."""
34
35 #### IServiceRegistry interface ##########################################
36
37 #: An event that is fired when a service is registered.
38 registered = Event
39
40 #: An event that is fired when a service is unregistered.
41 unregistered = Event
42
43 #### Private interface ###################################################
44
45 # The services in the registry.
46 #
47 # { service_id : (protocol_name, obj, properties) }
48 #
49 # where:
50 #
51 # 'protocol_name' is the (possible dotted) name of the interface, type or
52 # class that the object is registered against.
53 #
54 # 'obj' is the object that is registered (any old, Python object!).
55 #
56 # 'properties' is the arbitrary dictionary of properties that were
57 # registered with the object.
58 _services = Dict
59
60 # The next service Id (service Ids are never persisted between process
61 # invocations so this is simply an ever increasing integer!).
62 _service_id = Int
63
64 ###########################################################################
65 # 'IServiceRegistry' interface.
66 ###########################################################################
67
68 def get_required_service(
69 self, protocol, query="", minimize="", maximize=""
70 ):
71 """Return the service that matches the specified query.
72
73 Raise a 'NoSuchServiceError' exception if no such service exists.
74
75 """
76
77 service = self.get_service(protocol, query, minimize, maximize)
78 if service is None:
79 raise NoSuchServiceError(protocol)
80
81 return service
82
83 def get_service(self, protocol, query="", minimize="", maximize=""):
84 """Return at most one service that matches the specified query."""
85
86 services = self.get_services(protocol, query, minimize, maximize)
87 if len(services) > 0:
88 service = services[0]
89
90 else:
91 service = None
92
93 return service
94
95 def get_service_from_id(self, service_id):
96 """Return the service with the specified id."""
97
98 try:
99 protocol, obj, properties = self._services[service_id]
100
101 except KeyError:
102 raise ValueError("no service with id <%d>" % service_id)
103
104 return obj
105
106 def get_services(self, protocol, query="", minimize="", maximize=""):
107 """Return all services that match the specified query."""
108
109 services = []
110 for service_id, (name, obj, properties) in self._services.items():
111 if self._get_protocol_name(protocol) == name:
112 # If the protocol is a string then we need to import it!
113 if isinstance(protocol, str):
114 actual_protocol = ImportManager().import_symbol(protocol)
115
116 # Otherwise, it is an actual protocol, so just use it!
117 else:
118 actual_protocol = protocol
119
120 # If the registered service is actually a factory then use it
121 # to create the actual object.
122 obj = self._resolve_factory(
123 actual_protocol, name, obj, properties, service_id
124 )
125
126 # If a query was specified then only add the service if it
127 # matches it!
128 if len(query) == 0 or self._eval_query(obj, properties, query):
129 services.append(obj)
130
131 # Are we minimizing or maximising anything? If so then sort the list
132 # of services by the specified attribute/property.
133 if minimize != "":
134 services.sort(key=lambda x: getattr(x, minimize))
135
136 elif maximize != "":
137 services.sort(key=lambda x: getattr(x, maximize), reverse=True)
138
139 return services
140
141 def get_service_properties(self, service_id):
142 """Return the dictionary of properties associated with a service."""
143
144 try:
145 protocol, obj, properties = self._services[service_id]
146 properties = properties.copy()
147
148 except KeyError:
149 raise ValueError("no service with id <%d>" % service_id)
150
151 return properties
152
153 def register_service(self, protocol, obj, properties=None):
154 """Register a service."""
155
156 protocol_name = self._get_protocol_name(protocol)
157
158 # Make sure each service gets its own properties dictionary.
159 if properties is None:
160 properties = {}
161
162 service_id = self._next_service_id()
163 self._services[service_id] = (protocol_name, obj, properties)
164 self.registered = service_id
165
166 logger.debug("service <%d> registered %s", service_id, protocol_name)
167
168 return service_id
169
170 def set_service_properties(self, service_id, properties):
171 """Set the dictionary of properties associated with a service."""
172
173 try:
174 protocol, obj, old_properties = self._services[service_id]
175 self._services[service_id] = protocol, obj, properties.copy()
176
177 except KeyError:
178 raise ValueError("no service with id <%d>" % service_id)
179
180 def unregister_service(self, service_id):
181 """Unregister a service."""
182
183 try:
184 protocol, obj, properties = self._services.pop(service_id)
185 self.unregistered = service_id
186
187 logger.debug("service <%d> unregistered", service_id)
188
189 except KeyError:
190 raise ValueError("no service with id <%d>" % service_id)
191
192 ###########################################################################
193 # Private interface.
194 ###########################################################################
195
196 def _create_namespace(self, service, properties):
197 """Create a namespace in which to evaluate a query."""
198
199 namespace = {}
200 namespace.update(service.__dict__)
201 namespace.update(properties)
202
203 return namespace
204
205 def _eval_query(self, service, properties, query):
206 """Evaluate a query over a single service.
207
208 Return True if the service matches the query, otherwise return False.
209
210 """
211
212 namespace = self._create_namespace(service, properties)
213 try:
214 result = eval(query, namespace)
215
216 except Exception:
217 result = False
218
219 return result
220
221 def _get_protocol_name(self, protocol_or_name):
222 """Returns the full class name for a protocol."""
223
224 if isinstance(protocol_or_name, str):
225 name = protocol_or_name
226
227 else:
228 name = "%s.%s" % (
229 protocol_or_name.__module__,
230 protocol_or_name.__name__,
231 )
232
233 return name
234
235 def _is_service_factory(self, protocol, obj):
236 """Is the object a factory for services supporting the protocol?"""
237
238 # fixme: Should we have a formal notion of service factory with an
239 # appropriate API, or is this good enough? An API might have lifecycle
240 # methods to both create and destroy the service?!?
241
242 return not isinstance(obj, protocol)
243
244 def _next_service_id(self):
245 """Returns the next service ID."""
246
247 self._service_id += 1
248
249 return self._service_id
250
251 def _resolve_factory(self, protocol, name, obj, properties, service_id):
252 """If 'obj' is a factory then use it to create the actual service."""
253
254 # Is the registered service actually a service *factory*?
255 if self._is_service_factory(protocol, obj):
256 # A service factory is any callable that takes two arguments, the
257 # first is the protocol, the second is the (possibly empty)
258 # dictionary of properties that were registered with the service.
259 #
260 # If the factory is specified as a symbol path then import it.
261 if isinstance(obj, str):
262 obj = ImportManager().import_symbol(obj)
263
264 obj = obj(**properties)
265
266 # The resulting service object replaces the factory in the cache
267 # (i.e. the factory will not get called again unless it is
268 # unregistered first).
269 self._services[service_id] = (name, obj, properties)
270
271 return obj