├── LICENSE ├── README.md ├── client.py ├── client.rb ├── gen.sh ├── lib ├── parser.rb └── parser_services.rb ├── parser_pb2.py ├── protos └── parser.proto └── server.py /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### gRPC Twitter Text 2 | 3 | Response format: 4 | 5 | ```json 6 | { 7 | "users": [ 8 | ], 9 | "tags": [ 10 | ], 11 | "urls": [ 12 | ] 13 | } 14 | ``` 15 | -------------------------------------------------------------------------------- /client.py: -------------------------------------------------------------------------------- 1 | from grpc.beta import implementations 2 | 3 | import parser_pb2 4 | 5 | _TIMEOUT_SECONDS = 10 6 | 7 | text = ("@burnettedmond, you now support #IvoWertzel's tweet " 8 | "parser! https://github.com/edburnett/") 9 | 10 | def run(): 11 | channel = implementations.insecure_channel('localhost', 50051) 12 | stub = parser_pb2.beta_create_TwitterText_stub(channel) 13 | response = stub.Parse(parser_pb2.TweetRequest(text=text), _TIMEOUT_SECONDS) 14 | print 'Parser client received: %s' % response 15 | print 'response.users=%s' % response.users 16 | print 'response.tags=%s' % response.tags 17 | print 'response.urls=%s' % response.urls 18 | 19 | 20 | if __name__ == '__main__': 21 | run() 22 | -------------------------------------------------------------------------------- /client.rb: -------------------------------------------------------------------------------- 1 | this_dir = File.expand_path(File.dirname(__FILE__)) 2 | lib_dir = File.join(this_dir, 'lib') 3 | $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) 4 | 5 | require 'grpc' 6 | require 'parser_services' 7 | 8 | def main 9 | stub = Twittertext::TwitterText::Stub.new('localhost:50051', :this_channel_is_insecure) 10 | response = stub.parse(Twittertext::TweetRequest.new(text: "@burnettedmond, you now support #IvoWertzel's tweet parser! https://github.com/edburnett/")) 11 | puts "#{response.inspect}" 12 | puts "response.users=#{response.users}" 13 | puts "response.tags=#{response.tags}" 14 | puts "response.urls=#{response.urls}" 15 | end 16 | 17 | main 18 | -------------------------------------------------------------------------------- /gen.sh: -------------------------------------------------------------------------------- 1 | # Python client 2 | protoc -I protos/ --python_out=. --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_python_plugin` protos/parser.proto 3 | 4 | # Ruby 5 | protoc -I protos/ --ruby_out=lib --grpc_out=lib --plugin=protoc-gen-grpc=`which grpc_ruby_plugin` protos/parser.proto 6 | -------------------------------------------------------------------------------- /lib/parser.rb: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # source: parser.proto 3 | 4 | require 'google/protobuf' 5 | 6 | Google::Protobuf::DescriptorPool.generated_pool.build do 7 | add_message "twittertext.TweetRequest" do 8 | optional :text, :string, 1 9 | end 10 | add_message "twittertext.ParsedResponse" do 11 | repeated :users, :string, 1 12 | repeated :tags, :string, 2 13 | repeated :urls, :string, 3 14 | end 15 | end 16 | 17 | module Twittertext 18 | TweetRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("twittertext.TweetRequest").msgclass 19 | ParsedResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("twittertext.ParsedResponse").msgclass 20 | end 21 | -------------------------------------------------------------------------------- /lib/parser_services.rb: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # Source: parser.proto for package 'twittertext' 3 | 4 | require 'grpc' 5 | require 'parser' 6 | 7 | module Twittertext 8 | module TwitterText 9 | 10 | # TODO: add proto service documentation here 11 | class Service 12 | 13 | include GRPC::GenericService 14 | 15 | self.marshal_class_method = :encode 16 | self.unmarshal_class_method = :decode 17 | self.service_name = 'twittertext.TwitterText' 18 | 19 | rpc :Parse, TweetRequest, ParsedResponse 20 | end 21 | 22 | Stub = Service.rpc_stub_class 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /parser_pb2.py: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # source: parser.proto 3 | 4 | import sys 5 | _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import message as _message 8 | from google.protobuf import reflection as _reflection 9 | from google.protobuf import symbol_database as _symbol_database 10 | from google.protobuf import descriptor_pb2 11 | # @@protoc_insertion_point(imports) 12 | 13 | _sym_db = _symbol_database.Default() 14 | 15 | 16 | 17 | 18 | DESCRIPTOR = _descriptor.FileDescriptor( 19 | name='parser.proto', 20 | package='twittertext', 21 | syntax='proto3', 22 | serialized_pb=_b('\n\x0cparser.proto\x12\x0btwittertext\"\x1c\n\x0cTweetRequest\x12\x0c\n\x04text\x18\x01 \x01(\t\";\n\x0eParsedResponse\x12\r\n\x05users\x18\x01 \x03(\t\x12\x0c\n\x04tags\x18\x02 \x03(\t\x12\x0c\n\x04urls\x18\x03 \x03(\t2P\n\x0bTwitterText\x12\x41\n\x05Parse\x12\x19.twittertext.TweetRequest\x1a\x1b.twittertext.ParsedResponse\"\x00\x62\x06proto3') 23 | ) 24 | _sym_db.RegisterFileDescriptor(DESCRIPTOR) 25 | 26 | 27 | 28 | 29 | _TWEETREQUEST = _descriptor.Descriptor( 30 | name='TweetRequest', 31 | full_name='twittertext.TweetRequest', 32 | filename=None, 33 | file=DESCRIPTOR, 34 | containing_type=None, 35 | fields=[ 36 | _descriptor.FieldDescriptor( 37 | name='text', full_name='twittertext.TweetRequest.text', index=0, 38 | number=1, type=9, cpp_type=9, label=1, 39 | has_default_value=False, default_value=_b("").decode('utf-8'), 40 | message_type=None, enum_type=None, containing_type=None, 41 | is_extension=False, extension_scope=None, 42 | options=None), 43 | ], 44 | extensions=[ 45 | ], 46 | nested_types=[], 47 | enum_types=[ 48 | ], 49 | options=None, 50 | is_extendable=False, 51 | syntax='proto3', 52 | extension_ranges=[], 53 | oneofs=[ 54 | ], 55 | serialized_start=29, 56 | serialized_end=57, 57 | ) 58 | 59 | 60 | _PARSEDRESPONSE = _descriptor.Descriptor( 61 | name='ParsedResponse', 62 | full_name='twittertext.ParsedResponse', 63 | filename=None, 64 | file=DESCRIPTOR, 65 | containing_type=None, 66 | fields=[ 67 | _descriptor.FieldDescriptor( 68 | name='users', full_name='twittertext.ParsedResponse.users', index=0, 69 | number=1, type=9, cpp_type=9, label=3, 70 | has_default_value=False, default_value=[], 71 | message_type=None, enum_type=None, containing_type=None, 72 | is_extension=False, extension_scope=None, 73 | options=None), 74 | _descriptor.FieldDescriptor( 75 | name='tags', full_name='twittertext.ParsedResponse.tags', index=1, 76 | number=2, type=9, cpp_type=9, label=3, 77 | has_default_value=False, default_value=[], 78 | message_type=None, enum_type=None, containing_type=None, 79 | is_extension=False, extension_scope=None, 80 | options=None), 81 | _descriptor.FieldDescriptor( 82 | name='urls', full_name='twittertext.ParsedResponse.urls', index=2, 83 | number=3, type=9, cpp_type=9, label=3, 84 | has_default_value=False, default_value=[], 85 | message_type=None, enum_type=None, containing_type=None, 86 | is_extension=False, extension_scope=None, 87 | options=None), 88 | ], 89 | extensions=[ 90 | ], 91 | nested_types=[], 92 | enum_types=[ 93 | ], 94 | options=None, 95 | is_extendable=False, 96 | syntax='proto3', 97 | extension_ranges=[], 98 | oneofs=[ 99 | ], 100 | serialized_start=59, 101 | serialized_end=118, 102 | ) 103 | 104 | DESCRIPTOR.message_types_by_name['TweetRequest'] = _TWEETREQUEST 105 | DESCRIPTOR.message_types_by_name['ParsedResponse'] = _PARSEDRESPONSE 106 | 107 | TweetRequest = _reflection.GeneratedProtocolMessageType('TweetRequest', (_message.Message,), dict( 108 | DESCRIPTOR = _TWEETREQUEST, 109 | __module__ = 'parser_pb2' 110 | # @@protoc_insertion_point(class_scope:twittertext.TweetRequest) 111 | )) 112 | _sym_db.RegisterMessage(TweetRequest) 113 | 114 | ParsedResponse = _reflection.GeneratedProtocolMessageType('ParsedResponse', (_message.Message,), dict( 115 | DESCRIPTOR = _PARSEDRESPONSE, 116 | __module__ = 'parser_pb2' 117 | # @@protoc_insertion_point(class_scope:twittertext.ParsedResponse) 118 | )) 119 | _sym_db.RegisterMessage(ParsedResponse) 120 | 121 | 122 | import abc 123 | from grpc.beta import implementations as beta_implementations 124 | from grpc.framework.common import cardinality 125 | from grpc.framework.interfaces.face import utilities as face_utilities 126 | 127 | class BetaTwitterTextServicer(object): 128 | """""" 129 | __metaclass__ = abc.ABCMeta 130 | @abc.abstractmethod 131 | def Parse(self, request, context): 132 | raise NotImplementedError() 133 | 134 | class BetaTwitterTextStub(object): 135 | """The interface to which stubs will conform.""" 136 | __metaclass__ = abc.ABCMeta 137 | @abc.abstractmethod 138 | def Parse(self, request, timeout): 139 | raise NotImplementedError() 140 | Parse.future = None 141 | 142 | def beta_create_TwitterText_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): 143 | import parser_pb2 144 | import parser_pb2 145 | request_deserializers = { 146 | ('twittertext.TwitterText', 'Parse'): parser_pb2.TweetRequest.FromString, 147 | } 148 | response_serializers = { 149 | ('twittertext.TwitterText', 'Parse'): parser_pb2.ParsedResponse.SerializeToString, 150 | } 151 | method_implementations = { 152 | ('twittertext.TwitterText', 'Parse'): face_utilities.unary_unary_inline(servicer.Parse), 153 | } 154 | server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) 155 | return beta_implementations.server(method_implementations, options=server_options) 156 | 157 | def beta_create_TwitterText_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): 158 | import parser_pb2 159 | import parser_pb2 160 | request_serializers = { 161 | ('twittertext.TwitterText', 'Parse'): parser_pb2.TweetRequest.SerializeToString, 162 | } 163 | response_deserializers = { 164 | ('twittertext.TwitterText', 'Parse'): parser_pb2.ParsedResponse.FromString, 165 | } 166 | cardinalities = { 167 | 'Parse': cardinality.Cardinality.UNARY_UNARY, 168 | } 169 | stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) 170 | return beta_implementations.dynamic_stub(channel, 'twittertext.TwitterText', cardinalities, options=stub_options) 171 | # @@protoc_insertion_point(module_scope) 172 | -------------------------------------------------------------------------------- /protos/parser.proto: -------------------------------------------------------------------------------- 1 | // We're using proto3 syntax 2 | syntax = "proto3"; 3 | 4 | package twittertext; 5 | 6 | // This is the service for our API 7 | service TwitterText { 8 | // This is where we define the methods in this service 9 | 10 | // We have a method called `Parse` which takes 11 | // parameter called `TweetRequest` and returns 12 | // the message `ParsedResponse` 13 | rpc Parse(TweetRequest) returns (ParsedResponse) {} 14 | } 15 | 16 | // The request message has the tweet text to be parsed 17 | message TweetRequest { 18 | // The field `text` is of type `string` 19 | string text = 1; 20 | } 21 | 22 | // The request message has the tweet text to be parsed 23 | message ParsedResponse { 24 | // `repeated` is used for a list 25 | repeated string users = 1; 26 | repeated string tags = 2; 27 | repeated string urls = 3; 28 | } 29 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | from ttp import ttp 4 | 5 | import parser_pb2 6 | 7 | _ONE_DAY_IN_SECONDS = 60 * 60 * 24 8 | 9 | p = ttp.Parser() 10 | 11 | 12 | class Parser(parser_pb2.BetaTwitterTextServicer): 13 | 14 | def Parse(self, request, context): 15 | print 'Received message: %s' % request 16 | result = p.parse(request.text) 17 | return parser_pb2.ParsedResponse(users=result.users, 18 | tags=result.tags, 19 | urls=result.urls) 20 | 21 | 22 | def serve(): 23 | server = parser_pb2.beta_create_TwitterText_server(Parser()) 24 | server.add_insecure_port('[::]:50051') 25 | server.start() 26 | try: 27 | while True: 28 | time.sleep(_ONE_DAY_IN_SECONDS) 29 | except KeyboardInterrupt: 30 | server.stop(0) 31 | 32 | 33 | if __name__ == '__main__': 34 | serve() 35 | --------------------------------------------------------------------------------