File: protocol.py

package info (click to toggle)
python-avro 1.10.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,624 kB
  • sloc: python: 11,437; xml: 4,061; sh: 752; java: 386; makefile: 21
file content (262 lines) | stat: -rw-r--r-- 8,695 bytes parent folder | download
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
#!/usr/bin/env python

##
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Protocol implementation."""

from __future__ import absolute_import, division, print_function

import hashlib
import json

import avro.schema

try:
    unicode
except NameError:
    unicode = str

try:
    basestring  # type: ignore
except NameError:
    basestring = (bytes, unicode)

#
# Constants
#

# TODO(hammer): confirmed 'fixed' with Doug
VALID_TYPE_SCHEMA_TYPES = ('enum', 'record', 'error', 'fixed')

#
# Exceptions
#


class ProtocolParseException(avro.schema.AvroException):
    pass

#
# Base Classes
#


class Protocol(object):
    """An application protocol."""

    def _parse_types(self, types, type_names):
        type_objects = []
        for type in types:
            type_object = avro.schema.make_avsc_object(type, type_names)
            if type_object.type not in VALID_TYPE_SCHEMA_TYPES:
                fail_msg = 'Type %s not an enum, fixed, record, or error.' % type
                raise ProtocolParseException(fail_msg)
            type_objects.append(type_object)
        return type_objects

    def _parse_messages(self, messages, names):
        message_objects = {}
        for name, body in messages.items():
            if name in message_objects:
                fail_msg = 'Message name "%s" repeated.' % name
                raise ProtocolParseException(fail_msg)
            try:
                request = body.get('request')
                response = body.get('response')
                errors = body.get('errors')
            except AttributeError:
                fail_msg = 'Message name "%s" has non-object body %s.' % (name, body)
                raise ProtocolParseException(fail_msg)
            message_objects[name] = Message(name, request, response, errors, names)
        return message_objects

    def __init__(self, name, namespace=None, types=None, messages=None):
        # Ensure valid ctor args
        if not name:
            fail_msg = 'Protocols must have a non-empty name.'
            raise ProtocolParseException(fail_msg)
        elif not isinstance(name, basestring):
            fail_msg = 'The name property must be a string.'
            raise ProtocolParseException(fail_msg)
        elif not (namespace is None or isinstance(namespace, basestring)):
            fail_msg = 'The namespace property must be a string.'
            raise ProtocolParseException(fail_msg)
        elif not (types is None or isinstance(types, list)):
            fail_msg = 'The types property must be a list.'
            raise ProtocolParseException(fail_msg)
        elif not (messages is None or callable(getattr(messages, 'get', None))):
            fail_msg = 'The messages property must be a JSON object.'
            raise ProtocolParseException(fail_msg)

        self._props = {}
        self.set_prop('name', name)
        type_names = avro.schema.Names()
        if namespace is not None:
            self.set_prop('namespace', namespace)
            type_names.default_namespace = namespace
        if types is not None:
            self.set_prop('types', self._parse_types(types, type_names))
        if messages is not None:
            self.set_prop('messages', self._parse_messages(messages, type_names))
        self._md5 = hashlib.md5(str(self).encode()).digest()

    # read-only properties
    @property
    def name(self):
        return self.get_prop('name')

    @property
    def namespace(self):
        return self.get_prop('namespace')

    @property
    def fullname(self):
        return avro.schema.Name(self.name, self.namespace, None).fullname

    @property
    def types(self):
        return self.get_prop('types')

    @property
    def types_dict(self):
        return {type.name: type for type in self.types}

    @property
    def messages(self):
        return self.get_prop('messages')

    @property
    def md5(self):
        return self._md5

    @property
    def props(self):
        return self._props

    # utility functions to manipulate properties dict
    def get_prop(self, key):
        return self.props.get(key)

    def set_prop(self, key, value):
        self.props[key] = value

    def to_json(self):
        to_dump = {}
        to_dump['protocol'] = self.name
        names = avro.schema.Names(default_namespace=self.namespace)
        if self.namespace:
            to_dump['namespace'] = self.namespace
        if self.types:
            to_dump['types'] = [t.to_json(names) for t in self.types]
        if self.messages:
            messages_dict = {}
            for name, body in self.messages.items():
                messages_dict[name] = body.to_json(names)
            to_dump['messages'] = messages_dict
        return to_dump

    def __str__(self):
        return json.dumps(self.to_json())

    def __eq__(self, that):
        to_cmp = json.loads(str(self))
        return to_cmp == json.loads(str(that))


class Message(object):
    """A Protocol message."""

    def _parse_request(self, request, names):
        if not isinstance(request, list):
            fail_msg = 'Request property not a list: %s' % request
            raise ProtocolParseException(fail_msg)
        return avro.schema.RecordSchema(None, None, request, names, 'request')

    def _parse_response(self, response, names):
        if isinstance(response, basestring) and names.has_name(response, None):
            return names.get_name(response, None)
        else:
            return avro.schema.make_avsc_object(response, names)

    def _parse_errors(self, errors, names):
        if not isinstance(errors, list):
            fail_msg = 'Errors property not a list: %s' % errors
            raise ProtocolParseException(fail_msg)
        errors_for_parsing = {'type': 'error_union', 'declared_errors': errors}
        return avro.schema.make_avsc_object(errors_for_parsing, names)

    def __init__(self, name, request, response, errors=None, names=None):
        self._name = name

        self._props = {}
        self.set_prop('request', self._parse_request(request, names))
        self.set_prop('response', self._parse_response(response, names))
        self.set_prop('errors', self._parse_errors(errors or [], names))

    # read-only properties
    name = property(lambda self: self._name)
    request = property(lambda self: self.get_prop('request'))
    response = property(lambda self: self.get_prop('response'))
    errors = property(lambda self: self.get_prop('errors'))
    props = property(lambda self: self._props)

    # utility functions to manipulate properties dict
    def get_prop(self, key):
        return self.props.get(key)

    def set_prop(self, key, value):
        self.props[key] = value

    def __str__(self):
        return json.dumps(self.to_json())

    def to_json(self, names=None):
        if names is None:
            names = avro.schema.Names()
        to_dump = {}
        to_dump['request'] = self.request.to_json(names)
        to_dump['response'] = self.response.to_json(names)
        if self.errors:
            to_dump['errors'] = self.errors.to_json(names)
        return to_dump

    def __eq__(self, that):
        return self.name == that.name and self.props == that.props


def make_avpr_object(json_data):
    """Build Avro Protocol from data parsed out of JSON string."""
    try:
        name = json_data.get('protocol')
        namespace = json_data.get('namespace')
        types = json_data.get('types')
        messages = json_data.get('messages')
    except AttributeError:
        raise ProtocolParseException('Not a JSON object: %s' % json_data)
    return Protocol(name, namespace, types, messages)


def parse(json_string):
    """Constructs the Protocol from the JSON text."""
    try:
        json_data = json.loads(json_string)
    except ValueError:
        raise ProtocolParseException('Error parsing JSON: %s' % json_string)

    # construct the Avro Protocol object
    return make_avpr_object(json_data)