tonic-rails 0.2.0 → 0.4.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.
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ruby code generated from app/protos by `bin/rails tonic_rails:compile_protos`
4
+ # lives in lib/grpc. Its files require each other by plain name, so put the
5
+ # directory on the load path and keep Zeitwerk away from it.
6
+ Rails.root.join("lib/grpc").then do |generated|
7
+ $LOAD_PATH.unshift(generated.to_s) unless $LOAD_PATH.include?(generated.to_s)
8
+ Rails.autoloaders.main.ignore(generated)
9
+ end
10
+
11
+ Tonic::Rails.configure do |config|
12
+ # config.bind_address = "0.0.0.0:50051"
13
+ # config.dispatch_threads = ENV.fetch("RAILS_MAX_THREADS", 5).to_i
14
+ # config.reflection = Rails.env.development?
15
+ # config.health_check = -> { ActiveRecord::Base.connection.active? }
16
+ end
17
+
18
+ # Handlers in app/grpc are autoloaded; register them here so they're
19
+ # picked up again after code reloads.
20
+ Rails.application.config.to_prepare do
21
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module TonicRails
6
+ module Generators
7
+ # rails generate tonic_rails:service Item GetItem ListItems:server ImportItems:client Sync:bidi
8
+ #
9
+ # Creates a .proto with the service and its messages, a handler with a
10
+ # method per RPC, the handler's registration, and a test.
11
+ class ServiceGenerator < ::Rails::Generators::NamedBase
12
+ source_root File.expand_path("templates", __dir__)
13
+
14
+ STREAM_KINDS = %w[unary server client bidi].freeze
15
+
16
+ argument :rpcs, type: :array, default: [], banner: "Rpc[:server|:client|:bidi] ..."
17
+
18
+ class_option :package, type: :string,
19
+ desc: "Protobuf package (default: <app name>.v1)"
20
+
21
+ def check_rpcs
22
+ rpc_specs.each do |rpc|
23
+ next if rpc[:name].match?(/\A[A-Z][A-Za-z0-9]*\z/) && STREAM_KINDS.include?(rpc[:kind])
24
+
25
+ raise Thor::Error, "Invalid RPC #{rpc[:raw].inspect}: use CamelCase names, optionally :server, :client or :bidi"
26
+ end
27
+ end
28
+
29
+ def create_proto
30
+ template "service.proto.tt", "app/protos/#{package_path}/#{service_file}_service.proto"
31
+ end
32
+
33
+ def create_handler
34
+ template "handler.rb.tt", "app/grpc/#{service_file}_service.rb"
35
+ end
36
+
37
+ def register_handler
38
+ initializer = "config/initializers/tonic_rails.rb"
39
+ invoke "tonic_rails:install", [], skip_next_steps: true unless File.exist?(File.join(destination_root, initializer))
40
+ inject_into_file initializer, " Tonic::Rails.server.register(#{service_class})\n",
41
+ after: "Rails.application.config.to_prepare do\n"
42
+ end
43
+
44
+ def create_test
45
+ if File.directory?(File.join(destination_root, "spec"))
46
+ template "service_spec.rb.tt", "spec/grpc/#{service_file}_service_spec.rb"
47
+ else
48
+ template "service_test.rb.tt", "test/grpc/#{service_file}_service_test.rb"
49
+ end
50
+ end
51
+
52
+ def show_next_steps
53
+ say "\nNext: bin/rails tonic_rails:compile_protos, then fill in app/grpc/#{service_file}_service.rb", :green
54
+ end
55
+
56
+ private
57
+
58
+ # "Item" and "ItemService" both mean the service ItemService.
59
+ def service_base
60
+ class_name.delete_suffix("Service")
61
+ end
62
+
63
+ def service_file
64
+ service_base.underscore
65
+ end
66
+
67
+ def service_class
68
+ "#{service_base}Service"
69
+ end
70
+
71
+ def package
72
+ options[:package] || "#{app_name}.v1"
73
+ end
74
+
75
+ def app_name
76
+ app = defined?(::Rails.application) && ::Rails.application
77
+ name = app ? app.class.module_parent_name : File.basename(destination_root)
78
+ name.to_s.underscore.tr("-", "_").presence || "app"
79
+ end
80
+
81
+ def package_path
82
+ package.tr(".", "/")
83
+ end
84
+
85
+ def ruby_module
86
+ package.split(".").map(&:camelize).join("::")
87
+ end
88
+
89
+ def full_service_name
90
+ "#{package}.#{service_class}"
91
+ end
92
+
93
+ def rpc_specs
94
+ list = rpcs.empty? ? ["Get#{service_base}"] : rpcs
95
+ list.map do |raw|
96
+ name, kind = raw.split(":", 2)
97
+ { raw: raw, name: name.to_s, kind: kind || "unary", method: name.to_s.underscore }
98
+ end
99
+ end
100
+
101
+ def proto_rpc_line(rpc)
102
+ request = "#{rpc[:name]}Request"
103
+ response = "#{rpc[:name]}Response"
104
+ request = "stream #{request}" if %w[client bidi].include?(rpc[:kind])
105
+ response = "stream #{response}" if %w[server bidi].include?(rpc[:kind])
106
+ "rpc #{rpc[:name]}(#{request}) returns (#{response});"
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "<%= package_path %>/<%= service_file %>_service_pb"
4
+
5
+ class <%= service_class %>
6
+ include Tonic::Rails::Base
7
+
8
+ rpc_service "<%= full_service_name %>"
9
+ request_format :message
10
+ <% rpc_specs.each do |rpc| %>
11
+ <% case rpc[:kind] -%>
12
+ <% when "unary" -%>
13
+ # @param request [<%= ruby_module %>::<%= rpc[:name] %>Request]
14
+ # @return [<%= ruby_module %>::<%= rpc[:name] %>Response]
15
+ def <%= rpc[:method] %>(request)
16
+ raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
17
+ end
18
+ <% when "server" -%>
19
+ # @param request [<%= ruby_module %>::<%= rpc[:name] %>Request]
20
+ # @return [Enumerable<<%= ruby_module %>::<%= rpc[:name] %>Response>] each element is streamed as it's produced
21
+ def <%= rpc[:method] %>(request)
22
+ raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
23
+ end
24
+ <% when "client" -%>
25
+ # @param requests [Enumerator<<%= ruby_module %>::<%= rpc[:name] %>Request>] yields messages as they arrive
26
+ # @return [<%= ruby_module %>::<%= rpc[:name] %>Response]
27
+ def <%= rpc[:method] %>(requests)
28
+ raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
29
+ end
30
+ <% else -%>
31
+ # @param requests [Enumerator<<%= ruby_module %>::<%= rpc[:name] %>Request>] yields messages as they arrive
32
+ # @return [Enumerable<<%= ruby_module %>::<%= rpc[:name] %>Response>]
33
+ def <%= rpc[:method] %>(requests)
34
+ raise Tonic::Rails::RpcError.new("<%= rpc[:name] %> is not implemented yet", code: :unimplemented)
35
+ end
36
+ <% end -%>
37
+ <% end -%>
38
+ end
@@ -0,0 +1,16 @@
1
+ syntax = "proto3";
2
+
3
+ package <%= package %>;
4
+
5
+ service <%= service_class %> {
6
+ <% rpc_specs.each do |rpc| -%>
7
+ <%= proto_rpc_line(rpc) %>
8
+ <% end -%>
9
+ }
10
+ <% rpc_specs.each do |rpc| %>
11
+ message <%= rpc[:name] %>Request {
12
+ }
13
+
14
+ message <%= rpc[:name] %>Response {
15
+ }
16
+ <% end -%>
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails_helper"
4
+ require "tonic/rails/testing/rspec"
5
+
6
+ RSpec.describe <%= service_class %> do
7
+ <% rpc_specs.each_with_index do |rpc, i| -%>
8
+ <% if i.positive? %>
9
+ <% end -%>
10
+ describe "<%= rpc[:name] %>" do
11
+ it "is not implemented yet" do
12
+ request = <%= %w[client bidi].include?(rpc[:kind]) ? "[#{ruby_module}::#{rpc[:name]}Request.new]" : "#{ruby_module}::#{rpc[:name]}Request.new" %>
13
+ expect { Tonic::Rails::Testing.call(described_class, :<%= rpc[:name] %>, request) }.to raise_grpc_error(:unimplemented)
14
+ end
15
+ end
16
+ <% end -%>
17
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+ require "tonic/rails/testing/minitest"
5
+
6
+ class <%= service_class %>Test < ActiveSupport::TestCase
7
+ include Tonic::Rails::Testing::Assertions
8
+ <% rpc_specs.each do |rpc| %>
9
+ test "<%= rpc[:name] %> is not implemented yet" do
10
+ request = <%= %w[client bidi].include?(rpc[:kind]) ? "[#{ruby_module}::#{rpc[:name]}Request.new]" : "#{ruby_module}::#{rpc[:name]}Request.new" %>
11
+ assert_grpc_error(:unimplemented) { Tonic::Rails::Testing.call(<%= service_class %>, :<%= rpc[:name] %>, request) }
12
+ end
13
+ <% end -%>
14
+ end
@@ -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
- result = public_send(spec[:handler], build_request(reader, spec))
166
- respond(result, spec, sender)
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
- Tonic::Rails.log_exception(e, "#{self.class}##{rpc_name}")
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))
@@ -66,9 +66,39 @@ module Tonic
66
66
  # API schema; keep it off in production. Default false.
67
67
  attr_accessor :reflection
68
68
 
69
+ # Accept gRPC-Web requests, so browser apps can call services
70
+ # directly (unary and server-streaming RPCs). Also enables HTTP/1.1,
71
+ # which browsers use when there's no TLS. Default false.
72
+ attr_accessor :grpc_web
73
+
74
+ # Browser origins allowed to call gRPC-Web services (CORS), e.g.
75
+ # ["https://app.example.com"]. Empty = same-origin only. "*" allows
76
+ # any origin, without credentials (cookies). Default [].
77
+ attr_accessor :grpc_web_origins
78
+
79
+ # Extra request headers browsers may send (beyond content-type,
80
+ # x-grpc-web, x-user-agent, grpc-timeout and authorization).
81
+ attr_accessor :grpc_web_allowed_headers
82
+
83
+ # Extra response headers browsers may read, e.g. custom response
84
+ # metadata (grpc-status, grpc-message and grpc-status-details-bin are
85
+ # always exposed).
86
+ attr_accessor :grpc_web_exposed_headers
87
+
69
88
  # HTTP/2 PING interval and ack timeout, in seconds. Defaults 15 / 5.
70
89
  attr_accessor :keepalive_interval, :keepalive_timeout
71
90
 
91
+ # Callable checked every `health_check_interval` seconds (inside the
92
+ # Rails executor). While it returns false or raises, grpc.health.v1
93
+ # reports NOT_SERVING so readiness probes and load balancers route
94
+ # around this instance. Default nil (always SERVING while up).
95
+ #
96
+ # config.health_check = -> { ActiveRecord::Base.connection.active? }
97
+ attr_accessor :health_check
98
+
99
+ # Seconds between health checks. Default 5.
100
+ attr_accessor :health_check_interval
101
+
72
102
  # Look handler classes up again on each request so code reloading
73
103
  # works. The Railtie enables this when Rails reloading is on.
74
104
  attr_accessor :reload_handlers
@@ -94,6 +124,12 @@ module Tonic
94
124
  @keepalive_interval = 15
95
125
  @keepalive_timeout = 5
96
126
  @reload_handlers = false
127
+ @grpc_web = false
128
+ @grpc_web_origins = []
129
+ @grpc_web_allowed_headers = []
130
+ @grpc_web_exposed_headers = []
131
+ @health_check = nil
132
+ @health_check_interval = 5
97
133
  end
98
134
 
99
135
  def tls?
@@ -113,15 +149,34 @@ module Tonic
113
149
  raise ArgumentError, "max_message_size must be at most 4 GiB" if max_message_size > 0xFFFF_FFFF
114
150
  raise ArgumentError, "tls_cert_path and tls_key_path must be set together" if tls_cert_path.nil? != tls_key_path.nil?
115
151
  raise ArgumentError, "tls_client_ca_path requires tls_cert_path and tls_key_path" if tls_client_ca_path && !tls?
116
- unless interceptors.respond_to?(:each) && interceptors.all? { |i| i.respond_to?(:call) }
117
- raise ArgumentError, "interceptors must be an Array of callables"
118
- end
152
+
153
+ validate_callables!
154
+ validate_grpc_web!
119
155
 
120
156
  self
121
157
  end
122
158
 
123
159
  private
124
160
 
161
+ def validate_grpc_web!
162
+ %i[grpc_web_origins grpc_web_allowed_headers grpc_web_exposed_headers].each do |name|
163
+ value = public_send(name)
164
+ next if value.is_a?(Array) && value.all?(String)
165
+
166
+ raise ArgumentError, "#{name} must be an Array of Strings, got #{value.inspect}"
167
+ end
168
+ end
169
+
170
+ def validate_callables!
171
+ raise ArgumentError, "health_check must respond to #call" if health_check && !health_check.respond_to?(:call)
172
+ unless health_check_interval.is_a?(Numeric) && health_check_interval.positive?
173
+ raise ArgumentError, "health_check_interval must be a positive number, got #{health_check_interval.inspect}"
174
+ end
175
+ return if interceptors.respond_to?(:each) && interceptors.all? { |i| i.respond_to?(:call) }
176
+
177
+ raise ArgumentError, "interceptors must be an Array of callables"
178
+ end
179
+
125
180
  def positive_integer!(name)
126
181
  value = public_send(name)
127
182
  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
@@ -38,6 +38,7 @@ module Tonic
38
38
  reader: call[:reader],
39
39
  sender: call[:sender],
40
40
  timeout_ms: call[:timeout_ms],
41
+ peer: Peer.new(call[:peer_address], call[:peer_certificates] || []),
41
42
  )
42
43
  end
43
44