Source

htsql-firebird / src / htsql / core / adapter.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
#
# Copyright (c) 2006-2012, Prometheus Research, LLC
# See `LICENSE` for license information, `AUTHORS` for the list of authors.
#


"""
:mod:`htsql.core.adapter`
=========================

This module provides a mechanism for pluggable extensions.
"""


from .util import listof, aresubclasses, toposort
from .context import context
import sys
import types


class Component(object):
    """
    A unit of extension in the HTSQL component architecture.

    *HTSQL component architecture* allows you to:

    - declare *interfaces* that provide various services;

    - define *components* implementing the interfaces;

    - given an interface and a *dispatch key*, produce a component which
      implements the interface for the given key.

    Three types of interfaces are supported: *utilities*, *adapters* and
    *protocols*; see :class:`Utility`, :class:`Adapter`, :class:`Protocol`
    respectively.
    """

    # Augment method names with prefix `<name>.` to make the adapter
    # name visible in tracebacks.
    class __metaclass__(type):

        def __new__(mcls, name, bases, content):
            # Iterate over all values in the class namespace.
            for value in content.values():
                # Ignore non-function attributes.
                if not isinstance(value, types.FunctionType):
                    continue
                # Update the code name and regenerate the code object.
                code = value.func_code
                code_name = code.co_name
                if '.' in code_name:
                    continue
                code_name = '%s.%s' % (name, code_name)
                code = types.CodeType(code.co_argcount, code.co_nlocals,
                                      code.co_stacksize, code.co_flags,
                                      code.co_code, code.co_consts,
                                      code.co_names, code.co_varnames,
                                      code.co_filename, code_name,
                                      code.co_firstlineno, code.co_lnotab,
                                      code.co_freevars, code.co_cellvars)
                # Patch the function object.
                value.func_code = code
            # Create the class.
            return type.__new__(mcls, name, bases, content)

    @staticmethod
    def components():
        """
        Produce a list of all components of the active application.
        """
        # Get the component registry of the active application.
        registry = context.app.component_registry
        # A shortcut: return cached components.
        if registry.components is not None:
            return registry.components
        # A list of `Component` subclasses defined in modules exported by addons.
        components = [Component]
        idx = 0
        while idx < len(components):
            for subclass in components[idx].__subclasses__():
                # Skip realizations.
                if issubclass(subclass, Realization):
                    continue
                # Check if the component belongs to the current application.
                if subclass.active():
                    components.append(subclass)
            idx += 1
        # Cache and return the components.
        registry.components = components
        return components

    @classmethod
    def implementations(interface):
        """
        Produces a list of all components implementing the interface.
        """
        # Get the component registry of the active application.
        registry = context.app.component_registry
        # A shortcut: return cached implementations.
        try:
            return registry.implementations[interface]
        except KeyError:
            pass
        # Get all active components.
        components = interface.components()
        # Leave only components implementing the interface.
        implementations = [component
                           for component in components
                           if component.implements(interface)]
        # Cache and return the implementations.
        registry.implementations[interface] = implementations
        return implementations

    @classmethod
    def realize(interface, dispatch_key):
        """
        Produces a realization of the interface for the given dispatch key.
        """
        # Get the component registry of the active application.
        registry = context.app.component_registry

        # A shortcut: if the realization for the given interface and the
        # dispatch key is already built, return it.
        try:
            return registry.realizations[interface, dispatch_key]
        except KeyError:
            pass

        # Get the implementations of the interface.
        implementations = interface.implementations()
        # Leave only implementations matching the dispatch key.
        implementations = [implementation
                           for implementation in implementations
                           if implementation.matches(dispatch_key)]
        # Note: commented out since we force the interface component
        # to match any dispatch keys.
        ## Check that we have at least one matching implementation.
        #if not implementations:
        #    raise RuntimeError("when realizing interface %s.%s for key %r,"
        #                       " unable to find matching implementations"
        #                       % (interface.__module__, interface.__name__,
        #                          dispatch_key))

        # Generate a function:
        # order(implementation) -> [dominated implementations].
        order_graph = {}
        for dominating in implementations:
            order_graph[dominating] = []
            for dominated in implementations:
                if dominating is dominated:
                    continue
                if dominating.dominates(dominated):
                    order_graph[dominating].append(dominated)
        order = (lambda implementation: order_graph[implementation])

        # Now we need to order the implementations unambiguously.
        try:
            implementations = toposort(implementations, order, is_total=True)
        except RuntimeError, exc:
            # We intercept exceptions to provide a nicer error message.
            # `message` is an explanation we discard; `conflict` is a list
            # of implementations which either form a domination loop or
            # have no ordering relation between them.
            message, conflict = exc
            interface_name = "%s.%s" % (interface.__module__,
                                        interface.__name__)
            component_names = ", ".join("%s.%s" % (component.__module__,
                                                   component.__name__)
                                        for component in conflict)
            if conflict[0] is conflict[-1]:
                problem = "an ordering loop"
            else:
                problem = "ambiguous ordering"
            # Report a problem.
            raise RuntimeError("when realizing interface %s for key %r,"
                               " detected %s in components: %s"
                               % (interface_name, dispatch_key,
                                  problem, component_names))

        # We want the most specific implementations first.
        implementations.reverse()

        # Force the interface component to the list of implementations.
        if interface not in implementations:
            implementations.append(interface)

        # Generate the name of the realization of the form:
        #   interface[implementation1,implementation2,...]
        module = interface.__module__
        name = "%s[%s]" % (interface.__name__,
                           ",".join("%s.%s" % (component.__module__,
                                               component.__name__)
                                    for component in implementations
                                    if component is not interface))
        # Get the list of bases for the realization.
        bases = tuple([Realization] + implementations)
        # Class attributes for the realization.
        attributes = {
                '__module__': module,
                'interface': interface,
                'dispatch_key': dispatch_key,
        }
        # Generate the realization.
        realization = type(name, bases, attributes)

        # Cache and return the realization.
        registry.realizations[interface, dispatch_key] = realization
        return realization

    @classmethod
    def active(component):
        """
        Tests if the component is a part of the current application.
        """
        registry = context.app.component_registry
        return (component.__module__ in registry.modules)

    @classmethod
    def implements(component, interface):
        """
        Tests if the component implements the interface.
        """
        return issubclass(component, interface)

    @classmethod
    def dominates(component, other):
        """
        Tests if the component dominates another component.
        """
        # Refine in subclasses.
        return issubclass(component, other)

    @classmethod
    def matches(component, dispatch_key):
        """
        Tests if the component matches a dispatch key.
        """
        # Override in subclasses.
        return False

    @classmethod
    def dispatch(interface, *args, **kwds):
        """
        Extract the dispatch key from the constructor arguments.
        """
        # Override in subclasses.
        return None

    def __new__(interface, *args, **kwds):
        # Extract polymorphic parameters.
        dispatch_key = interface.dispatch(*args, **kwds)
        # Realize the interface.
        realization = interface.realize(dispatch_key)
        # Create an instance of the realization.
        return super(Component, realization).__new__(realization)


class Realization(Component):
    """
    A realization of an interface for some dispatch key.
    """

    interface = None
    dispatch_key = None

    def __new__(cls, *args, **kwds):
        # Bypass `Component.__new__`.
        return object.__new__(cls)


class Utility(Component):
    """
    Implements utility interfaces.

    An utility is an interface with a single realization.

    This is an abstract class; to declare an utility interface, create
    a subclass of :class:`Utility`.  To add an implementation of the
    interface, create a subclass of the interface class.

    The following example declared an interface ``SayHello`` and provide
    an implementation ``PrintHello`` that prints ``'Hello, World!`` to
    the standard output::

        class SayHello(Utility):
            def __call__(self):
                raise NotImplementedError("interface is not implemented")

        class PrintHello(SayHello):
            def __call__(self):
                print "Hello, World!"

        def hello():
            hello = SayHello()
            hello()

        >>> hello()
        Hello, World!
    """

    weight = 0.0

    @classmethod
    def dominates(component, other):
        if issubclass(component, other):
            return True
        if component.weight > other.weight:
            return True
        return False

    @classmethod
    def matches(component, dispatch_key):
        # For an utility, the dispatch key is always a 0-tuple.
        assert dispatch_key == ()
        return True

    @classmethod
    def dispatch(interface, *args, **kwds):
        # The dispatch key is always a 0-tuple.
        return ()


def weigh(value):
    assert isinstance(value, (int, float))
    frame = sys._getframe(1)
    frame.f_locals['weight'] = value


class Adapter(Component):
    """
    Implements adapter interfaces.

    An adapter interface provides mechanism for polymorphic dispatch
    based on the types of the arguments.

    This is an abstract class; to declare an adapter interface, create
    a subclass of :class:`Adapter` and indicate the most generic type
    signature of the polymorphic arguments using function :func:`adapts`.

    To add an implementation of an adapter interface, create a subclass
    of the interface class and indicate the matching type signatures
    using functions :func:`adapts`, :func:`adapts_many`, or
    :func:`adapts_none`.

    Class attributes:

    `types` (a list of type signatures)
        List of signatures that the component matches.
    
    `arity` (an integer)
        Number of polymorphic arguments.

    The following example declares an adapter interface ``Format``
    and implements it for several data types::

        class Format(Adapter):
            adapts(object)
            def __init__(self, value):
                self.value = value
            def __call__(self):
                # The default implementation.
                return str(self.value)

        class FormatString(Format):
            adapts(str)
            def __call__(self):
                # Display alphanumeric values unquoted, the others quoted.
                if self.value.isalnum():
                    return self.value
                else:
                    return repr(self.value)

        class FormatList(Format):
            adapts(list)
            def __call__(self):
                # Apply `format` to the list elements.
                return "[%s]" % ",".join(format(item) for item in self.value)

        def format(value):
            format = Format(value)
            return format()

        >>> print format(123)
        123
        >>> print format("ABC")
        ABC
        >>> print format("Hello, World!")
        'Hello, World!'
        >>> print format([123, "ABC", "Hello, World!"])
        [123, ABC, 'Hello, World!']
    """

    types = []
    arity = 0

    @classmethod
    def dominates(component, other):
        # A component implementing an adapter interface dominates
        # over another component implementing the same interface
        # if one of the following two conditions holds:
        
        # (1) The component is a subclass of the other component.
        if issubclass(component, other):
            return True

        # (2) The signature of the component is more specific than
        #     the signature of the other component.
        # Note: In case if the component has more than one signature,
        # we require that at least one of the signatures is more
        # specific than some signature of the other component.  This
        # rule does not guarantee anti-symmetricity, so ambiguously
        # defined implementations may make the ordering ill defined.
        # Validness of the ordering is verified in `Component.realize()`.
        for type_vector in component.types:
            for other_type_vector in other.types:
                if aresubclasses(type_vector, other_type_vector):
                    if type_vector != other_type_vector:
                        return True

        return False

    @classmethod
    def matches(component, dispatch_key):
        # For an adapter interface, the dispatch key is a signature.
        # A component matches the dispatch key the component signature
        # is equal or less specific than the dispatch key.
        # Note: if the component has more than one signature, it
        # matches the dispatch key if at least one of its signatures
        # is equal or less specific than the dispatch key.
        assert isinstance(list(dispatch_key), listof(type))
        return any(aresubclasses(dispatch_key, type_vector)
                   for type_vector in component.types)

    @classmethod
    def dispatch(interface, *args, **kwds):
        # The types of the leading arguments of the constructor
        # form a dispatch key.
        assert interface.arity <= len(args)
        type_vector = tuple(type(arg) for arg in args[:interface.arity])
        return type_vector


def adapts(*type_vector):
    """
    Specifies the adapter signature.

    The component matches the specified or any more specific
    signature.

    Use it in the namespace of the component, for example::

        class DoSmth(Adapter):

            adapts(T1, T2, ...)
    """
    assert isinstance(list(type_vector), listof(type))
    frame = sys._getframe(1)
    frame.f_locals['types'] = [type_vector]
    frame.f_locals['arity'] = len(type_vector)


def adapts_none():
    """
    Indicates that the adapter does not match any signatures.

    Use it in the namespace of the adapter, for example::

        class DoSmth(Adapter):

            adapts_none()
    """
    frame = sys._getframe(1)
    frame.f_locals['types'] = []


def adapts_many(*type_vectors):
    """
    Specifies signatures of the adapter.

    The component matches any of the specified signatures as well
    all more specific signatures.

    Use it in the namespace of the adapter, for example::

        class DoSmth(Adapter):

            adapts_many((T11, T12, ...),
                        (T21, T22, ...),
                        ...)
    """
    # Normalize the given type vectors.
    type_vectors = [type_vector if isinstance(type_vector, tuple)
                                else (type_vector,)
                  for type_vector in type_vectors]
    assert len(type_vectors) > 0
    arity = len(type_vectors[0])
    assert all(len(type_vector) == arity
               for type_vector in type_vectors)
    frame = sys._getframe(1)
    frame.f_locals['types'] = type_vectors
    frame.f_locals['arity'] = arity


class Protocol(Component):
    """
    Implements protocol interfaces.

    A protocol interface provides mechanism for name-based dispatch.

    This is an abstract class; to declare a protocol interface, create
    a subclass of :class:`Protocol`.

    To add an implementation of a protocol interface, create a subclass
    of the interface class and specify its name using function :func:`named`.

    Class attributes:

    `names` (a list of strings)
        List of names that the component matches.

    The following example declares a protocol interface ``Weigh``
    and adds several implementations::

        class Weigh(Protocol):
            def __init__(self, name):
                self.name = name
            def __call__(self):
                # The default implementation.
                return -1

        class WeighAlice(Weigh):
            named("Alice")
            def __call__(self):
                return 150

        class WeighBob(Weigh):
            named("Bob")
            def __call__(self):
                return 160

        def weigh(name):
            weigh = Weigh(name)
            return weigh()

        >>> weigh("Alice")
        150
        >>> weigh("Bob")
        160
        >>> weigh("Clark")
        -1
    """

    names = []

    @classmethod
    def dispatch(interface, name, *args, **kwds):
        # The first argument of the constructor is the protocol name.
        return name

    @classmethod
    def matches(component, dispatch_key):
        # The dispatch key is the protocol name.
        assert isinstance(dispatch_key, str)
        return (dispatch_key in component.names)


def named(*names):
    """
    Specifies the names of the protocol.

    Use it in the namespace of the protocol, for example::

        class DoSmth(Protocol):

            named("...")
    """
    frame = sys._getframe(1)
    frame.f_locals['names'] = list(names)


class ComponentRegistry(object):
    """
    Contains cached components and realizations.
    """

    def __init__(self, addons):
        # Packages exported by addons.
        packages = set()
        for addon in addons:
            # In Python 2.6+:
            # root_package = sys.modules[addon.__module__].__package__
            root_package = addon.__module__
            if not hasattr(sys.modules[root_package], '__path__'):
                root_package = root_package.rsplit('.', 1)[0]
            # An addon exports packages defined in `packages` attribute.
            for package in addon.packages:
                # Resolve relative package names.
                if package == '.':
                    package = root_package
                elif package.startswith('.'):
                    package = root_package+package
                packages.add(package)
        # All modules exported by the addons.
        modules = set()
        for module in sorted(sys.modules):
            # In Python 2.6+:
            # package = sys.modules[module].__package__
            package = module
            if not hasattr(sys.modules[package], '__path__'):
                package = package.rsplit('.', 1)[0]
            if package in packages:
                modules.add(module)
        self.modules = modules
        # List of active components (populated by `Component.components()`).
        self.components = None
        # A mapping: interface -> [components]  (populated by
        # `Component.implementations()`).
        self.implementations = {}
        # A mapping: (interface, dispatch_key) -> realization (populated by
        # `Component.realize()`).
        self.realizations = {}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.