| 1 |
# Copyright DataStax, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from collections import OrderedDict |
| 16 |
from warnings import warn |
| 17 |
|
| 18 |
from cassandra.datastax.insights.util import namespace |
| 19 |
|
| 20 |
_NOT_SET = object() |
| 21 |
|
| 22 |
|
| 23 |
def _default_serializer_for_object(obj, policy): |
| 24 |
# the insights server expects an 'options' dict for policy |
| 25 |
# objects, but not for other objects |
| 26 |
if policy: |
| 27 |
return {'type': obj.__class__.__name__, |
| 28 |
'namespace': namespace(obj.__class__), |
| 29 |
'options': {}} |
| 30 |
else: |
| 31 |
return {'type': obj.__class__.__name__, |
| 32 |
'namespace': namespace(obj.__class__)} |
| 33 |
|
| 34 |
|
| 35 |
class InsightsSerializerRegistry(object): |
| 36 |
|
| 37 |
initialized = False |
| 38 |
|
| 39 |
def __init__(self, mapping_dict=None): |
| 40 |
mapping_dict = mapping_dict or {} |
| 41 |
class_order = self._class_topological_sort(mapping_dict) |
| 42 |
self._mapping_dict = OrderedDict( |
| 43 |
((cls, mapping_dict[cls]) for cls in class_order) |
| 44 |
) |
| 45 |
|
| 46 |
def serialize(self, obj, policy=False, default=_NOT_SET, cls=None): |
| 47 |
try: |
| 48 |
return self._get_serializer(cls if cls is not None else obj.__class__)(obj) |
| 49 |
except Exception: |
| 50 |
if default is _NOT_SET: |
| 51 |
result = _default_serializer_for_object(obj, policy) |
| 52 |
else: |
| 53 |
result = default |
| 54 |
|
| 55 |
return result |
| 56 |
|
| 57 |
def _get_serializer(self, cls): |
| 58 |
try: |
| 59 |
return self._mapping_dict[cls] |
| 60 |
except KeyError: |
| 61 |
for registered_cls, serializer in self._mapping_dict.items(): |
| 62 |
if issubclass(cls, registered_cls): |
| 63 |
return self._mapping_dict[registered_cls] |
| 64 |
raise ValueError |
| 65 |
|
| 66 |
def register(self, cls, serializer): |
| 67 |
self._mapping_dict[cls] = serializer |
| 68 |
self._mapping_dict = OrderedDict( |
| 69 |
((cls, self._mapping_dict[cls]) |
| 70 |
for cls in self._class_topological_sort(self._mapping_dict)) |
| 71 |
) |
| 72 |
|
| 73 |
def register_serializer_for(self, cls): |
| 74 |
""" |
| 75 |
Parameterized registration helper decorator. Given a class `cls`, |
| 76 |
produces a function that registers the decorated function as a |
| 77 |
serializer for it. |
| 78 |
""" |
| 79 |
def decorator(serializer): |
| 80 |
self.register(cls, serializer) |
| 81 |
return serializer |
| 82 |
|
| 83 |
return decorator |
| 84 |
|
| 85 |
@staticmethod |
| 86 |
def _class_topological_sort(classes): |
| 87 |
""" |
| 88 |
A simple topological sort for classes. Takes an iterable of class objects |
| 89 |
and returns a list A of those classes, ordered such that A[X] is never a |
| 90 |
superclass of A[Y] for X < Y. |
| 91 |
|
| 92 |
This is an inefficient sort, but that's ok because classes are infrequently |
| 93 |
registered. It's more important that this be maintainable than fast. |
| 94 |
|
| 95 |
We can't use `.sort()` or `sorted()` with a custom `key` -- those assume |
| 96 |
a total ordering, which we don't have. |
| 97 |
""" |
| 98 |
unsorted, sorted_ = list(classes), [] |
| 99 |
while unsorted: |
| 100 |
head, tail = unsorted[0], unsorted[1:] |
| 101 |
|
| 102 |
# if head has no subclasses remaining, it can safely go in the list |
| 103 |
if not any(issubclass(x, head) for x in tail): |
| 104 |
sorted_.append(head) |
| 105 |
else: |
| 106 |
# move to the back -- head has to wait until all its subclasses |
| 107 |
# are sorted into the list |
| 108 |
tail.append(head) |
| 109 |
|
| 110 |
unsorted = tail |
| 111 |
|
| 112 |
# check that sort is valid |
| 113 |
for i, head in enumerate(sorted_): |
| 114 |
for after_head_value in sorted_[(i + 1):]: |
| 115 |
if issubclass(after_head_value, head): |
| 116 |
warn('Sorting classes produced an invalid ordering.\n' |
| 117 |
'In: {classes}\n' |
| 118 |
'Out: {sorted_}'.format(classes=classes, sorted_=sorted_)) |
| 119 |
return sorted_ |
| 120 |
|
| 121 |
|
| 122 |
insights_registry = InsightsSerializerRegistry() |