twirp 0.0.2.1 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 0beb3999bd9e3f24928e3177696919e1e48003c3
4
- data.tar.gz: 0173e308fa7df470db82f6a5129972ab2c368679
3
+ metadata.gz: 76e48aace902f0cec12c1055dd664f659fb9dcf3
4
+ data.tar.gz: 792f3fcc5a62cbd2adfd9f3d714b246e96c63bca
5
5
  SHA512:
6
- metadata.gz: ea168c51643ae809dd9998fb932bee65f4ee8b21472aff74107b5beef1afc0a34a8af4b6d2591c65a80aa64ce503b3094dc5fee6a2d9b3a0dcf24dfdbfa3ec23
7
- data.tar.gz: cc0310f0f12b57c3fdfe938573769ba88c752d91ec8c220e261dda410105a61e89d1ca8204fae6f82fac16956a50ee6033122f2c7dc7a720c010bbaf3b269670
6
+ metadata.gz: ea48c85b317496979d87015964d714a95db49093d5a81183b50928fbcdb453f4469fdf819b907012b1094f692fc08d3892b89bf55d870791f8607eded50ca06b
7
+ data.tar.gz: bb59b2e6077814fa06b9b29fee4473155408eb0930ddb4ca00a2e088534e4a32b64450eda3721445c26634d5ed36ead624b35544c2c8988f070ffc066a7bf8ad
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md CHANGED
@@ -4,12 +4,12 @@ Twirp services and clients in Ruby.
4
4
 
5
5
  ### Installation
6
6
  Install the `twirp` gem:
7
- ```
7
+ ```sh
8
8
  ➜ gem install twirp
9
9
  ```
10
10
 
11
11
  Use `go get` to install the ruby_twirp protoc plugin:
12
- ```
12
+ ```sh
13
13
  ➜ go get github.com/cyrusaf/ruby-twirp/protoc-gen-twirp_ruby
14
14
  ```
15
15
 
@@ -18,13 +18,13 @@ You will also need:
18
18
  version 3+.
19
19
 
20
20
  ### Haberdasher Example
21
- See the `examples/` folder for the final product.
21
+ See the `example/` folder for the final product.
22
22
 
23
23
  First create a basic `.proto` file:
24
- ```
24
+ ```protobuf
25
25
  // haberdasher.proto
26
26
  syntax = "proto3";
27
- package examples;
27
+ package example;
28
28
 
29
29
  service Haberdasher {
30
30
  rpc HelloWorld(HelloWorldRequest) returns (HelloWorldResponse);
@@ -41,47 +41,46 @@ message HelloWorldResponse {
41
41
  ```
42
42
 
43
43
  Run the `protoc` binary to generate `gen/haberdasher_pb.rb` and `gen/haberdasher_twirp.rb`.
44
- ```
44
+ ```sh
45
45
  ➜ protoc --proto_path=. ./haberdasher.proto --ruby_out=gen --twirp_ruby_out=gen
46
46
  ```
47
47
 
48
48
  Write an implementation of our haberdasher service and attach to a rack server:
49
- ```
49
+ ```ruby
50
50
  # main.rb
51
51
  require 'rack'
52
52
  require_relative 'gen/haberdasher_pb.rb'
53
53
  require_relative 'gen/haberdasher_twirp.rb'
54
54
 
55
- class HaberdasherImplementation
56
- def HelloWorld(req)
57
- return Examples::HelloWorldResponse.new(message: "Hello #{req.name}")
55
+ class HaberdasherHandler
56
+ def hello_world(req)
57
+ return Example::HelloWorldResponse.new(message: "Hello #{req.name}")
58
58
  end
59
59
  end
60
60
 
61
- svc = HaberdasherImplementation.new()
62
- url_map = Rack::URLMap.new HaberdasherService::PATH_PREFIX => HaberdasherService.new(svc).handler
63
- Rack::Handler::WEBrick.run url_map
61
+ handler = HaberdasherHandler.new()
62
+ Rack::Handler::WEBrick.run Example::HaberdasherService.new(handler)
64
63
  ```
65
64
 
66
65
  You can also mount onto a rails service:
67
- ```
66
+ ```ruby
68
67
  App::Application.routes.draw do
69
- svc = HaberdasherImplementation.new()
70
- mount HaberdasherServer.new(svc).handler, at: HaberdasherServer::PATH_PREFIX
68
+ handler = HaberdasherHandler.new()
69
+ mount Example::HaberdasherService.new(handler), at: HaberdasherService::PATH_PREFIX
71
70
  end
72
71
  ```
73
72
 
74
73
  Run `ruby main.rb` to start the server on port 8080:
75
- ```
74
+ ```sh
76
75
  ➜ ruby main.rb
77
76
  ```
78
77
 
79
78
  `curl` your server to get a response:
80
- ```
79
+ ```sh
81
80
  ➜ curl --request POST \
82
81
  --url http://localhost:8080/twirp/examples.Haberdasher/HelloWorld \
83
82
  --header 'content-type: application/json' \
84
83
  --data '{
85
84
  "name": "World"
86
- }'
85
+ }'
87
86
  ```
@@ -3,5 +3,5 @@ source "https://rubygems.org"
3
3
 
4
4
  git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
5
5
 
6
- gem 'twirp'
6
+ gem "twirp"
7
7
  gem "rack"
File without changes
@@ -4,15 +4,15 @@
4
4
  require 'google/protobuf'
5
5
 
6
6
  Google::Protobuf::DescriptorPool.generated_pool.build do
7
- add_message "examples.HelloWorldRequest" do
7
+ add_message "example.HelloWorldRequest" do
8
8
  optional :name, :string, 1
9
9
  end
10
- add_message "examples.HelloWorldResponse" do
10
+ add_message "example.HelloWorldResponse" do
11
11
  optional :message, :string, 1
12
12
  end
13
13
  end
14
14
 
15
- module Examples
16
- HelloWorldRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.HelloWorldRequest").msgclass
17
- HelloWorldResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("examples.HelloWorldResponse").msgclass
15
+ module Example
16
+ HelloWorldRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("example.HelloWorldRequest").msgclass
17
+ HelloWorldResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("example.HelloWorldResponse").msgclass
18
18
  end
@@ -0,0 +1,11 @@
1
+ # Code generated by protoc-gen-twirp_ruby, DO NOT EDIT.
2
+ require 'twirp'
3
+
4
+ module Example
5
+ class HaberdasherService < Twirp::Service
6
+ PATH_PREFIX = "/twirp/example.Haberdasher"
7
+ package "example"
8
+ service "Haberdasher"
9
+ rpc :HelloWorld, HelloWorldRequest, HelloWorldResponse, handler_method: 'hello_world'
10
+ end
11
+ end
@@ -1,5 +1,5 @@
1
1
  syntax = "proto3";
2
- package examples;
2
+ package example;
3
3
 
4
4
  service Haberdasher {
5
5
  rpc HelloWorld(HelloWorldRequest) returns (HelloWorldResponse);
data/example/main.rb ADDED
@@ -0,0 +1,13 @@
1
+ require 'rack'
2
+ require_relative 'gen/haberdasher_pb.rb'
3
+ require_relative 'gen/haberdasher_twirp.rb'
4
+
5
+ class HaberdasherHandler
6
+ def hello_world(req)
7
+ return Example::HelloWorldResponse.new(message: "Hello #{req.name}")
8
+ end
9
+ end
10
+
11
+ handler = HaberdasherHandler.new()
12
+ service = Example::HaberdasherService.new(handler)
13
+ Rack::Handler::WEBrick.run service
data/lib/twirp/error.rb CHANGED
@@ -41,7 +41,23 @@ module Twirp
41
41
 
42
42
  attr_reader :code
43
43
  attr_reader :msg
44
- def meta; @meta || {}; end
44
+
45
+ def meta(key)
46
+ @meta ||= {}
47
+ @meta[key]
48
+ end
49
+
50
+ def add_meta(key, value)
51
+ validate_meta_key_value(key, value)
52
+ @meta ||= {}
53
+ @meta[key] = value
54
+ end
55
+
56
+ def delete_meta(key)
57
+ @meta ||= {}
58
+ @meta.delete(key.to_s)
59
+ @meta = nil if @meta.size == 0
60
+ end
45
61
 
46
62
  def as_json
47
63
  h = {
@@ -73,14 +89,18 @@ module Twirp
73
89
  if !meta.is_a? Hash
74
90
  raise ArgumentError.new("Twirp::Error meta must be a Hash, but it is a #{meta.class.to_s}")
75
91
  end
76
- meta.each do |k, v|
77
- if !k.is_a?(String) || !v.is_a?(String)
78
- raise ArgumentError.new("Twirp::Error meta must be a Hash with String keys and values")
79
- end
92
+ meta.each do |key, value|
93
+ validate_meta_key_value(key, value)
80
94
  end
81
95
  meta
82
96
  end
83
97
 
98
+ def validate_meta_key_value(key, value)
99
+ if !key.is_a?(String) || !value.is_a?(String)
100
+ raise ArgumentError.new("Twirp::Error meta must be a Hash with String keys and values")
101
+ end
102
+ end
103
+
84
104
  end
85
105
 
86
106
  end
data/lib/twirp/service.rb CHANGED
@@ -1,66 +1,164 @@
1
1
  module Twirp
2
+
2
3
  class Service
3
- @@rpcs = {}
4
4
 
5
- def initialize(svc)
6
- @svc = svc
7
- end
5
+ class << self
8
6
 
9
- def self.rpc(name, request_class, response_class)
10
- @@rpcs[name] = {
11
- request_class: request_class,
12
- response_class: response_class
13
- }
14
- end
7
+ # Configure service package name.
8
+ def package(package_name)
9
+ @package_name = package_name.to_s
10
+ end
15
11
 
16
- def route_request(req)
17
- # Parse url to get method names
18
- method_name = req.fullpath[self.class::PATH_PREFIX.length+1..-1]
12
+ # Configure service name
13
+ def service(service_name)
14
+ @service_name = service_name.to_s
15
+ end
19
16
 
20
- # Get req/res types from @@rpcs
21
- rpc = @@rpcs[method_name.to_sym]
22
- request_class = rpc[:request_class]
23
- response_class = rpc[:response_class]
17
+ # Configure service routing to handle rpc calls.
18
+ def rpc(method_name, request_class, response_class, opts)
19
+ if !request_class.is_a?(Class)
20
+ raise ArgumentError.new("request_class must be a Protobuf Message class")
21
+ end
22
+ if !response_class.is_a?(Class)
23
+ raise ArgumentError.new("response_class must be a Protobuf Message class")
24
+ end
25
+ if !opts || !opts[:handler_method]
26
+ raise ArgumentError.new("opts[:handler_method] is mandatory")
27
+ end
24
28
 
25
- case req.env["CONTENT_TYPE"]
26
- when "application/json"
27
- return self.serve_json(req, method_name, request_class, response_class)
28
- when "application/protobuf"
29
- return self.serve_proto(req, method_name, request_class, response_class)
30
- else
31
- return self.serve_error(Twerr.NotFound("unexpected Content-Type: #{req.env["CONTENT_TYPE"]}"))
29
+ @rpcs ||= {}
30
+ @rpcs[method_name.to_s] = {
31
+ request_class: request_class,
32
+ response_class: response_class,
33
+ handler_method: opts[:handler_method],
34
+ }
35
+ end
36
+
37
+ # Get configured package name as String.
38
+ # And empty value means that there's no package
39
+ def package_name
40
+ @package_name.to_s
41
+ end
42
+
43
+ # Get configured service name as String.
44
+ # If not configured, it defaults to the class name
45
+ def service_name
46
+ sname = @service_name.to_s
47
+ sname.empty? ? self.name : sname
48
+ end
49
+
50
+ # Get configured metadata for rpc methods
51
+ def rpcs
52
+ @rpcs || {}
53
+ end
54
+
55
+ # Path prefix that should be used to route requests to this service.
56
+ # It is based on the package and service name, in the expected Twirp URL format.
57
+ # The full URL would be: {BaseURL}/path_prefix/{MethodName}
58
+ def path_prefix
59
+ if package_name.empty?
60
+ service_name # e.g. "Haberdasher"
61
+ else
62
+ "#{package_name}.#{service_name}" # e.g. "the.haberdasher.pkg.Haberdasher"
63
+ end
32
64
  end
33
65
  end
34
66
 
35
- def serve_json(req, method_name, request_class, response_class)
36
- params = request_class.decode_json(req.body.read)
37
- resp = @svc.send(method_name, params)
38
- self.serve_success_json(response_class.encode_json(resp))
67
+ # Instantiate a new service with a handler.
68
+ # A handler implements each rpc method as a regular object method call.
69
+ def initialize(handler)
70
+ # validate that the handler reponds to all expected methods
71
+ self.class.rpcs.each do |method_name, rpc|
72
+ if !handler.respond_to? rpc[:handler_method]
73
+ raise ArgumentError.new("Handler must respond to .#{rpc[:handler_method]}(req) in order to handle the message #{method_name}.")
74
+ end
75
+ end
76
+
77
+ @handler = handler
39
78
  end
40
79
 
41
- def serve_proto(req, method_name, request_class, response_class)
42
- params = request_type.decode(req.body.read)
43
- resp = @svc.send(method_name, params)
44
- self.serve_success_proto(response_class.encode(resp))
80
+ # Register a before hook (not implemented)
81
+ def before(&block)
82
+ # TODO... and also after hooks
45
83
  end
46
84
 
47
- def serve_success_proto(resp)
48
- return ['200', {'Content-Type' => 'application/protobuf'}, [resp]]
85
+ # A service instance is a Rack middleware block.
86
+ def call(env)
87
+ req = Rack::Request.new(env)
88
+
89
+ if req.request_method != "POST"
90
+ return error_response(bad_route_error("Only POST method is allowed", req))
91
+ end
92
+
93
+ method_name = req.fullpath.split("/").last
94
+ rpc_method = self.class.rpcs[method_name]
95
+ if !rpc_method
96
+ return error_response(bad_route_error("rpc method not found: #{method_name.inspect}", req))
97
+ end
98
+
99
+ request_class = rpc_method[:request_class]
100
+ response_class = rpc_method[:response_class]
101
+
102
+ content_type = req.env["CONTENT_TYPE"]
103
+ req_msg = decode_request(rpc_method[:request_class], content_type, req.body.read)
104
+ if !req_msg
105
+ return error_response(bad_route_error("unexpected Content-Type: #{content_type.inspect}", req))
106
+ end
107
+
108
+ # Handle Twirp request
109
+ # TODO: wrap with begin-rescue block
110
+ resp_msg = @handler.send(rpc_method[:handler_method], req_msg)
111
+
112
+ if resp_msg.is_a? Twirp::Error
113
+ return error_response(resp_msg)
114
+ end
115
+
116
+ if resp_msg.is_a? Hash # allow handlers to respond with just the attributes
117
+ resp_msg = response_class.new(resp_msg)
118
+ end
119
+ encoded_resp = encode_response(response_class, content_type, resp_msg)
120
+
121
+ return [200, {'Content-Type' => content_type}, [encoded_resp]]
122
+
123
+ # TODO: add recue for any error in the method, wrap with Twith error
49
124
  end
50
125
 
51
- def serve_success_json(resp)
52
- return ['200', {'Content-Type' => 'application/json'}, [resp]]
126
+ # path prefix that can be used to mount this service
127
+ def path_prefix
128
+ self.class.path_prefix
53
129
  end
54
130
 
55
- def serve_error(twerr)
56
- return ['500', {'Content-Type' => 'application/json'}, []]
131
+ private
132
+
133
+ def decode_request(request_class, content_type, body)
134
+ case content_type
135
+ when "application/json"
136
+ request_class.decode_json(body)
137
+ when "application/protobuf"
138
+ request_type.decode(body)
139
+ end
57
140
  end
58
141
 
59
- def handler
60
- return Proc.new do |env|
61
- req = Rack::Request.new(env)
62
- self.route_request(req)
142
+ def encode_response(response_class, content_type, resp)
143
+ case content_type
144
+ when "application/json"
145
+ response_class.encode_json(resp)
146
+ when "application/protobuf"
147
+ response_class.encode(resp)
63
148
  end
64
149
  end
150
+
151
+ def error_response(twirp_error)
152
+ status = Twirp::ERROR_CODES_TO_HTTP_STATUS[twirp_error.code]
153
+ headers = {'Content-Type' => 'application/json'}
154
+ resp_body = twirp_error.to_json
155
+ [status, headers, [resp_body]]
156
+ end
157
+
158
+ def bad_route_error(msg, req)
159
+ meta_invalid_route = "#{req.request_method} #{req.fullpath}"
160
+ Twirp::Error.new(:bad_route, msg, "twirp_invalid_route" => meta_invalid_route)
161
+ end
162
+
65
163
  end
66
164
  end
data/lib/twirp/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Twirp
2
- VERSION = "0.0.2.1"
2
+ VERSION = "0.0.3"
3
3
  end
@@ -68,20 +68,36 @@ func (g *generator) Generate(in *plugin.CodeGeneratorRequest) *plugin.CodeGenera
68
68
  }
69
69
 
70
70
  func (g *generator) generateFile(file *descriptor.FileDescriptorProto) *plugin.CodeGeneratorResponse_File {
71
+ indent := ""
71
72
  pkgName := pkgName(file)
72
73
  g.P(`# Code generated by protoc-gen-twirp_ruby, DO NOT EDIT.`)
73
- for _, service := range file.Service {
74
+ g.P(`require 'twirp'`)
75
+ g.P(``)
76
+ if pkgName != "" {
77
+ g.P(fmt.Sprintf("module %s", CamelCase(pkgName)))
78
+ indent = indent + " "
79
+ }
80
+ for i, service := range file.Service {
74
81
  serviceName := serviceName(service)
75
- g.P(`require 'twirp'`)
76
- g.P(``)
77
- g.P(fmt.Sprintf("class %sService < Twirp::Service", serviceName))
78
- g.P(fmt.Sprintf(` PATH_PREFIX = "/twirp/%s.%s"`, pkgName, serviceName))
82
+ g.P(fmt.Sprintf("%sclass %sService < Twirp::Service", indent, serviceName))
83
+ g.P(fmt.Sprintf(`%s PATH_PREFIX = "/twirp/%s.%s"`, indent, pkgName, serviceName))
84
+ if pkgName != "" {
85
+ g.P(fmt.Sprintf(`%s package "%s"`, indent, pkgName))
86
+ }
87
+ g.P(fmt.Sprintf(`%s service "%s"`, indent, CamelCase(serviceName)))
79
88
  for _, method := range service.GetMethod() {
80
89
  methName := methodName(method)
81
90
  inputName := methodInputName(method)
82
91
  outputName := methodOutputName(method)
83
- g.P(fmt.Sprintf(" rpc :%s, %s::%s, %s::%s", methName, CamelCase(pkgName), inputName, CamelCase(pkgName), outputName))
92
+ g.P(fmt.Sprintf(`%s rpc :%s, %s, %s, handler_method: "%s"`,
93
+ indent, methName, inputName, outputName, SnakeCase(methName)))
84
94
  }
95
+ g.P(fmt.Sprintf(`%send`, indent))
96
+ if i < len(file.Service)-1 {
97
+ g.P(``)
98
+ }
99
+ }
100
+ if pkgName != "" {
85
101
  g.P(`end`)
86
102
  }
87
103
 
@@ -0,0 +1,105 @@
1
+ require 'minitest/autorun'
2
+ require 'rack/mock'
3
+
4
+ require 'google/protobuf'
5
+ require_relative '../lib/twirp'
6
+
7
+ # Protobuf messages.
8
+ # This is what the protoc code generator would produce.
9
+ Google::Protobuf::DescriptorPool.generated_pool.build do
10
+ add_message "foopkg.DoFooRequest" do
11
+ optional :foo, :string, 1
12
+ end
13
+ add_message "foopkg.DoFooResponse" do
14
+ optional :bar, :string, 1
15
+ end
16
+ end
17
+ module FooPkg
18
+ DoFooRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("foopkg.DoFooRequest").msgclass
19
+ DoFooResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("foopkg.DoFooResponse").msgclass
20
+ end
21
+
22
+ # Twirp Service.
23
+ # This is wha the twirp_ruby protoc plugin code generator would produce.
24
+ module FooPkg
25
+ class FooService < Twirp::Service
26
+ package "foopkg"
27
+ service "FooService"
28
+
29
+ rpc "DoFoo", DoFooRequest, DoFooResponse, handler_method: :do_foo
30
+ end
31
+ end
32
+
33
+ # Example service handler.
34
+ # This would be provided by the developer as implementation for the service.
35
+ class FooHandler
36
+ def do_foo(req)
37
+ {bar: "Hello #{req.foo}"}
38
+ end
39
+ end
40
+
41
+ # Twirp Service with no package and no rpc methods.
42
+ class EmptyService < Twirp::Service
43
+ end
44
+
45
+ class ServiceTest < Minitest::Test
46
+
47
+ def test_rpc_methods
48
+ # make sure that rpcs have been properly setup by the `rpc` DSL constructor
49
+ assert_equal 1, FooPkg::FooService.rpcs.size
50
+ assert_equal({
51
+ request_class: FooPkg::DoFooRequest,
52
+ response_class: FooPkg::DoFooResponse,
53
+ handler_method: :do_foo,
54
+ }, FooPkg::FooService.rpcs["DoFoo"])
55
+ end
56
+
57
+ def test_package_service_getters
58
+ assert_equal "foopkg", FooPkg::FooService.package_name
59
+ assert_equal "FooService", FooPkg::FooService.service_name
60
+ assert_equal "foopkg.FooService", FooPkg::FooService.path_prefix
61
+
62
+ assert_equal "", EmptyService.package_name # defaults to empty string
63
+ assert_equal "EmptyService", EmptyService.service_name # defaults to class name
64
+ assert_equal "EmptyService", EmptyService.path_prefix # with no package is just the service name
65
+ end
66
+
67
+ def test_initialize_service
68
+ # simple initialization
69
+ svc = FooPkg::FooService.new(FooHandler.new)
70
+ assert svc.respond_to?(:call) # so it is a Proc that can be used as Rack middleware
71
+
72
+ empty_svc = EmptyService.new(nil) # an empty service does not need a handler
73
+ assert svc.respond_to?(:call)
74
+ end
75
+
76
+ def test_path_prefix
77
+ svc = FooPkg::FooService.new(FooHandler.new)
78
+ assert_equal "foopkg.FooService", svc.path_prefix
79
+ end
80
+
81
+ def test_initialize_fails_on_invalid_handlers
82
+ assert_raises ArgumentError do
83
+ FooPkg::FooService.new() # handler is mandatory
84
+ end
85
+
86
+ # verify that handler implements required methods
87
+ err = assert_raises ArgumentError do
88
+ FooPkg::FooService.new("fake handler")
89
+ end
90
+ assert_equal "Handler must respond to .do_foo(req) in order to handle the message DoFoo.", err.message
91
+ end
92
+
93
+ def test_successful_simple_request
94
+ env = Rack::MockRequest.env_for("/twirp/foopkg.FooService/DoFoo", method: "POST",
95
+ input: '{"foo": "World"}', "CONTENT_TYPE" => "application/json")
96
+
97
+ svc = FooPkg::FooService.new(FooHandler.new)
98
+ status, headers, body = svc.call(env)
99
+
100
+ assert_equal 200, status
101
+ assert_equal 'application/json', headers['Content-Type']
102
+ assert_equal body[0], '{"bar":"Hello World"}'
103
+ end
104
+
105
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: twirp
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.2.1
4
+ version: 0.0.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Cyrus A. Forbes
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2018-02-06 00:00:00.000000000 Z
12
+ date: 2018-02-16 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: google-protobuf
@@ -51,19 +51,21 @@ files:
51
51
  - ".gitignore"
52
52
  - Gemfile
53
53
  - Gemfile.lock
54
+ - LICENSE
54
55
  - README.md
55
- - examples/Gemfile
56
- - examples/Gemfile.lock
57
- - examples/gen/haberdasher_pb.rb
58
- - examples/gen/haberdasher_twirp.rb
59
- - examples/haberdasher.proto
60
- - examples/main.rb
56
+ - example/Gemfile
57
+ - example/Gemfile.lock
58
+ - example/gen/haberdasher_pb.rb
59
+ - example/gen/haberdasher_twirp.rb
60
+ - example/haberdasher.proto
61
+ - example/main.rb
61
62
  - lib/twirp.rb
62
63
  - lib/twirp/error.rb
63
64
  - lib/twirp/service.rb
64
65
  - lib/twirp/version.rb
65
66
  - protoc-gen-twirp_ruby/main.go
66
67
  - test/error_test.rb
68
+ - test/service_test.rb
67
69
  - twirp.gemspec
68
70
  homepage: https://github.com/cyrusaf/ruby-twirp
69
71
  licenses:
@@ -91,3 +93,4 @@ specification_version: 4
91
93
  summary: Twirp services in Ruby.
92
94
  test_files:
93
95
  - test/error_test.rb
96
+ - test/service_test.rb
@@ -1,7 +0,0 @@
1
- # Code generated by protoc-gen-twirp_ruby, DO NOT EDIT.
2
- require 'twirp'
3
-
4
- class HaberdasherService < Twirp::Service
5
- PATH_PREFIX = "/twirp/examples.Haberdasher"
6
- rpc :HelloWorld, Examples::HelloWorldRequest, Examples::HelloWorldResponse
7
- end
data/examples/main.rb DELETED
@@ -1,12 +0,0 @@
1
- require 'rack'
2
- require_relative 'gen/haberdasher_pb.rb'
3
- require_relative 'gen/haberdasher_twirp.rb'
4
-
5
- class HaberdasherImplementation
6
- def HelloWorld(req)
7
- return Examples::HelloWorldResponse.new(message: "Hello #{req.name}")
8
- end
9
- end
10
-
11
- svc = HaberdasherImplementation.new()
12
- Rack::Handler::WEBrick.run HaberdasherService.new(svc).handler