-
Notifications
You must be signed in to change notification settings - Fork 17
feat: add protobuf V3 #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
runeglom
wants to merge
3
commits into
DisasterAWARE:main
Choose a base branch
from
runeglom:feat/protobufv3
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import re | ||
| import tempfile | ||
| from os import path | ||
|
|
||
| from .schema import DataFormat, Schema, ValidationError | ||
| from .utils_protobufv3 import load_pb_file, load_pb_str | ||
|
|
||
|
|
||
| class ProtobufV3Schema(Schema): | ||
| """Implementation of the `Schema` protocol for Protobuf V3 schemas. | ||
|
|
||
| Arguments: | ||
| definition: the schema, either as a file path string or (perspectively) a string | ||
| message_class_name: the class name of the message to be | ||
| serialized / deserialized | ||
| """ | ||
|
|
||
| def __init__(self, definition: str, | ||
| message_class_name: str): | ||
| # distinguish: protobuf schema file vs. protbuf schema string | ||
| if re.match(r"^(.+)/([^/]+)$", definition): | ||
| self._parsed = load_pb_file(definition) | ||
| else: | ||
| temp_file = tempfile.NamedTemporaryFile(delete=True) | ||
| self._parsed = load_pb_str(definition, f"{path.basename(temp_file.name)}.proto") | ||
| self._msg_obj = getattr(self._parsed, message_class_name)() | ||
| self._message_class_name = message_class_name | ||
|
|
||
| def __hash__(self): | ||
| return hash(str(self)) | ||
|
|
||
| def __eq__(self, other): | ||
| return isinstance(other, ProtobufV3Schema) and \ | ||
| self._parsed == other._parsed | ||
|
|
||
| def __str__(self): | ||
| return self._parsed | ||
|
|
||
| def __repr__(self): | ||
| return '<ProtobufV3Schema %s>' % self._parsed | ||
|
|
||
| @property | ||
| def data_format(self) -> DataFormat: | ||
| return 'PROTOBUFV3' | ||
|
|
||
| @property | ||
| def fqn(self) -> str: | ||
| return "" | ||
|
|
||
| def read(self, bytestr: bytes): | ||
| self._msg_obj.ParseFromString(bytestr) | ||
| return self._msg_obj | ||
|
|
||
| def write(self, data) -> bytes: | ||
| return data.SerializeToString() | ||
|
|
||
| def validate(self, data): | ||
| try: | ||
| data.SerializeToString() | ||
| except Exception as e: | ||
| # the message will contain space characters, json.loads + str is a | ||
| # (relatively inefficient) way to remove them | ||
| detail: list[str] = json.loads(str(e)) | ||
| raise ValidationError(str(detail)) from e |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import tempfile | ||
| from importlib.machinery import SourceFileLoader | ||
| from os import path, makedirs | ||
| from types import ModuleType | ||
|
|
||
| from grpc_tools import protoc | ||
|
|
||
|
|
||
| def load_pb_file(proto_schema_file: str) -> ModuleType: | ||
| """ | ||
| Helper function to load a protobuf schema from a given file. | ||
|
|
||
| :param proto_schema_file: file path and name as string (ends with ".proto") | ||
| """ | ||
| with tempfile.TemporaryDirectory() as temp_dir: | ||
| schema_file_name = path.basename(proto_schema_file) | ||
| proto_dir = path.dirname(proto_schema_file) | ||
| proto_name = schema_file_name[:-6] | ||
|
|
||
| compiled_dir = path.join(temp_dir, 'protol', proto_name) | ||
|
|
||
| return compile_pb_schema(proto_dir, proto_name, proto_schema_file, compiled_dir) | ||
|
|
||
|
|
||
| def load_pb_str(proto_schema_str: str, schema_file_name: str) -> ModuleType: | ||
| """ | ||
| Helper function to load a protobuf schema from a given string. | ||
|
|
||
| :param proto_schema_str: protobuf schema as string | ||
| :param schema_file_name: protobuf schema file name (ends with ".proto") | ||
| """ | ||
| with tempfile.TemporaryDirectory() as proto_dir: | ||
| proto_name = schema_file_name[:-6] | ||
|
|
||
| # create protobuf schema file in temp folder | ||
| proto_schema_file = path.join(proto_dir, schema_file_name) | ||
| with open(proto_schema_file, 'w') as f: | ||
| f.write(proto_schema_str) | ||
|
|
||
| compiled_dir = path.join(proto_dir, 'protol', proto_name) | ||
|
|
||
| return compile_pb_schema(proto_dir, proto_name, proto_schema_file, compiled_dir) | ||
|
|
||
|
|
||
| def compile_pb_schema(proto_dir, proto_name, proto_schema_file, compiled_dir): | ||
| """ | ||
| Compile protobuf schema to Python classes. | ||
|
|
||
| :param proto_dir: directory of the protobuf schema file name | ||
| :param proto_name: protobuf schema file name (without extension) | ||
| :param proto_schema_file: the given protobuf schema file | ||
| :param compiled_dir: directory containing the compiled Python classes | ||
| """ | ||
| pb2_name = f'{proto_name}_pb2' | ||
| pb2_file = path.join(compiled_dir, f'{pb2_name}.py') | ||
|
|
||
| if path.isdir(compiled_dir): | ||
| if path.exists(pb2_file): | ||
| return SourceFileLoader(pb2_name, pb2_file).load_module() | ||
| else: | ||
| makedirs(compiled_dir) | ||
|
|
||
| proto_include = protoc.pkg_resources.resource_filename('grpc_tools', '_proto') | ||
| compile_arguments = [ | ||
| f'-I{proto_dir}', | ||
| f'--proto_path={proto_dir}', | ||
| f'--python_out={compiled_dir}', | ||
| proto_schema_file, | ||
| f'-I{proto_include}' | ||
| ] | ||
| protoc.main(compile_arguments) | ||
|
|
||
| return SourceFileLoader(pb2_name, pb2_file).load_module() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| syntax = "proto3"; | ||
| package aws_schema_registry.integrationtests; | ||
|
|
||
| message User { | ||
| string name = 1; | ||
| int32 favorite_number = 2; | ||
| string favorite_color = 3; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| syntax = "proto3"; | ||
| package alpha.beta; | ||
|
|
||
| message MyMessage { | ||
| string text = 1; | ||
| int32 number = 2; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| from aws_schema_registry.protobufv3 import ProtobufV3Schema | ||
|
|
||
|
|
||
| def test_fully_qualified_name(): | ||
| s = ProtobufV3Schema('./resources/example.proto', 'MyMessage') | ||
| assert s.fqn == "" | ||
|
|
||
|
|
||
| def test_readwrite(): | ||
| s = ProtobufV3Schema('./resources/example.proto', 'MyMessage') | ||
| d = s._parsed.MyMessage(text = 'Hello World!', number = 42) | ||
| assert s.read(s.write(d)) == d | ||
|
|
||
|
|
||
| def test_readwrite_schema_str(): | ||
| s = ProtobufV3Schema("""syntax = "proto3"; | ||
| package gamma.delta; | ||
|
|
||
| message MySecondMessage { | ||
| string text = 1; | ||
| int32 number = 2; | ||
| } | ||
| """, 'MySecondMessage') | ||
| d = s._parsed.MySecondMessage(text = 'Hello World!', number = 42) | ||
| assert s.read(s.write(d)) == d |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note: load_module() is removed in python 3.15