├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── VERSION ├── datamountaineer ├── __init__.py └── schemaregistry │ ├── __init__.py │ ├── client │ ├── ClientError.py │ ├── SchemaRegistryClient.py │ └── __init__.py │ ├── serializers │ ├── MessageSerializer.py │ ├── Util.py │ └── __init__.py │ └── tests │ ├── __init__.py │ ├── adv_schema.avsc │ ├── basic_schema.avsc │ ├── data_gen.py │ ├── mock_registry.py │ ├── test_cached_client.py │ ├── test_message_serializer.py │ ├── test_registry.py │ └── test_util.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | .venv* 38 | *.ignore.py 39 | *.avro 40 | .idea/ 41 | 42 | # Testing 43 | .cache 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.5" 5 | - "3.6" 6 | 7 | # command to install dependencies 8 | install: 9 | - "pip install -r requirements.txt" 10 | 11 | # command to run tests 12 | script: py.test -v 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include VERSION 3 | include requirements.txt 4 | global-include *.avsc 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/datamountaineer/python-serializers.svg?branch=master)](https://travis-ci.org/datamountaineer/python-serializers) 2 | [![PyPI](https://img.shields.io/badge/PyPi-0.3-blue.svg)](https://pypi.python.org/pypi/datamountaineer-schemaregistry/0.3) 3 | 4 | # Python Schema Registry Client and Serializers/Deserializers 5 | 6 | A Python client used to interact with [Confluent](http://confluent.io/)'s 7 | [schema registry](https://github.com/confluentinc/schema-registry). Supports Python 3.6. This also works within a virtual env. 8 | 9 | The API is heavily based off of the existing Java API of [Confluent schema registry](https://github.com/confluentinc/schema-registry). 10 | 11 | The serializers/deserializers use [fastavro](https://github.com/tebeka/fastavro) for reading and writing by default. 12 | When one does not want to use `fastavro`, it can be disabled by providing `fast_avro=False` to the `MessageSerializer` constructor and Apache Avro's `avro` package will be used instead. 13 | 14 | # Installation 15 | 16 | Run `python setup.py install` from the source root. 17 | 18 | or via pip 19 | 20 | ``` 21 | pip3 install datamountaineer-schemaregistry 22 | ``` 23 | 24 | # Example Usage 25 | 26 | Setup 27 | 28 | ```python 29 | from datamountaineer.schemaregistry.client import SchemaRegistryClient 30 | from datamountaineer.schemaregistry.serializers import MessageSerializer, Util 31 | 32 | # Initialize the client 33 | client = SchemaRegistryClient(url='http://registry.host') 34 | ``` 35 | 36 | Schema operations 37 | 38 | ```python 39 | # register a schema for a subject 40 | schema_id = client.register('my_subject', avro_schema) 41 | 42 | # fetch a schema by ID 43 | avro_schema = client.get_by_id(schema_id) 44 | 45 | # get the latest schema info for a subject 46 | schema_id,avro_schema,schema_version = client.get_latest_schema('my_subject') 47 | 48 | # get the version of a schema 49 | schema_version = client.get_version('my_subject', avro_schema) 50 | 51 | # Compatibility tests 52 | is_compatible = client.test_compatibility('my_subject', another_schema) 53 | 54 | # One of NONE, FULL, FORWARD, BACKWARD 55 | new_level = client.update_compatibility('NONE','my_subject') 56 | current_level = client.get_compatibility('my_subject') 57 | ``` 58 | 59 | Encoding to write back to Kafka. Encoding by id is the most efficent as it avoids an extra trip to the Schema Registry to 60 | lookup the schema id. 61 | 62 | ```python 63 | # Message operations 64 | 65 | # encode a record to put onto kafka 66 | serializer = MessageSerializer(client) 67 | 68 | #build your avro 69 | record = get_obj_to_put_into_kafka() 70 | 71 | # use the schema id directly 72 | encoded = serializer.encode_record_with_schema_id(schema_id, record) 73 | ``` 74 | 75 | Encode by schema only. 76 | 77 | ```python 78 | # use an existing schema and topic 79 | # this will register the schema to the right subject based 80 | # on the topic name and then serialize 81 | encoded = serializer.encode_record_with_schema('my_topic', avro_schema, record) 82 | ``` 83 | 84 | Reading messages 85 | 86 | ```python 87 | # decode a message from kafka 88 | message = get_message_from_kafka() 89 | decoded_object = serializer.decode_message(message) 90 | ``` 91 | # Release Notes 92 | 93 | **0.3** 94 | * Testing, setup, and import improvements from PR #4 95 | 96 | # Testing 97 | 98 | ``` 99 | pip3 install pytest mock 100 | py.test -s -rxs -v 101 | ``` 102 | 103 | 104 | 105 | # License 106 | 107 | The project is licensed under the Apache 2 license. 108 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.3.1 2 | -------------------------------------------------------------------------------- /datamountaineer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lensesio/python-serializers/da7e92d4604d1d975f85157cc01d5d1d34899b2c/datamountaineer/__init__.py -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Entry point for schema registry module 3 | """ 4 | __version__ = (2, 0) 5 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/client/ClientError.py: -------------------------------------------------------------------------------- 1 | VALID_LEVELS = ['NONE', 'FULL', 'FORWARD', 'BACKWARD'] 2 | 3 | 4 | class ClientError(Exception, object): 5 | 6 | """Error thrown by Schema Registry clients""" 7 | 8 | def __init__(self, message, http_code=-1): 9 | self.message = message 10 | self.http_code = http_code 11 | super(ClientError, self).__init__(self.__str__()) 12 | 13 | def __repr__(self): 14 | return "ClientError(error={error})".format(error=self.message) 15 | 16 | def __str__(self): 17 | return self.message 18 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/client/SchemaRegistryClient.py: -------------------------------------------------------------------------------- 1 | import urllib.request 2 | import urllib.error 3 | import urllib.parse 4 | import json 5 | import sys 6 | 7 | from datamountaineer.schemaregistry.client.ClientError import * 8 | from ..serializers import Util 9 | 10 | # Common accept header sent 11 | ACCEPT_HDR = "application/vnd.schemaregistry.v1+json, application/vnd.schemaregistry+json, application/json" 12 | 13 | 14 | class SchemaRegistryClient(object): 15 | 16 | """ 17 | A client that talks to a Schema Registry over HTTP 18 | 19 | See http://datamountaineer.io/docs/current/schema-registry/docs/intro.html 20 | 21 | Errors communicating to the server will result in a ClientError being raised. 22 | """ 23 | 24 | def __init__(self, url): 25 | """Construct a client by passing in the base URL of the schema registry server""" 26 | 27 | self.url = url.rstrip('/') 28 | self.id_to_schema = {} 29 | 30 | def _send_request(self, url, method='GET', body=None, headers=None): 31 | if body: 32 | body = json.dumps(body).encode('utf-8') 33 | 34 | new_req = urllib.request.Request(url, data=body) 35 | # must be callable 36 | new_req.get_method = lambda: method 37 | # set the accept header 38 | new_req.add_header("Accept", ACCEPT_HDR) 39 | if body: 40 | new_req.add_header("Content-Length", str(len(body))) 41 | new_req.add_header("Content-Type", "application/json") 42 | # add additional headers if present 43 | if headers: 44 | for header_name in headers: 45 | new_req.add_header(header_name, headers[header_name]) 46 | try: 47 | response = urllib.request.urlopen(new_req) 48 | # read response 49 | result = json.loads(response.read().decode('utf-8')) 50 | # build meta with headers as a dict 51 | meta = response.info() 52 | # http code 53 | code = response.getcode() 54 | # return result + meta tuple 55 | return (result, meta, code) 56 | except urllib.request.HTTPError as e: 57 | code = e.code 58 | result = json.loads(e.read().decode('utf-8')) 59 | message = "HTTP Error (%d) from schema registry: %s %d" % (code, 60 | result.get('message'), 61 | result.get('error_code')) 62 | raise ClientError(message, code) 63 | except ClientError as e: 64 | raise e 65 | except: 66 | msg = "An unexpected error occurred: %s" % (str(sys.exc_info()[1])) 67 | raise ClientError(msg) 68 | 69 | def _cache_schema(self, schema, schema_id): 70 | # overwrite, not much performance impact, as shouldn't be happening often 71 | self.id_to_schema[schema_id] = schema 72 | 73 | def _set_subject(self, subject, is_key=False): 74 | subject_suffix = ('-key' if is_key else '-value') 75 | # get the latest schema for the subject 76 | if (subject.endswith("-value") or subject.endswith("-key")): 77 | return subject 78 | else: 79 | return (subject + subject_suffix) 80 | 81 | def register(self, subject, avro_schema, is_key=False): 82 | """ 83 | Register a schema with the registry under the given subject 84 | and receive a schema id. 85 | 86 | avro_schema must be a parsed schema from the python avro library 87 | 88 | """ 89 | subject = self._set_subject(subject, is_key) 90 | 91 | url = '/'.join([self.url, 'subjects', subject, 'versions']) 92 | body = { 'schema' : json.dumps(avro_schema.to_json()) } 93 | result, meta, code = self._send_request(url, method='POST', body=body) 94 | schema_id = result['id'] 95 | self._cache_schema(avro_schema, schema_id) 96 | return schema_id 97 | 98 | def get_by_id(self, schema_id): 99 | """Retrieve a parsed avro schema by id or None if not found""" 100 | 101 | if schema_id in self.id_to_schema: 102 | return self.id_to_schema[schema_id] 103 | 104 | url = '/'.join([self.url, 'schemas', 'ids', str(schema_id)]) 105 | try: 106 | result, meta, code = self._send_request(url) 107 | except ClientError as e: 108 | if e.http_code == 404: 109 | return None 110 | else: 111 | raise e 112 | else: 113 | # need to parse the schema 114 | schema_str = result.get("schema") 115 | try: 116 | result = Util.parse_schema_from_string(schema_str) 117 | # cache it 118 | self._cache_schema(result, schema_id) 119 | return result 120 | except: 121 | # bad schema - should not happen 122 | raise ClientError("Received bad schema from registry.") 123 | 124 | def get_latest_schema(self, subject, is_key=False): 125 | """ 126 | Return the latest 3-tuple of: 127 | (the schema id, the parsed avro schema, the schema version) 128 | for a particular subject. 129 | 130 | This call always contacts the registry. 131 | 132 | If the subject is not found, (None,None,None) is returned. 133 | """ 134 | subject = self._set_subject(subject, is_key) 135 | 136 | url = '/'.join([self.url, 'subjects', subject, 'versions', 'latest']) 137 | try: 138 | result, meta, code = self._send_request(url) 139 | except ClientError as e: 140 | if e.http_code == 404: 141 | return (None, None, None) 142 | raise e 143 | 144 | schema_id = result['id'] 145 | version = result['version'] 146 | 147 | if schema_id in self.id_to_schema: 148 | schema = self.id_to_schema[schema_id] 149 | else: 150 | try: 151 | schema = Util.parse_schema_from_string(result['schema']) 152 | except: 153 | # bad schema - should not happen 154 | raise ClientError("Received bad schema from registry.") 155 | 156 | self._cache_schema(schema, schema_id) 157 | return (schema_id, schema, version) 158 | 159 | def list_all(self): 160 | """ 161 | Get a list of all the key and value schemas in the registry. 162 | """ 163 | keys = [] 164 | values = [] 165 | 166 | url = '/'.join([self.url, 'subjects']) 167 | try: 168 | result, meta, code = self._send_request(url) 169 | except ClientError as e: 170 | if e.http_code == 404: 171 | return (keys, values) 172 | raise e 173 | 174 | for subject in result: 175 | m = re.match("(.*)-(value|key)$", subject) 176 | if m: 177 | if m.groups()[1] == 'key': 178 | keys.append(m.groups()[0]) 179 | else: 180 | values.append(m.groups()[0]) 181 | 182 | return (keys, values) 183 | 184 | def get_version(self, subject, avro_schema, is_key=False): 185 | """ 186 | Get the version of a schema for a given subject. 187 | 188 | Returns -1 if not found. 189 | """ 190 | subject = self._set_subject(subject, is_key) 191 | url = '/'.join([self.url, 'subjects', subject]) 192 | body = { 'schema' : json.dumps(avro_schema.to_json()) } 193 | try: 194 | result, meta, code = self._send_request(url, method='POST', body=body) 195 | schema_id = result['id'] 196 | version = result['version'] 197 | self._cache_schema(avro_schema, schema_id) 198 | return version 199 | except ClientError as e: 200 | if e.http_code == 404: 201 | return -1 202 | else: 203 | raise e 204 | 205 | def test_compatibility(self, subject, avro_schema, version='latest', is_key=False): 206 | """ 207 | Test the compatibility of a candidate parsed schema for a given subject. 208 | 209 | By default the latest version is checked against. 210 | """ 211 | subject = self._set_subject(subject, is_key) 212 | url = '/'.join([self.url, 'compatibility', 'subjects', subject, 213 | 'versions', str(version)]) 214 | body = { 'schema' : json.dumps(avro_schema.to_json()) } 215 | try: 216 | result, meta, code = self._send_request(url, method='POST', body=body) 217 | return result.get('is_compatible') 218 | except: 219 | return False 220 | 221 | def update_compatibility(self, level, subject=None, is_key=False): 222 | """ 223 | Update the compatibility level for a subject. Level must be one of: 224 | 225 | 'NONE','FULL','FORWARD', or 'BACKWARD' 226 | """ 227 | subject = self._set_subject(subject, is_key) 228 | 229 | if level not in VALID_LEVELS: 230 | raise ClientError("Invalid level specified: %s" % (str(level))) 231 | 232 | url = '/'.join([self.url, 'config']) 233 | 234 | if subject: 235 | url += '/' + subject 236 | 237 | body = { "compatibility" : level } 238 | result, meta, code = self._send_request(url, method='PUT', body=body) 239 | return result['compatibility'] 240 | 241 | def get_compatibility(self, subject=None, is_key=False): 242 | """ 243 | Get the current compatibility level for a subject. Result will be one of: 244 | 245 | 'NONE','FULL','FORWARD', or 'BACKWARD' 246 | """ 247 | subject = self._set_subject(subject, is_key) 248 | 249 | url = '/'.join([self.url, 'config']) 250 | 251 | if subject: 252 | url += '/' + subject 253 | 254 | result, meta, code = self._send_request(url) 255 | compatibility = result.get('compatibility', None) 256 | if not compatibility: 257 | compatbility = result.get('compatibilityLevel') 258 | 259 | return compatbility 260 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/client/__init__.py: -------------------------------------------------------------------------------- 1 | from .SchemaRegistryClient import * 2 | from .ClientError import * 3 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/serializers/MessageSerializer.py: -------------------------------------------------------------------------------- 1 | try: 2 | from fastavro.reader import read_data 3 | from fastavro import dump 4 | HAS_FAST = True 5 | except: 6 | HAS_FAST = False 7 | 8 | import io 9 | import struct 10 | import avro.io 11 | 12 | from datamountaineer.schemaregistry.serializers import SerializerError 13 | from datamountaineer.schemaregistry.client import ClientError 14 | 15 | MAGIC_BYTE = 0 16 | 17 | 18 | class ContextBytesIO(io.BytesIO): 19 | 20 | """ 21 | Wrapper to allow use of BytesIO via 'with' constructs. 22 | """ 23 | 24 | def __enter__(self): 25 | return self 26 | 27 | def __exit__(self, *args): 28 | self.close() 29 | return False 30 | 31 | 32 | class MessageSerializer(object): 33 | 34 | """ 35 | A helper class that can serialize and deserialize messages 36 | that need to be encoded or decoded using the schema registry. 37 | 38 | All encode_* methods return a buffer that can be sent to kafka. 39 | All decode_* methods expect a buffer received from kafka. 40 | """ 41 | 42 | def __init__(self, registry_client, fast_avro=True): 43 | self.registry_client = registry_client 44 | self.id_to_decoder_func = { } 45 | self.id_to_writers = { } 46 | self.fast_avro = HAS_FAST 47 | 48 | def _set_subject(self, subject, is_key=False): 49 | subject_suffix = ('-key' if is_key else '-value') 50 | # get the latest schema for the subject 51 | return (subject + subject_suffix) 52 | 53 | def encode_record_with_schema(self, topic, schema, record, is_key=False): 54 | """ 55 | Given a parsed avro schema, encode a record for the given topic. The 56 | record is expected to be a dictionary. 57 | 58 | The schema is registered with the subject of 'topic-value' 59 | """ 60 | if not isinstance(record, dict): 61 | raise SerializerError("record must be a dictionary") 62 | 63 | subject = self._set_subject(topic, is_key) 64 | 65 | # register it 66 | try: 67 | schema_id = self.registry_client.register(subject, schema) 68 | except: 69 | schema_id = None 70 | 71 | if not schema_id: 72 | message = "Unable to retrieve schema id for subject %s" % (subject) 73 | raise SerializerError(message) 74 | 75 | if not self.fast_avro: 76 | self.id_to_writers[schema_id] = avro.io.DatumWriter(schema) 77 | 78 | return self.encode_record_with_schema_id(schema_id, schema, record) 79 | 80 | # subject = topic + suffix 81 | def encode_record_for_topic(self, topic, record, is_key=False): 82 | """ 83 | Encode a record for a given topic. 84 | 85 | This is expensive as it fetches the latest schema for a given topic. 86 | """ 87 | if not isinstance(record, dict): 88 | raise SerializerError("record must be a dictionary") 89 | 90 | subject = self._set_subject(topic, is_key) 91 | 92 | try: 93 | schema_id, schema, version = self.registry_client.get_latest_schema(subject) 94 | except ClientError as e: 95 | message = "Unable to retrieve schema id for subject %s" % (subject) 96 | raise SerializerError(message) 97 | else: 98 | if not self.fast_avro: 99 | self.id_to_writers[schema_id] = avro.io.DatumWriter(schema) 100 | return self.encode_record_with_schema_id(schema_id, schema, record) 101 | 102 | def encode_record_with_schema_id(self, schema_id, schema, record): 103 | """ 104 | Encode a record with a given schema id. The record must 105 | be a python dictionary. 106 | """ 107 | if not isinstance(record, dict): 108 | raise SerializerError("record must be a dictionary") 109 | 110 | if not self.fast_avro: 111 | if schema_id not in self.id_to_writers: 112 | # get the writer + schema 113 | try: 114 | schema = self.registry_client.get_by_id(schema_id) 115 | if not schema: 116 | raise SerializerError("Schema does not exist") 117 | self.id_to_writers[schema_id] = avro.io.DatumWriter(schema) 118 | except ClientError as e: 119 | raise SerializerError("Error fetching schema from registry") 120 | 121 | with ContextBytesIO() as outf: 122 | # write the header 123 | # magic byte 124 | outf.write(struct.pack('b', MAGIC_BYTE)) 125 | # write the schema ID in network byte order (big end) 126 | outf.write(struct.pack('>I', schema_id)) 127 | if self.fast_avro: 128 | dump(outf, record, schema.to_json()) 129 | else: 130 | writer = self.id_to_writers[schema_id] 131 | encoder = avro.io.BinaryEncoder(outf) 132 | writer.write(record, encoder) 133 | return outf.getvalue() 134 | 135 | def get_schema(self, schema_id): 136 | # fetch from schema reg 137 | try: 138 | # first call will cache in the client 139 | schema = self.registry_client.get_by_id(schema_id) 140 | except: 141 | schema = None 142 | 143 | if not schema: 144 | err = "unable to fetch schema with id %d" % (schema_id) 145 | raise SerializerError(err) 146 | 147 | return schema 148 | 149 | # Decoder support 150 | def _get_decoder_func(self, schema_id, payload): 151 | if schema_id in self.id_to_decoder_func: 152 | return self.id_to_decoder_func[schema_id] 153 | 154 | schema = self.get_schema(schema_id) 155 | 156 | curr_pos = payload.tell() 157 | 158 | if self.fast_avro: 159 | # try to use fast avro 160 | try: 161 | schema_dict = schema.to_json() 162 | payload.seek(curr_pos) 163 | decoder_func = lambda p: read_data(p, schema_dict) 164 | self.id_to_decoder_func[schema_id] = decoder_func 165 | return self.id_to_decoder_func[schema_id] 166 | except: 167 | payload.seek(curr_pos) 168 | pass 169 | 170 | avro_reader = avro.io.DatumReader(schema) 171 | 172 | def decoder(p): 173 | bin_decoder = avro.io.BinaryDecoder(p) 174 | return avro_reader.read(bin_decoder) 175 | 176 | self.id_to_decoder_func[schema_id] = decoder 177 | return self.id_to_decoder_func[schema_id] 178 | 179 | def decode_message(self, message): 180 | """ 181 | Decode a message from kafka that has been encoded for use with 182 | the schema registry. 183 | """ 184 | if len(message) <= 5: 185 | raise SerializerError("message is too small to decode") 186 | 187 | with ContextBytesIO(message) as payload: 188 | magic, schema_id = struct.unpack('>bI', payload.read(5)) 189 | if magic != MAGIC_BYTE: 190 | raise SerializerError("message does not start with magic byte") 191 | decoder_func = self._get_decoder_func(schema_id, payload) 192 | return decoder_func(payload) 193 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/serializers/Util.py: -------------------------------------------------------------------------------- 1 | """ 2 | Basic utilities for handling avro schemas 3 | """ 4 | from avro import schema 5 | 6 | 7 | def parse_schema_from_string(schema_str): 8 | """Parse a schema given a schema string""" 9 | return schema.Parse(schema_str) 10 | 11 | 12 | def parse_schema_from_file(schema_path): 13 | """Parse a schema from a file path""" 14 | with open(schema_path) as f: 15 | return parse_schema_from_string(f.read()) 16 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/serializers/__init__.py: -------------------------------------------------------------------------------- 1 | class SerializerError(Exception): 2 | 3 | """Generic error from serializer package""" 4 | 5 | def __init__(self, message): 6 | self.message = message 7 | 8 | def __repr__(self): 9 | return 'SerializerError(error={error})'.format(error=self.message) 10 | 11 | def __str__(self): 12 | return self.message 13 | 14 | from .MessageSerializer import * 15 | from .Util import * 16 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lensesio/python-serializers/da7e92d4604d1d975f85157cc01d5d1d34899b2c/datamountaineer/schemaregistry/tests/__init__.py -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/adv_schema.avsc: -------------------------------------------------------------------------------- 1 | { 2 | "name": "advanced", 3 | "type": "record", 4 | "doc": "advanced schema for tests", 5 | "namespace": "python.test.advanced", 6 | "fields": [ 7 | { 8 | "name": "number", 9 | "doc": "age", 10 | "type": [ 11 | "long", 12 | "null" 13 | ] 14 | }, 15 | { 16 | "name": "name", 17 | "doc": "a name", 18 | "type": [ 19 | "string" 20 | ] 21 | }, 22 | { 23 | "name": "friends", 24 | "doc": "friends", 25 | "type" : { 26 | "type": "map", 27 | "values" : { 28 | "name": "basicPerson", 29 | "type": "record", 30 | "namespace": "python.test.advanced", 31 | "fields": [ 32 | { 33 | "name": "number", 34 | "doc": "friend age", 35 | "type": [ 36 | "long", 37 | "null" 38 | ] 39 | }, 40 | { 41 | "name": "name", 42 | "doc": "friend name", 43 | "type": [ 44 | "string" 45 | ] 46 | } 47 | ] 48 | } 49 | } 50 | } 51 | ] 52 | } 53 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/basic_schema.avsc: -------------------------------------------------------------------------------- 1 | { 2 | "name": "basicPerson", 3 | "type": "record", 4 | "namespace": "python.test.advanced", 5 | "fields": [ 6 | { 7 | "name": "number", 8 | "doc": "friend age", 9 | "type": [ 10 | "long", 11 | "null" 12 | ] 13 | }, 14 | { 15 | "name": "name", 16 | "doc": "friend name", 17 | "type": [ 18 | "string" 19 | ] 20 | } 21 | ] 22 | } -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/data_gen.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import os.path 4 | 5 | NAMES = ['stefan', 'melanie', 'nick', 'darrel', 'kent', 'simon'] 6 | AGES = list(range(1, 10)) + [None] 7 | 8 | 9 | def get_schema_path(fname): 10 | dname = os.path.dirname(os.path.realpath(__file__)) 11 | return os.path.join(dname, fname) 12 | 13 | 14 | def load_schema_file(fname): 15 | fname = get_schema_path(fname) 16 | with open(fname) as f: 17 | return f.read() 18 | 19 | BASIC_SCHEMA = load_schema_file('basic_schema.avsc') 20 | 21 | 22 | def create_basic_item(i): 23 | return { 24 | 'name' : random.choice(NAMES) + '-' + str(i), 25 | 'number' : random.choice(AGES) 26 | } 27 | 28 | BASIC_ITEMS = map(create_basic_item, range(1, 20)) 29 | 30 | ADVANCED_SCHEMA = load_schema_file('adv_schema.avsc') 31 | 32 | 33 | def create_adv_item(i): 34 | friends = map(create_basic_item, range(1, 3)) 35 | basic = create_basic_item(i) 36 | basic['friends'] = dict(map(lambda bi: (bi['name'], bi), friends)) 37 | return basic 38 | 39 | ADVANCED_ITEMS = map(create_adv_item, range(1, 20)) 40 | 41 | from avro import schema 42 | from avro.datafile import DataFileReader, DataFileWriter 43 | from avro.io import DatumReader, DatumWriter 44 | import json 45 | 46 | 47 | def _write_items(base_name, schema_str, items): 48 | avro_schema = schema.parse(schema_str) 49 | avro_file = base_name + '.avro' 50 | with DataFileWriter(open(avro_file, "w"), DatumWriter(), avro_schema) as writer: 51 | for i in items: 52 | writer.append(i) 53 | writer.close 54 | return (avro_file) 55 | 56 | 57 | def write_basic_items(base_name): 58 | return _write_items(base_name, BASIC_SCHEMA, BASIC_ITEMS) 59 | 60 | 61 | def write_advanced_items(base_name): 62 | return _write_items(base_name, ADVANCED_SCHEMA, ADVANCED_ITEMS) 63 | 64 | 65 | def cleanup(files): 66 | for f in files: 67 | try: 68 | os.remove(f) 69 | except OSError: 70 | pass 71 | 72 | if __name__ == "__main__": 73 | write_advanced_items("advanced") 74 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/mock_registry.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | import http.server 4 | from threading import Thread 5 | 6 | from datamountaineer.schemaregistry.tests import data_gen 7 | 8 | from datamountaineer.schemaregistry.serializers import Util 9 | 10 | 11 | class ReqHandler(http.server.BaseHTTPRequestHandler): 12 | protocol_version = "HTTP/1.0" 13 | 14 | def do_GET(self): 15 | self.server._run_routes(self) 16 | 17 | def do_POST(self): 18 | self.server._run_routes(self) 19 | 20 | def log_message(self, format, *args): 21 | pass 22 | 23 | 24 | class MockServer(http.server.HTTPServer, object): 25 | 26 | def __init__(self, *args, **kwargs): 27 | super(MockServer, self).__init__(*args, **kwargs) 28 | self.counts = { } 29 | self.schema_cache = { } 30 | self.all_routes = { 31 | 'GET' : [ 32 | (r"/schemas/ids/(\d+)", 'get_schema_by_id'), 33 | (r"/subjects/(\w+-\w+)/versions/latest", 'get_latest') 34 | ], 35 | 'POST' : [ 36 | (r"/subjects/(\w+-\w+)/versions", 'register'), 37 | (r"/subjects/(\w+-\w+)", 'get_version') 38 | ] 39 | } 40 | self.schema = data_gen.load_schema_file('basic_schema.avsc') 41 | 42 | def _send_response(self, resp, status, body): 43 | resp.send_response(status) 44 | resp.send_header("Content-Type", "application/json") 45 | resp.end_headers() 46 | resp.wfile.write(json.dumps(body).encode('utf-8')) 47 | 48 | def _create_error(self, msg, status=400, err_code=1): 49 | return (status, { 50 | "error_code" : err_code, 51 | "message" : msg 52 | }) 53 | 54 | def _run_routes(self, req): 55 | self.add_count((req.command, req.path)) 56 | routes = self.all_routes.get(req.command, []) 57 | for r in routes: 58 | m = re.match(r[0], req.path) 59 | if m: 60 | func = getattr(self, r[1]) 61 | status, body = func(req, m.groups()) 62 | ret = self._send_response(req, status, body) 63 | return ret 64 | 65 | # here means we got a bad req 66 | status, body = self._create_error("bad path specified") 67 | self._send_response(req, status, body) 68 | 69 | def get_schema_by_id(self, req, groups): 70 | result = { 71 | "schema" : self.schema 72 | } 73 | return (200, result) 74 | 75 | def _get_identity_schema(self, avro_schema): 76 | return json.dumps(avro_schema.to_json()) 77 | 78 | def _get_schema_from_body(self, req): 79 | length = req.headers['content-length'] 80 | data = req.rfile.read(int(length)) 81 | data = json.loads(data.decode('utf-8')) 82 | schema = data.get("schema", None) 83 | 84 | if not schema: 85 | return None 86 | try: 87 | avro_schema = Util.parse_schema_from_string(schema) 88 | return self._get_identity_schema(avro_schema) 89 | except: 90 | return None 91 | 92 | def register(self, req, groups): 93 | schema_id = 1 94 | return (200, {'id' : schema_id }) 95 | 96 | def get_version(self, req, groups): 97 | avro_schema = self._get_schema_from_body(req) 98 | 99 | if not avro_schema: 100 | return self._create_error("Invalid avro schema", 422, 42201) 101 | subject = groups[0] 102 | version = 1 103 | if version == -1: 104 | return self._create_error("Not found", 404) 105 | schema_id = 1 106 | 107 | result = { 108 | "schema" : avro_schema, 109 | "subject" : subject, 110 | "id" : schema_id, 111 | "version" : version 112 | } 113 | return (200, result) 114 | 115 | def get_latest(self, req, groups): 116 | subject = groups[0] 117 | result = { 118 | "schema" : self.schema, 119 | "subject" : subject, 120 | "id" : 1, 121 | "version" : 1 122 | } 123 | return (200, result) 124 | 125 | def add_count(self, path): 126 | if path not in self.counts: 127 | self.counts[path] = 0 128 | self.counts[path] += 1 129 | 130 | 131 | class ServerThread(Thread): 132 | 133 | def __init__(self, port): 134 | Thread.__init__(self) 135 | self.server = None 136 | self.port = port 137 | 138 | def run(self): 139 | self.server = MockServer(('127.0.0.1', self.port), ReqHandler) 140 | self.server.serve_forever() 141 | 142 | def shutdown(self): 143 | if self.server: 144 | self.server.shutdown() 145 | self.server.socket.close() 146 | 147 | 148 | if __name__ == '__main__': 149 | s = ServerThread(9001) 150 | s.start() 151 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/test_cached_client.py: -------------------------------------------------------------------------------- 1 | import time 2 | import unittest 3 | 4 | from datamountaineer.schemaregistry.tests import data_gen 5 | from datamountaineer.schemaregistry.tests import mock_registry 6 | 7 | from datamountaineer.schemaregistry.client import SchemaRegistryClient 8 | from datamountaineer.schemaregistry.serializers import Util 9 | 10 | 11 | class TestCacheSchemaRegistryClient(unittest.TestCase): 12 | 13 | def setUp(self): 14 | self.server = mock_registry.ServerThread(9001) 15 | self.server.start() 16 | time.sleep(1) 17 | self.client = SchemaRegistryClient('http://127.0.0.1:9001') 18 | 19 | def tearDown(self): 20 | self.server.shutdown() 21 | self.server.join() 22 | 23 | def assertLatest(self, meta_tuple, sid, schema, version): 24 | self.assertNotEqual(sid, -1) 25 | self.assertNotEqual(version, -1) 26 | self.assertEqual(meta_tuple[0], sid) 27 | self.assertEqual(meta_tuple[1], schema) 28 | self.assertEqual(meta_tuple[2], version) 29 | 30 | def test_register(self): 31 | parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA) 32 | client = self.client 33 | schema_id = client.register('test', parsed) 34 | self.assertTrue(schema_id == 1) 35 | self.assertEqual(len(client.id_to_schema), 1) 36 | 37 | def test_multi_subject_register(self): 38 | parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA) 39 | client = self.client 40 | schema_id = client.register('test', parsed) 41 | self.assertTrue(schema_id == 1) 42 | 43 | # register again under different subject 44 | dupe_id = client.register('other', parsed) 45 | self.assertEqual(schema_id, dupe_id) 46 | self.assertEqual(len(client.id_to_schema), 1) 47 | 48 | def test_dupe_register(self): 49 | parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA) 50 | subject = 'test' 51 | client = self.client 52 | schema_id = client.register(subject, parsed) 53 | self.assertTrue(schema_id == 1) 54 | latest = client.get_latest_schema(subject) 55 | 56 | # register again under same subject 57 | dupe_id = client.register(subject, parsed) 58 | self.assertEqual(schema_id, dupe_id) 59 | dupe_latest = client.get_latest_schema(subject) 60 | self.assertEqual(latest, dupe_latest) 61 | 62 | def test_getters(self): 63 | parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA) 64 | client = self.client 65 | subject = 'test' 66 | version = client.get_version(subject, parsed) 67 | self.assertEqual(version, 1) 68 | schema = client.get_by_id(1) 69 | # self.assertEqual(schema, parsed) 70 | latest = client.get_latest_schema(subject) 71 | self.assertEqual(latest, (1, schema, 1)) 72 | 73 | # register 74 | schema_id = client.register(subject, parsed) 75 | latest = client.get_latest_schema(subject) 76 | version = client.get_version(subject, parsed) 77 | self.assertLatest(latest, schema_id, parsed, version) 78 | 79 | fetched = client.get_by_id(schema_id) 80 | self.assertEqual(fetched, parsed) 81 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/test_message_serializer.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import unittest 3 | 4 | from datamountaineer.schemaregistry.tests import data_gen 5 | from datamountaineer.schemaregistry.client import SchemaRegistryClient 6 | from datamountaineer.schemaregistry.serializers import (MessageSerializer, 7 | Util, 8 | SerializerError) 9 | 10 | from mock import MagicMock 11 | 12 | 13 | class TestMessageSerializer(unittest.TestCase): 14 | 15 | def setUp(self): 16 | self.subject = 'test_adv' 17 | self.schema = Util.parse_schema_from_string(data_gen.ADVANCED_SCHEMA) 18 | 19 | self.client = SchemaRegistryClient('http://127.0.0.1:9001') 20 | self.client.register = MagicMock(return_value=1) 21 | self.client.get_by_id = MagicMock(retrun_value=self.schema) 22 | self.client.get_latest_schema = MagicMock(return_value=(1, self.schema, 1)) 23 | self.client.get_version = MagicMock(return_value=1) 24 | self.ms = MessageSerializer(self.client, fast_avro=True) 25 | self.msslow = MessageSerializer(self.client, fast_avro=False) 26 | self.ms.get_schema = MagicMock(return_value=self.schema) 27 | self.msslow.get_schema = MagicMock(return_value=self.schema) 28 | 29 | def assertMessageIsSame(self, message, expected, schema_id): 30 | self.assertTrue(message) 31 | self.assertTrue(len(message) > 5) 32 | magic, sid = struct.unpack('>bI', message[0:5]) 33 | self.assertEqual(magic, 0) 34 | self.assertEqual(sid, schema_id) 35 | decoded = self.ms.decode_message(message) 36 | self.assertTrue(decoded) 37 | self.assertEqual(decoded, expected) 38 | decoded = self.msslow.decode_message(message) 39 | self.assertTrue(decoded) 40 | self.assertEqual(decoded, expected) 41 | 42 | def test_encode_with_schema_id(self): 43 | adv_schema_id = self.client.register(self.subject, self.schema) 44 | records = data_gen.ADVANCED_ITEMS 45 | for record in records: 46 | message = self.ms.encode_record_with_schema_id(adv_schema_id, self.schema, record) 47 | self.assertMessageIsSame(message, record, adv_schema_id) 48 | message = self.msslow.encode_record_with_schema_id(adv_schema_id, self.schema, record) 49 | self.assertMessageIsSame(message, record, adv_schema_id) 50 | 51 | def test_encode_record_for_topic(self): 52 | schema_id = self.client.register(self.subject, self.schema) 53 | records = data_gen.ADVANCED_ITEMS 54 | for record in records: 55 | message = self.ms.encode_record_for_topic(self.subject, record) 56 | self.assertMessageIsSame(message, record, schema_id) 57 | message = self.msslow.encode_record_for_topic(self.subject, record) 58 | self.assertMessageIsSame(message, record, schema_id) 59 | 60 | def test_encode_record_with_schema(self): 61 | schema_id = self.client.register(self.subject, self.schema) 62 | records = data_gen.ADVANCED_ITEMS 63 | for record in records: 64 | message = self.ms.encode_record_with_schema(self.subject, self.schema, record) 65 | self.assertMessageIsSame(message, record, schema_id) 66 | message = self.msslow.encode_record_with_schema(self.subject, self.schema, record) 67 | self.assertMessageIsSame(message, record, schema_id) 68 | 69 | def test_decode_record(self): 70 | records = data_gen.ADVANCED_ITEMS 71 | for record in records: 72 | encoded = self.ms.encode_record_with_schema(self.subject, self.schema, record) 73 | decoded = self.ms.decode_message(encoded) 74 | self.assertEqual(decoded, record) 75 | encoded = self.msslow.encode_record_with_schema(self.subject, self.schema, record) 76 | decoded = self.msslow.decode_message(encoded) 77 | self.assertEqual(decoded, record) 78 | 79 | def test_bad_input(self): 80 | adv_schema_id = self.client.register(self.subject, self.schema) 81 | 82 | with self.assertRaises(SerializerError): 83 | self.ms.encode_record_with_schema_id(adv_schema_id, self.schema, 'notadict') 84 | 85 | with self.assertRaises(SerializerError): 86 | self.ms.encode_record_with_schema_id(adv_schema_id, self.schema, ['notadict']) 87 | 88 | with self.assertRaises(SerializerError): 89 | self.ms.encode_record_for_topic(self.subject, 'notadict') 90 | 91 | with self.assertRaises(SerializerError): 92 | self.ms.encode_record_for_topic(self.subject, ['notadict']) 93 | 94 | with self.assertRaises(SerializerError): 95 | self.ms.encode_record_with_schema(self.subject, self.schema, 'notadict') 96 | 97 | with self.assertRaises(SerializerError): 98 | self.ms.encode_record_with_schema(self.subject, self.schema, ['notadict']) 99 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/test_registry.py: -------------------------------------------------------------------------------- 1 | # from bottle import route, response 2 | # import setup_test_path 3 | # import data_gen 4 | # import json 5 | # from patched_bottle_daemon import * 6 | # 7 | # schema_cache = {} 8 | # schema = data_gen.load_schema_file('basic_schema.avsc') 9 | # 10 | # def _send_response(resp, status, body): 11 | # resp.status = status 12 | # resp.content_type = "application/json" 13 | # return json.dumps(body).encode('utf-8') 14 | # 15 | # @route('/subjects//versions/latest', method='GET') 16 | # def get_latest(subject): 17 | # result = { 18 | # "schema" : schema, 19 | # "subject" : subject, 20 | # "id" : 1, 21 | # "version" : 1 22 | # } 23 | # resp = _send_response(response, 200, result) 24 | # return resp 25 | # 26 | # @route('/schemas/ids/', method='GET') 27 | # def get_schema_by_id(id): 28 | # result = { 29 | # "schema": schema 30 | # } 31 | # resp = _send_response(response, 200, result) 32 | # return resp 33 | # 34 | # @route('/subjects//versions', method='POST') 35 | # def register(schema): 36 | # schema_id = 1 37 | # resp = _send_response(response, 200, {'id' : schema_id }) 38 | # return resp 39 | # 40 | # @route('/subjects/', method='POST') 41 | # def get_version(subject): 42 | # result = { 43 | # "schema" : schema, 44 | # "subject" : subject, 45 | # "id" : 1, 46 | # "version" : 1 47 | # } 48 | # resp = _send_response(response, 200, result) 49 | # return resp 50 | # 51 | # class Server(): 52 | # 53 | # def start(self): 54 | # bottle_daemon_run(cmd='Start') 55 | # 56 | # def stop(self, cmd): 57 | # testargs = [cmd] 58 | # with patch.object(sys, 'argv', testargs): 59 | # bottle_daemon_run(cmd='Stop') 60 | # 61 | # 62 | # 63 | -------------------------------------------------------------------------------- /datamountaineer/schemaregistry/tests/test_util.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from avro import schema 4 | 5 | from datamountaineer.schemaregistry.tests import data_gen 6 | 7 | from datamountaineer.schemaregistry.client import Util 8 | 9 | 10 | class TestUtil(unittest.TestCase): 11 | 12 | def test_schema_from_string(self): 13 | parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA) 14 | self.assertTrue(isinstance(parsed, schema.Schema)) 15 | 16 | def test_schema_from_file(self): 17 | parsed = Util.parse_schema_from_file(data_gen.get_schema_path('adv_schema.avsc')) 18 | self.assertTrue(isinstance(parsed, schema.Schema)) 19 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | fastavro 2 | avro-python3 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | 4 | def version(): 5 | with open('VERSION') as f: 6 | return f.read().strip() 7 | 8 | 9 | def readme(): 10 | with open('README.md') as f: 11 | return f.read() 12 | 13 | 14 | def reqs(): 15 | return [ 16 | line.strip() for line in open('requirements.txt') if not line.startswith('#') 17 | ] 18 | 19 | 20 | setup( 21 | name = 'datamountaineer-schemaregistry', 22 | description = 'DataMountaineer Python 3 Confluent Schema Registry Client', 23 | long_description = readme(), 24 | version = version(), 25 | license = 'Apache 2.0', 26 | author = 'DataMountaineer', 27 | author_email = 'andrew@datamountaineer.com', 28 | keywords = 'datamountaineer schema registry schemaregistry confluent avro', 29 | install_requires = reqs(), 30 | tests_require = ['mock'], 31 | url = 'https://github.com/datamountaineer/python-serializers', 32 | classifiers = [ 33 | 'Development Status :: 4 - Beta', 34 | 'Intended Audience :: Developers', 35 | 'License :: OSI Approved :: Apache Software License', 36 | 'Operating System :: OS Independent', 37 | 'Programming Language :: Python', 38 | 'Topic :: Software Development :: Libraries', 39 | ], 40 | packages = [ 41 | 'datamountaineer', 42 | 'datamountaineer.schemaregistry', 43 | 'datamountaineer.schemaregistry.serializers', 44 | 'datamountaineer.schemaregistry.client', 45 | 'datamountaineer.schemaregistry.tests' 46 | ], 47 | ) 48 | --------------------------------------------------------------------------------