tonic-rails 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +34 -1
- data/Cargo.lock +1 -1
- data/README.md +104 -2
- data/ext/tonic_rails_native/Cargo.toml +1 -1
- data/ext/tonic_rails_native/src/dispatch.rs +23 -1
- data/ext/tonic_rails_native/src/gvl.rs +22 -0
- data/ext/tonic_rails_native/src/lib.rs +1 -0
- data/ext/tonic_rails_native/src/server.rs +21 -0
- data/lib/generators/tonic_rails/install/install_generator.rb +45 -0
- data/lib/generators/tonic_rails/install/templates/tonic_rails.rb.tt +21 -0
- data/lib/generators/tonic_rails/service/service_generator.rb +110 -0
- data/lib/generators/tonic_rails/service/templates/handler.rb.tt +38 -0
- data/lib/generators/tonic_rails/service/templates/service.proto.tt +16 -0
- data/lib/generators/tonic_rails/service/templates/service_spec.rb.tt +17 -0
- data/lib/generators/tonic_rails/service/templates/service_test.rb.tt +14 -0
- data/lib/tonic/rails/base.rb +104 -5
- data/lib/tonic/rails/configuration.rb +25 -3
- data/lib/tonic/rails/health.rb +105 -0
- data/lib/tonic/rails/peer.rb +60 -0
- data/lib/tonic/rails/router.rb +1 -0
- data/lib/tonic/rails/server.rb +23 -0
- data/lib/tonic/rails/tasks/tonic-rails.rake +13 -1
- data/lib/tonic/rails/testing/errors.rb +47 -0
- data/lib/tonic/rails/testing/minitest.rb +44 -0
- data/lib/tonic/rails/testing/rspec.rb +53 -0
- data/lib/tonic/rails/testing.rb +5 -3
- data/lib/tonic/rails/version.rb +1 -1
- data/lib/tonic-rails.rb +2 -0
- metadata +13 -1
data/lib/tonic/rails/base.rb
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "active_support/callbacks"
|
|
4
|
+
require "active_support/rescuable"
|
|
3
5
|
require "active_support/core_ext/class/attribute"
|
|
4
6
|
require "active_support/core_ext/hash/keys"
|
|
5
7
|
require "active_support/core_ext/string/inflections"
|
|
@@ -25,8 +27,17 @@ module Tonic
|
|
|
25
27
|
# is set (fastest), or string-keyed Hashes by default. Handlers may
|
|
26
28
|
# return either a protobuf message or a Hash; streaming handlers
|
|
27
29
|
# return any Enumerable of them.
|
|
30
|
+
#
|
|
31
|
+
# Like controllers, handlers get callbacks and exception mapping:
|
|
32
|
+
#
|
|
33
|
+
# before_rpc :authenticate, except: :Health
|
|
34
|
+
# rescue_from ActiveRecord::RecordNotFound, code: :not_found
|
|
35
|
+
# rescue_from Pundit::NotAuthorizedError, with: :forbidden
|
|
28
36
|
module Base
|
|
29
37
|
def self.included(base)
|
|
38
|
+
base.include(ActiveSupport::Callbacks)
|
|
39
|
+
base.include(ActiveSupport::Rescuable)
|
|
40
|
+
base.define_callbacks(:rpc)
|
|
30
41
|
base.extend(ClassMethods)
|
|
31
42
|
base.class_attribute :grpc_service_name, instance_writer: false
|
|
32
43
|
base.class_attribute :grpc_rpcs, instance_writer: false, default: {}
|
|
@@ -34,6 +45,20 @@ module Tonic
|
|
|
34
45
|
end
|
|
35
46
|
|
|
36
47
|
module ClassMethods
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
def add_rpc_callback(kind, methods, only, except, block)
|
|
51
|
+
only &&= rpc_name_matcher(only)
|
|
52
|
+
except &&= rpc_name_matcher(except)
|
|
53
|
+
condition = lambda do |handler|
|
|
54
|
+
name = handler.current_rpc.underscore
|
|
55
|
+
(only.nil? || only.include?(name)) && (except.nil? || !except.include?(name))
|
|
56
|
+
end
|
|
57
|
+
(methods + [block].compact).each { |callback| set_callback(:rpc, kind, callback, if: condition) }
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
public
|
|
61
|
+
|
|
37
62
|
# @param name [String] fully-qualified service name, e.g. "shop.ProductService"
|
|
38
63
|
def service(name)
|
|
39
64
|
self.grpc_service_name = name.to_s
|
|
@@ -97,6 +122,51 @@ module Tonic
|
|
|
97
122
|
end
|
|
98
123
|
end
|
|
99
124
|
|
|
125
|
+
# Run a method or block before each RPC. Raising (e.g. an RpcError)
|
|
126
|
+
# stops the call. The decoded `request` is available.
|
|
127
|
+
# @param only [Symbol, String, Array] RPC names to apply to
|
|
128
|
+
# @param except [Symbol, String, Array] RPC names to skip
|
|
129
|
+
def before_rpc(*methods, only: nil, except: nil, &block)
|
|
130
|
+
add_rpc_callback(:before, methods, only, except, block)
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Run after each RPC that completes without raising (for streaming
|
|
134
|
+
# responses, after the last message is sent).
|
|
135
|
+
def after_rpc(*methods, only: nil, except: nil, &block)
|
|
136
|
+
add_rpc_callback(:after, methods, only, except, block)
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Wrap each RPC; the method or block must yield to run it.
|
|
140
|
+
def around_rpc(*methods, only: nil, except: nil, &block)
|
|
141
|
+
add_rpc_callback(:around, methods, only, except, block)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Map exceptions raised during an RPC (including callbacks) to a
|
|
145
|
+
# gRPC status. Same as ActiveSupport::Rescuable, plus a `code:`
|
|
146
|
+
# shorthand:
|
|
147
|
+
#
|
|
148
|
+
# rescue_from ActiveRecord::RecordNotFound, code: :not_found
|
|
149
|
+
# rescue_from Stale, code: :aborted, message: "please retry"
|
|
150
|
+
# rescue_from Denied, with: :deny # def deny(e) = raise RpcError...
|
|
151
|
+
#
|
|
152
|
+
# With `code:`, the client receives `message` (a String, or a Proc
|
|
153
|
+
# given the exception), defaulting to the exception's own message.
|
|
154
|
+
# Handlers given via `with:` or a block must raise an RpcError.
|
|
155
|
+
def rescue_from(*klasses, with: nil, code: nil, message: nil, &)
|
|
156
|
+
return super(*klasses, with: with, &) unless code
|
|
157
|
+
|
|
158
|
+
RpcError.normalize_code(code) # fail at definition time on typos
|
|
159
|
+
super(*klasses) do |exception|
|
|
160
|
+
text = message.respond_to?(:call) ? message.call(exception) : (message || exception.message)
|
|
161
|
+
raise RpcError.new(text, code: code)
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# @api private
|
|
166
|
+
def rpc_name_matcher(names)
|
|
167
|
+
Array(names).map { |name| name.to_s.underscore }
|
|
168
|
+
end
|
|
169
|
+
|
|
100
170
|
# @api private Called by Server#register.
|
|
101
171
|
def register_on(router)
|
|
102
172
|
raise NotConfiguredError, "#{self} has no service name; call `service` or `rpc_service`" unless grpc_service_name
|
|
@@ -106,6 +176,18 @@ module Tonic
|
|
|
106
176
|
end
|
|
107
177
|
end
|
|
108
178
|
|
|
179
|
+
# The RPC being handled, as named in the .proto (e.g. "GetItem").
|
|
180
|
+
# @return [String]
|
|
181
|
+
attr_reader :current_rpc
|
|
182
|
+
|
|
183
|
+
# The client: address, and certificate with mutual TLS.
|
|
184
|
+
# @return [Tonic::Rails::Peer]
|
|
185
|
+
attr_reader :peer
|
|
186
|
+
|
|
187
|
+
# The decoded request: a message (or Hash), or for client-streaming
|
|
188
|
+
# RPCs an Enumerator of them. Also passed to the handler method.
|
|
189
|
+
attr_reader :request
|
|
190
|
+
|
|
109
191
|
# gRPC request metadata (lower-case header names). Binary (`-bin`)
|
|
110
192
|
# values are base64-encoded, as sent on the wire.
|
|
111
193
|
# @return [Hash{String=>String}]
|
|
@@ -152,29 +234,46 @@ module Tonic
|
|
|
152
234
|
# (`#push`) for server-streaming RPCs.
|
|
153
235
|
# @return [String, nil] the encoded unary response, or nil when
|
|
154
236
|
# messages were streamed through `sender`
|
|
155
|
-
def call_rpc(rpc_name, metadata:, reader:, sender: nil, timeout_ms: nil)
|
|
237
|
+
def call_rpc(rpc_name, metadata:, reader:, sender: nil, timeout_ms: nil, peer: nil)
|
|
156
238
|
spec = self.class.grpc_rpcs[rpc_name.to_s]
|
|
157
239
|
raise RpcError.new("method not implemented", code: :unimplemented) unless spec
|
|
158
240
|
raise RpcError.new("method #{rpc_name} not implemented", code: :unimplemented) unless respond_to?(spec[:handler])
|
|
159
241
|
|
|
242
|
+
@current_rpc = rpc_name.to_s
|
|
243
|
+
@peer = peer || Peer.new
|
|
160
244
|
@grpc_metadata = metadata
|
|
161
245
|
@grpc_sender = sender
|
|
162
246
|
@grpc_headers_sent = false
|
|
163
247
|
@grpc_deadline_at = timeout_ms && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + (timeout_ms / 1000.0))
|
|
164
248
|
|
|
165
|
-
|
|
166
|
-
|
|
249
|
+
@request = build_request(reader, spec)
|
|
250
|
+
response = nil
|
|
251
|
+
run_callbacks(:rpc) { response = respond(public_send(spec[:handler], @request), spec, sender) }
|
|
252
|
+
response
|
|
167
253
|
rescue RpcError
|
|
168
254
|
raise
|
|
169
255
|
rescue StandardError => e
|
|
170
|
-
|
|
171
|
-
raise RpcError.new("internal error", code: :internal)
|
|
256
|
+
rescue_exception(e)
|
|
172
257
|
ensure
|
|
173
258
|
attach_trailing_metadata
|
|
174
259
|
end
|
|
175
260
|
|
|
176
261
|
private
|
|
177
262
|
|
|
263
|
+
# rescue_from handlers must raise; anything they don't handle (or a
|
|
264
|
+
# handler that returns normally) becomes a logged INTERNAL error.
|
|
265
|
+
def rescue_exception(exception)
|
|
266
|
+
if rescue_with_handler(exception)
|
|
267
|
+
Tonic::Rails.log_exception(
|
|
268
|
+
TypeError.new("rescue_from handler for #{exception.class} returned instead of raising an RpcError"),
|
|
269
|
+
"#{self.class}##{current_rpc}",
|
|
270
|
+
)
|
|
271
|
+
else
|
|
272
|
+
Tonic::Rails.log_exception(exception, "#{self.class}##{current_rpc}")
|
|
273
|
+
end
|
|
274
|
+
raise RpcError.new("internal error", code: :internal)
|
|
275
|
+
end
|
|
276
|
+
|
|
178
277
|
def build_request(reader, spec)
|
|
179
278
|
unless spec[:request_stream]
|
|
180
279
|
return read_request(reader, spec) || raise(RpcError.new("missing request message", code: :invalid_argument))
|
|
@@ -69,6 +69,17 @@ module Tonic
|
|
|
69
69
|
# HTTP/2 PING interval and ack timeout, in seconds. Defaults 15 / 5.
|
|
70
70
|
attr_accessor :keepalive_interval, :keepalive_timeout
|
|
71
71
|
|
|
72
|
+
# Callable checked every `health_check_interval` seconds (inside the
|
|
73
|
+
# Rails executor). While it returns false or raises, grpc.health.v1
|
|
74
|
+
# reports NOT_SERVING so readiness probes and load balancers route
|
|
75
|
+
# around this instance. Default nil (always SERVING while up).
|
|
76
|
+
#
|
|
77
|
+
# config.health_check = -> { ActiveRecord::Base.connection.active? }
|
|
78
|
+
attr_accessor :health_check
|
|
79
|
+
|
|
80
|
+
# Seconds between health checks. Default 5.
|
|
81
|
+
attr_accessor :health_check_interval
|
|
82
|
+
|
|
72
83
|
# Look handler classes up again on each request so code reloading
|
|
73
84
|
# works. The Railtie enables this when Rails reloading is on.
|
|
74
85
|
attr_accessor :reload_handlers
|
|
@@ -94,6 +105,8 @@ module Tonic
|
|
|
94
105
|
@keepalive_interval = 15
|
|
95
106
|
@keepalive_timeout = 5
|
|
96
107
|
@reload_handlers = false
|
|
108
|
+
@health_check = nil
|
|
109
|
+
@health_check_interval = 5
|
|
97
110
|
end
|
|
98
111
|
|
|
99
112
|
def tls?
|
|
@@ -113,15 +126,24 @@ module Tonic
|
|
|
113
126
|
raise ArgumentError, "max_message_size must be at most 4 GiB" if max_message_size > 0xFFFF_FFFF
|
|
114
127
|
raise ArgumentError, "tls_cert_path and tls_key_path must be set together" if tls_cert_path.nil? != tls_key_path.nil?
|
|
115
128
|
raise ArgumentError, "tls_client_ca_path requires tls_cert_path and tls_key_path" if tls_client_ca_path && !tls?
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
end
|
|
129
|
+
|
|
130
|
+
validate_callables!
|
|
119
131
|
|
|
120
132
|
self
|
|
121
133
|
end
|
|
122
134
|
|
|
123
135
|
private
|
|
124
136
|
|
|
137
|
+
def validate_callables!
|
|
138
|
+
raise ArgumentError, "health_check must respond to #call" if health_check && !health_check.respond_to?(:call)
|
|
139
|
+
unless health_check_interval.is_a?(Numeric) && health_check_interval.positive?
|
|
140
|
+
raise ArgumentError, "health_check_interval must be a positive number, got #{health_check_interval.inspect}"
|
|
141
|
+
end
|
|
142
|
+
return if interceptors.respond_to?(:each) && interceptors.all? { |i| i.respond_to?(:call) }
|
|
143
|
+
|
|
144
|
+
raise ArgumentError, "interceptors must be an Array of callables"
|
|
145
|
+
end
|
|
146
|
+
|
|
125
147
|
def positive_integer!(name)
|
|
126
148
|
value = public_send(name)
|
|
127
149
|
return if value.is_a?(Integer) && value.positive?
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Tonic
|
|
4
|
+
module Rails
|
|
5
|
+
# What grpc.health.v1 reports, per service ("" = the whole server).
|
|
6
|
+
#
|
|
7
|
+
# A service reports SERVING only while the app hasn't marked it
|
|
8
|
+
# NOT_SERVING (Server#not_serving!) *and* the optional
|
|
9
|
+
# `config.health_check` passes. Neither overrides the other.
|
|
10
|
+
# @api private
|
|
11
|
+
class Health
|
|
12
|
+
def initialize(configuration, router)
|
|
13
|
+
@configuration = configuration
|
|
14
|
+
@router = router
|
|
15
|
+
@marks = {}
|
|
16
|
+
@check_passing = true
|
|
17
|
+
@native = nil
|
|
18
|
+
@checker = nil
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def mark(services, serving)
|
|
22
|
+
names = services.empty? ? names_to_report : services.map(&:to_s)
|
|
23
|
+
names.each { |name| @marks[name] = serving }
|
|
24
|
+
publish(names)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Start reporting through a running native server.
|
|
28
|
+
def attach(native)
|
|
29
|
+
@native = native
|
|
30
|
+
@check_passing = true
|
|
31
|
+
publish(names_to_report)
|
|
32
|
+
start_checker
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Stop the checker before shutdown flips everything NOT_SERVING, so
|
|
36
|
+
# a passing check can't flip it back.
|
|
37
|
+
def detach
|
|
38
|
+
stop_checker
|
|
39
|
+
@native = nil
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def names_to_report
|
|
45
|
+
["", *@router.service_names, *@marks.keys].uniq
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def publish(names)
|
|
49
|
+
native = @native
|
|
50
|
+
return unless native
|
|
51
|
+
|
|
52
|
+
names.each { |name| native.set_health(name, @check_passing && @marks.fetch(name, true)) }
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def start_checker
|
|
56
|
+
check = @configuration.health_check
|
|
57
|
+
return unless check
|
|
58
|
+
|
|
59
|
+
@wakeup = Thread::Queue.new
|
|
60
|
+
@checker = Thread.new do
|
|
61
|
+
Thread.current.name = "tonic-rails-health"
|
|
62
|
+
loop do
|
|
63
|
+
passing = run_check(check)
|
|
64
|
+
changed(passing) if passing != @check_passing
|
|
65
|
+
break if @wakeup.pop(timeout: @configuration.health_check_interval)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def stop_checker
|
|
71
|
+
return unless @checker
|
|
72
|
+
|
|
73
|
+
@wakeup << :stop
|
|
74
|
+
@checker.join(@configuration.drain_timeout.to_f + 5)
|
|
75
|
+
@checker = nil
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def changed(passing)
|
|
79
|
+
@check_passing = passing
|
|
80
|
+
publish(names_to_report)
|
|
81
|
+
logger = @configuration.logger
|
|
82
|
+
return unless logger
|
|
83
|
+
|
|
84
|
+
if passing
|
|
85
|
+
logger.info("tonic-rails: health check passing; SERVING")
|
|
86
|
+
else
|
|
87
|
+
logger.warn("tonic-rails: health check failing; NOT_SERVING")
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# Runs inside the Rails executor so database connections are returned.
|
|
92
|
+
def run_check(check)
|
|
93
|
+
result = if defined?(::Rails.application) && ::Rails.application
|
|
94
|
+
::Rails.application.executor.wrap { check.call }
|
|
95
|
+
else
|
|
96
|
+
check.call
|
|
97
|
+
end
|
|
98
|
+
result ? true : false
|
|
99
|
+
rescue StandardError => e
|
|
100
|
+
Tonic::Rails.log_exception(e, "health check")
|
|
101
|
+
false
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Tonic
|
|
4
|
+
module Rails
|
|
5
|
+
# The client on the other end of an RPC, available in handlers as
|
|
6
|
+
# `peer`:
|
|
7
|
+
#
|
|
8
|
+
# peer.address # => "10.0.4.17:51234"
|
|
9
|
+
# peer.ip # => "10.0.4.17"
|
|
10
|
+
# peer.certificate # => OpenSSL::X509::Certificate, with mutual TLS
|
|
11
|
+
# peer.certificate&.subject.to_s # => "/CN=billing-service"
|
|
12
|
+
class Peer
|
|
13
|
+
# @return [String, nil] "ip:port" ("[ipv6]:port" for IPv6)
|
|
14
|
+
attr_reader :address
|
|
15
|
+
|
|
16
|
+
# @param address [String, nil]
|
|
17
|
+
# @param certificates [Array<String>] DER-encoded chain, leaf first
|
|
18
|
+
def initialize(address = nil, certificates = [])
|
|
19
|
+
@address = address
|
|
20
|
+
@certificate_ders = certificates
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# @return [String, nil]
|
|
24
|
+
def ip
|
|
25
|
+
return unless address
|
|
26
|
+
|
|
27
|
+
host = address.rpartition(":").first
|
|
28
|
+
host.delete_prefix("[").delete_suffix("]")
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @return [Integer, nil]
|
|
32
|
+
def port
|
|
33
|
+
address && Integer(address.rpartition(":").last, exception: false)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# The client certificate presented over mutual TLS, or nil.
|
|
37
|
+
# @return [OpenSSL::X509::Certificate, nil]
|
|
38
|
+
def certificate
|
|
39
|
+
certificate_chain.first
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# @return [Array<OpenSSL::X509::Certificate>] leaf first
|
|
43
|
+
def certificate_chain
|
|
44
|
+
@certificate_chain ||= begin
|
|
45
|
+
require "openssl"
|
|
46
|
+
@certificate_ders.map { |der| OpenSSL::X509::Certificate.new(der) }
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# True when the client authenticated with a certificate.
|
|
51
|
+
def authenticated?
|
|
52
|
+
!@certificate_ders.empty?
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def inspect
|
|
56
|
+
"#<#{self.class.name} #{address || 'unknown'}#{' (certificate)' if authenticated?}>"
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
data/lib/tonic/rails/router.rb
CHANGED
data/lib/tonic/rails/server.rb
CHANGED
|
@@ -22,6 +22,7 @@ module Tonic
|
|
|
22
22
|
@state = :stopped
|
|
23
23
|
@stop_signal = nil
|
|
24
24
|
@stop_requested = false
|
|
25
|
+
@health = Health.new(configuration, @router)
|
|
25
26
|
@lock = Mutex.new
|
|
26
27
|
end
|
|
27
28
|
|
|
@@ -58,6 +59,7 @@ module Tonic
|
|
|
58
59
|
@native = build_native_server
|
|
59
60
|
@native.start_server
|
|
60
61
|
log_pump = spawn_log_pump
|
|
62
|
+
@health.attach(@native)
|
|
61
63
|
@state = :running
|
|
62
64
|
|
|
63
65
|
request_log = subscribe_request_logger
|
|
@@ -67,10 +69,12 @@ module Tonic
|
|
|
67
69
|
yield self if block_given?
|
|
68
70
|
|
|
69
71
|
wait_for_stop(workers)
|
|
72
|
+
@health.detach
|
|
70
73
|
shutdown(workers)
|
|
71
74
|
ensure
|
|
72
75
|
ActiveSupport::Notifications.unsubscribe(request_log) if request_log
|
|
73
76
|
previous_handlers&.each { |signal, handler| Signal.trap(signal, handler || "DEFAULT") }
|
|
77
|
+
@health.detach
|
|
74
78
|
@native&.stop_server
|
|
75
79
|
stop_log_pump(log_pump)
|
|
76
80
|
@native = nil
|
|
@@ -91,6 +95,25 @@ module Tonic
|
|
|
91
95
|
@state == :running
|
|
92
96
|
end
|
|
93
97
|
|
|
98
|
+
# Mark the whole server, or the given services (fully-qualified
|
|
99
|
+
# names), SERVING in grpc.health.v1. Takes effect immediately when
|
|
100
|
+
# running, otherwise when the server starts.
|
|
101
|
+
#
|
|
102
|
+
# With `config.health_check`, a service reports SERVING only while the
|
|
103
|
+
# check passes *and* it's marked serving here.
|
|
104
|
+
def serving!(*services)
|
|
105
|
+
@health.mark(services, true)
|
|
106
|
+
self
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Mark the whole server, or the given services, NOT_SERVING (e.g. for
|
|
110
|
+
# maintenance), so load balancers and readiness probes route around
|
|
111
|
+
# this instance. Calls are still served.
|
|
112
|
+
def not_serving!(*services)
|
|
113
|
+
@health.mark(services, false)
|
|
114
|
+
self
|
|
115
|
+
end
|
|
116
|
+
|
|
94
117
|
# @return [Hash{Symbol=>Integer}] request and connection counters
|
|
95
118
|
def stats
|
|
96
119
|
native = @native
|
|
@@ -27,7 +27,19 @@ namespace :tonic_rails do
|
|
|
27
27
|
ruby_out = ENV.fetch("RUBY_OUT", "lib/grpc")
|
|
28
28
|
protos = Dir.glob(File.join(proto_dir, "**", "*.proto"))
|
|
29
29
|
abort "No .proto files found in #{proto_dir}/" if protos.empty?
|
|
30
|
-
|
|
30
|
+
version = begin
|
|
31
|
+
IO.popen(%w[protoc --version], err: File::NULL, &:read)[/\d+(\.\d+)+/]
|
|
32
|
+
rescue SystemCallError
|
|
33
|
+
nil
|
|
34
|
+
end
|
|
35
|
+
abort "protoc not found on PATH. Install the Protocol Buffers compiler (22.0 or newer)." unless version
|
|
36
|
+
# protoc before 22 emits the Ruby DSL that google-protobuf 4 removed
|
|
37
|
+
# (`undefined method 'build' for DescriptorPool` at load time).
|
|
38
|
+
major = version.split(".").then { |parts| parts.first == "3" ? parts[1].to_i : parts.first.to_i }
|
|
39
|
+
if major < 22
|
|
40
|
+
abort "protoc #{version} is too old for google-protobuf 4: install protoc 22.0 or newer " \
|
|
41
|
+
"(distribution packages are often older; see https://github.com/protocolbuffers/protobuf/releases)."
|
|
42
|
+
end
|
|
31
43
|
|
|
32
44
|
FileUtils.mkdir_p(ruby_out)
|
|
33
45
|
sh "protoc", "--ruby_out=#{ruby_out}", "-I#{proto_dir}", *protos
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Tonic
|
|
4
|
+
module Rails
|
|
5
|
+
module Testing
|
|
6
|
+
# Shared helpers for the RSpec matcher and Minitest assertions.
|
|
7
|
+
# @api private
|
|
8
|
+
module Errors
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# Exceptions that carry a gRPC status: tonic-rails' own, and the
|
|
12
|
+
# official grpc gem client's, when it's loaded.
|
|
13
|
+
def classes
|
|
14
|
+
[Tonic::Rails::RpcError, (GRPC::BadStatus if defined?(GRPC::BadStatus))].compact
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def status?(error)
|
|
18
|
+
classes.any? { |klass| error.is_a?(klass) }
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# @return [Integer]
|
|
22
|
+
def code(error)
|
|
23
|
+
error.code
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# @return [String] the status message the client sees. The grpc
|
|
27
|
+
# gem keeps it in #details (its #message adds the code).
|
|
28
|
+
def message(error)
|
|
29
|
+
text = defined?(GRPC::BadStatus) && error.is_a?(GRPC::BadStatus) ? error.details.to_s : error.message
|
|
30
|
+
text.dup.force_encoding(Encoding::UTF_8)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def code_name(code)
|
|
34
|
+
Tonic::Rails::RpcError::CODE_NAMES.fetch(code, code)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def message_matches?(expected, actual)
|
|
38
|
+
expected.is_a?(Regexp) ? expected.match?(actual) : expected.to_s == actual
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def describe(error)
|
|
42
|
+
"#{code_name(code(error)).to_s.upcase} (#{message(error).inspect})"
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "tonic/rails/testing"
|
|
4
|
+
require "tonic/rails/testing/errors"
|
|
5
|
+
|
|
6
|
+
module Tonic
|
|
7
|
+
module Rails
|
|
8
|
+
module Testing
|
|
9
|
+
# Minitest assertions for gRPC statuses:
|
|
10
|
+
#
|
|
11
|
+
# class ItemServiceTest < ActiveSupport::TestCase
|
|
12
|
+
# include Tonic::Rails::Testing::Assertions
|
|
13
|
+
#
|
|
14
|
+
# test "missing items" do
|
|
15
|
+
# error = assert_grpc_error(:not_found) { Tonic::Rails::Testing.call(ItemService, :GetItem, { id: 0 }) }
|
|
16
|
+
# assert_match(/0/, error.message)
|
|
17
|
+
# end
|
|
18
|
+
# end
|
|
19
|
+
module Assertions
|
|
20
|
+
# Asserts the block raises a gRPC status (Tonic::Rails::RpcError or
|
|
21
|
+
# GRPC::BadStatus) with the given code and, optionally, message
|
|
22
|
+
# (String or Regexp). Returns the error.
|
|
23
|
+
def assert_grpc_error(code = nil, message = nil, &)
|
|
24
|
+
errors = Testing::Errors
|
|
25
|
+
error = assert_raises(*errors.classes, &)
|
|
26
|
+
if code
|
|
27
|
+
expected = Tonic::Rails::RpcError.normalize_code(code)
|
|
28
|
+
assert_equal(
|
|
29
|
+
errors.code_name(expected), errors.code_name(errors.code(error)),
|
|
30
|
+
"Expected gRPC status #{errors.code_name(expected).to_s.upcase}, got #{errors.describe(error)}"
|
|
31
|
+
)
|
|
32
|
+
end
|
|
33
|
+
if message
|
|
34
|
+
assert(
|
|
35
|
+
errors.message_matches?(message, errors.message(error)),
|
|
36
|
+
"Expected gRPC message #{message.inspect}, got #{errors.message(error).inspect}",
|
|
37
|
+
)
|
|
38
|
+
end
|
|
39
|
+
error
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rspec/expectations"
|
|
4
|
+
require "tonic/rails/testing"
|
|
5
|
+
require "tonic/rails/testing/errors"
|
|
6
|
+
|
|
7
|
+
# Matches a block that ends with a gRPC status, raised as a
|
|
8
|
+
# Tonic::Rails::RpcError (Testing.call) or a GRPC::BadStatus (the official
|
|
9
|
+
# client):
|
|
10
|
+
#
|
|
11
|
+
# expect { Tonic::Rails::Testing.call(ItemService, :GetItem, { id: 0 }) }
|
|
12
|
+
# .to raise_grpc_error(:not_found)
|
|
13
|
+
# expect { stub.get_item(request) }.to raise_grpc_error(:invalid_argument).with_message(/name/)
|
|
14
|
+
# expect { ... }.to raise_grpc_error # any non-OK status
|
|
15
|
+
RSpec::Matchers.define :raise_grpc_error do |expected_code = nil|
|
|
16
|
+
errors = Tonic::Rails::Testing::Errors
|
|
17
|
+
|
|
18
|
+
supports_block_expectations
|
|
19
|
+
|
|
20
|
+
chain(:with_message) { |message| @expected_message = message }
|
|
21
|
+
|
|
22
|
+
match do |block|
|
|
23
|
+
@expected = expected_code && Tonic::Rails::RpcError.normalize_code(expected_code)
|
|
24
|
+
begin
|
|
25
|
+
block.call
|
|
26
|
+
@error = nil
|
|
27
|
+
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
28
|
+
raise unless errors.status?(e)
|
|
29
|
+
|
|
30
|
+
@error = e
|
|
31
|
+
end
|
|
32
|
+
return false unless @error
|
|
33
|
+
|
|
34
|
+
(@expected.nil? || errors.code(@error) == @expected) &&
|
|
35
|
+
(!defined?(@expected_message) || errors.message_matches?(@expected_message, errors.message(@error)))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
description do
|
|
39
|
+
text = +"raise a gRPC error"
|
|
40
|
+
text << " #{errors.code_name(@expected).to_s.upcase}" if @expected
|
|
41
|
+
text << " with message #{@expected_message.inspect}" if defined?(@expected_message)
|
|
42
|
+
text
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
failure_message do
|
|
46
|
+
actual = @error ? "got #{errors.describe(@error)}" : "nothing was raised"
|
|
47
|
+
"expected block to #{description}, but #{actual}"
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
failure_message_when_negated do
|
|
51
|
+
"expected block not to #{description}, but got #{errors.describe(@error)}"
|
|
52
|
+
end
|
|
53
|
+
end
|
data/lib/tonic/rails/testing.rb
CHANGED
|
@@ -65,11 +65,12 @@ module Tonic
|
|
|
65
65
|
# request; an Array of them for client- and bidi-streaming RPCs
|
|
66
66
|
# @param metadata [Hash{String=>String}]
|
|
67
67
|
# @param timeout_ms [Integer, nil] simulated client deadline
|
|
68
|
+
# @param peer [Tonic::Rails::Peer, nil] simulated client (address, certificates)
|
|
68
69
|
# @return [Google::Protobuf::AbstractMessage, Array] the response, or
|
|
69
70
|
# an Array of responses for server- and bidi-streaming RPCs
|
|
70
71
|
# @raise [RpcError] when the handler ends the call with a status
|
|
71
|
-
def call(service_class, rpc_name, request, metadata: {}, timeout_ms: nil)
|
|
72
|
-
invoke(service_class, rpc_name, request, metadata: metadata, timeout_ms: timeout_ms).response
|
|
72
|
+
def call(service_class, rpc_name, request, metadata: {}, timeout_ms: nil, peer: nil)
|
|
73
|
+
invoke(service_class, rpc_name, request, metadata: metadata, timeout_ms: timeout_ms, peer: peer).response
|
|
73
74
|
end
|
|
74
75
|
|
|
75
76
|
# Like #call, but returns a Result with the response metadata too:
|
|
@@ -80,7 +81,7 @@ module Tonic
|
|
|
80
81
|
# result.trailers["x-cost-ms"] # => "3"
|
|
81
82
|
#
|
|
82
83
|
# @return [Result]
|
|
83
|
-
def invoke(service_class, rpc_name, request, metadata: {}, timeout_ms: nil)
|
|
84
|
+
def invoke(service_class, rpc_name, request, metadata: {}, timeout_ms: nil, peer: nil)
|
|
84
85
|
spec = service_class.grpc_rpcs.fetch(rpc_name.to_s) do
|
|
85
86
|
raise ArgumentError, "#{service_class} has no RPC #{rpc_name}"
|
|
86
87
|
end
|
|
@@ -95,6 +96,7 @@ module Tonic
|
|
|
95
96
|
reader: reader,
|
|
96
97
|
sender: sender,
|
|
97
98
|
timeout_ms: timeout_ms,
|
|
99
|
+
peer: peer,
|
|
98
100
|
)
|
|
99
101
|
|
|
100
102
|
response = if spec[:response_stream]
|
data/lib/tonic/rails/version.rb
CHANGED
data/lib/tonic-rails.rb
CHANGED
|
@@ -11,11 +11,13 @@ end
|
|
|
11
11
|
|
|
12
12
|
require "tonic/rails/version"
|
|
13
13
|
require "tonic/rails/metadata"
|
|
14
|
+
require "tonic/rails/peer"
|
|
14
15
|
require "tonic/rails/rpc_error"
|
|
15
16
|
require "tonic/rails/configuration"
|
|
16
17
|
require "tonic/rails/router"
|
|
17
18
|
require "tonic/rails/instrumentation"
|
|
18
19
|
require "tonic/rails/base"
|
|
20
|
+
require "tonic/rails/health"
|
|
19
21
|
require "tonic/rails/reflection"
|
|
20
22
|
require "tonic/rails/server"
|
|
21
23
|
|