connectrpc 0.2.1 → 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/README.md +57 -21
- data/docs/design.md +245 -52
- data/docs/development.md +102 -14
- data/docs/grpc-web.md +30 -13
- data/docs/grpc.md +98 -5
- data/docs/rbs.md +56 -19
- data/docs/streaming.md +80 -34
- data/docs/unary.md +269 -45
- data/lib/connectrpc/bindings/google_protobuf.rb +20 -7
- data/lib/connectrpc/client.rb +47 -22
- data/lib/connectrpc/deadline.rb +27 -6
- data/lib/connectrpc/error.rb +2 -2
- data/lib/connectrpc/generator/names.rb +17 -0
- data/lib/connectrpc/generator/rbs_renderer.rb +4 -3
- data/lib/connectrpc/generator/renderer.rb +35 -3
- data/lib/connectrpc/generator/runtime_names.rb +23 -5
- data/lib/connectrpc/generator/schema.rb +14 -7
- data/lib/connectrpc/grpc.rb +7 -4
- data/lib/connectrpc/grpc_client.rb +2 -2
- data/lib/connectrpc/grpc_server.rb +14 -14
- data/lib/connectrpc/grpc_web_cors.rb +12 -4
- data/lib/connectrpc/grpc_web_server.rb +19 -13
- data/lib/connectrpc/instrumentation.rb +47 -7
- data/lib/connectrpc/keepalive.rb +40 -0
- data/lib/connectrpc/method.rb +8 -8
- data/lib/connectrpc/metrics/connection_observer.rb +46 -17
- data/lib/connectrpc/metrics/definitions.rb +6 -2
- data/lib/connectrpc/protocol.rb +64 -11
- data/lib/connectrpc/proxy.rb +425 -0
- data/lib/connectrpc/server.rb +97 -13
- data/lib/connectrpc/streaming/client.rb +22 -25
- data/lib/connectrpc/streaming/client_execution.rb +2 -1
- data/lib/connectrpc/streaming/client_scope.rb +14 -7
- data/lib/connectrpc/streaming/server.rb +1 -0
- data/lib/connectrpc/streaming/server_terminal.rb +57 -14
- data/lib/connectrpc/streaming/session_messages.rb +12 -5
- data/lib/connectrpc/streaming/streams.rb +17 -6
- data/lib/connectrpc/streaming/terminal.rb +3 -5
- data/lib/connectrpc/transports/net_http.rb +512 -52
- data/lib/connectrpc/version.rb +1 -1
- data/lib/connectrpc.rb +1 -0
- data/sig/connectrpc.rbs +63 -17
- metadata +6 -2
data/lib/connectrpc/client.rb
CHANGED
|
@@ -6,7 +6,7 @@ module ConnectRPC
|
|
|
6
6
|
class Client # rubocop:disable Metrics/ClassLength
|
|
7
7
|
# Configuration validates each independent public bound eagerly.
|
|
8
8
|
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
|
|
9
|
-
def initialize(base_url:, binding
|
|
9
|
+
def initialize(base_url:, binding: nil, transport: nil, codec: :proto, request_limit: Protocol::DEFAULT_LIMIT,
|
|
10
10
|
response_limit: Protocol::DEFAULT_LIMIT, request_wire_limit: request_limit,
|
|
11
11
|
response_wire_limit: response_limit, accept_encoding: nil, use_get: false, get_url_limit: 8192,
|
|
12
12
|
protocol: :connect, mode: :unary, encoding: :identity, instrumentation: nil,
|
|
@@ -17,6 +17,7 @@ module ConnectRPC
|
|
|
17
17
|
@unary_interceptors, @stream_interceptors = Interceptors.client(interceptors)
|
|
18
18
|
@grpc_status_wire_limit = Protocol.limit!(grpc_status_wire_limit)
|
|
19
19
|
@grpc_status_limit = Protocol.limit!(grpc_status_limit)
|
|
20
|
+
binding = Protocol.binding!(binding)
|
|
20
21
|
@status_codec = GRPCProtocol.status_codec!(binding, status_codec) if protocol == :grpc
|
|
21
22
|
raise ArgumentError, "gRPC requires protobuf POST" if protocol == :grpc && (codec != :proto || use_get)
|
|
22
23
|
raise ArgumentError, "use_get must be true or false" unless [true, false].include?(use_get)
|
|
@@ -40,32 +41,38 @@ module ConnectRPC
|
|
|
40
41
|
|
|
41
42
|
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
|
|
42
43
|
|
|
43
|
-
def call(method, request, metadata: {}, timeout: 30, cancellation: nil)
|
|
44
|
+
def call(method, request, metadata: {}, timeout: 30, deadline: nil, cancellation: nil)
|
|
44
45
|
raise ArgumentError, "call requires a unary Method" unless method.is_a?(Method)
|
|
45
46
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
end
|
|
49
|
-
|
|
47
|
+
validate_call_options!(deadline, cancellation)
|
|
48
|
+
limit = [timeout, deadline] #: [Numeric?, Deadline?]
|
|
50
49
|
if @protocol == :grpc
|
|
51
50
|
raise ArgumentError, "Transport does not support unary gRPC" unless stream_capability?(method)
|
|
52
51
|
|
|
53
|
-
return stream_call(method, request, metadata,
|
|
52
|
+
return stream_call(method, request, metadata, limit, cancellation) { |_| nil }
|
|
54
53
|
end
|
|
55
|
-
return instrumented_call(method, request, metadata,
|
|
54
|
+
return instrumented_call(method, request, metadata, limit, cancellation) if @instrumentation
|
|
56
55
|
|
|
57
|
-
process_call(method, request, metadata,
|
|
56
|
+
process_call(method, request, metadata, limit, cancellation)
|
|
58
57
|
end
|
|
59
58
|
|
|
60
59
|
private
|
|
61
60
|
|
|
61
|
+
def validate_call_options!(deadline, cancellation)
|
|
62
|
+
raise ArgumentError, "deadline must be a Deadline or nil" unless deadline.nil? || deadline.is_a?(Deadline)
|
|
63
|
+
return if cancellation.nil? || cancellation.is_a?(CancellationToken)
|
|
64
|
+
|
|
65
|
+
raise ArgumentError, "cancellation must be a CancellationToken or nil"
|
|
66
|
+
end
|
|
67
|
+
|
|
62
68
|
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
|
|
63
|
-
def process_call(method, request, metadata,
|
|
69
|
+
def process_call(method, request, metadata, limit, cancellation, lifecycle: nil, injection: nil, &observe)
|
|
64
70
|
# @type var state: CallCancellation?
|
|
65
71
|
state = nil
|
|
66
72
|
# @type var independent: Exception?
|
|
67
73
|
independent = nil
|
|
68
|
-
|
|
74
|
+
timeout, supplied = limit
|
|
75
|
+
deadline = Protocol.call_deadline(timeout, supplied)
|
|
69
76
|
active = state = CallCancellation.new(deadline: deadline, cancellation: cancellation)
|
|
70
77
|
active.check!
|
|
71
78
|
metadata = Metadata.new(metadata)
|
|
@@ -143,13 +150,12 @@ module ConnectRPC
|
|
|
143
150
|
metadata
|
|
144
151
|
end
|
|
145
152
|
|
|
146
|
-
def instrumented_call(method, request, metadata,
|
|
153
|
+
def instrumented_call(method, request, metadata, limit, cancellation)
|
|
147
154
|
# @type var injection: Hash[String, String | Array[String]]
|
|
148
155
|
injection = {}
|
|
149
156
|
instrumentation = @instrumentation #: Instrumentation
|
|
150
157
|
lifecycle = instrumentation.start(owner: self, role: :client, method: method.is_a?(Method) ? method : nil,
|
|
151
|
-
carrier: injection,
|
|
152
|
-
server_port: @base_url.port)
|
|
158
|
+
carrier: injection, **request_facts(method))
|
|
153
159
|
lifecycle.begin_processing(self)
|
|
154
160
|
# @type var response: TransportResponse?
|
|
155
161
|
response = nil
|
|
@@ -158,8 +164,8 @@ module ConnectRPC
|
|
|
158
164
|
completed = false
|
|
159
165
|
begin
|
|
160
166
|
result = lifecycle.activate do
|
|
161
|
-
process_call(method, request, metadata,
|
|
162
|
-
|
|
167
|
+
process_call(method, request, metadata, limit, cancellation, lifecycle: lifecycle,
|
|
168
|
+
injection: injection) do |received|
|
|
163
169
|
response = received
|
|
164
170
|
end
|
|
165
171
|
end
|
|
@@ -169,10 +175,11 @@ module ConnectRPC
|
|
|
169
175
|
error = e
|
|
170
176
|
raise
|
|
171
177
|
ensure
|
|
178
|
+
head, trailers = Instrumentation.unary_carriers(response ? response.headers : {})
|
|
172
179
|
lifecycle.processing_finished(code: error.is_a?(Error) ? error.code : ("OK" if completed),
|
|
173
180
|
error: error, normalized_error: error, http_status: response&.status,
|
|
174
181
|
response_bytes: response&.body&.bytesize,
|
|
175
|
-
response_metadata:
|
|
182
|
+
response_metadata: head, response_trailers: trailers)
|
|
176
183
|
lifecycle.finish(delivery: :unobserved)
|
|
177
184
|
end
|
|
178
185
|
end
|
|
@@ -223,8 +230,7 @@ module ConnectRPC
|
|
|
223
230
|
body = compress_request(body, deadline, lifecycle) if @encoding == :gzip
|
|
224
231
|
Protocol.check_size!(body, @request_wire_limit)
|
|
225
232
|
url = @base_url.dup
|
|
226
|
-
|
|
227
|
-
url.path = base_path.delete_suffix("/") + method.path
|
|
233
|
+
url.path = request_path(method)
|
|
228
234
|
get = @use_get && method.idempotency == :no_side_effects
|
|
229
235
|
lifecycle.request_bytes = body.bytesize if lifecycle && get
|
|
230
236
|
GetQuery.build(url, body, codec: @codec, encoding: @encoding, limit: @get_url_limit, deadline: deadline) if get
|
|
@@ -234,6 +240,18 @@ module ConnectRPC
|
|
|
234
240
|
response_limit: @response_wire_limit, deadline: nil)
|
|
235
241
|
end
|
|
236
242
|
|
|
243
|
+
def request_path(method)
|
|
244
|
+
base_path = @base_url.path #: String
|
|
245
|
+
base_path.delete_suffix("/") + method.path
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
# Client endpoint facts for instrumentation; never the query, which can carry a GET message.
|
|
249
|
+
def request_facts(method)
|
|
250
|
+
transport = @transport #: (_Transport | _StreamingTransport | _GRPCTransport) & _TransportClassProbe
|
|
251
|
+
{ server_address: @base_url.hostname.freeze, server_port: @base_url.port, url_scheme: @base_url.scheme.freeze,
|
|
252
|
+
url_path: request_path(method).freeze, transport_class: transport.class }
|
|
253
|
+
end
|
|
254
|
+
|
|
237
255
|
def request_headers(metadata, deadline, get: false)
|
|
238
256
|
headers = metadata.to_h.merge("content-type" => [Protocol::CONTENT_TYPES.fetch(@codec)],
|
|
239
257
|
"accept-encoding" => [@accept_encoding.join(", ")],
|
|
@@ -241,6 +259,13 @@ module ConnectRPC
|
|
|
241
259
|
headers["content-encoding"] = ["gzip"] if @encoding == :gzip
|
|
242
260
|
%w[content-type content-encoding connect-protocol-version].each { |key| headers.delete(key) } if get
|
|
243
261
|
headers["connect-timeout-ms"] = [deadline.timeout_ms] if deadline
|
|
262
|
+
default_user_agent(headers, Protocol::USER_AGENT)
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# Presence, not truthiness: "user-agent" => [] sends none. Interceptors
|
|
266
|
+
# run earlier and do not see this default.
|
|
267
|
+
def default_user_agent(headers, value)
|
|
268
|
+
headers["user-agent"] = [value] unless headers.key?("user-agent")
|
|
244
269
|
headers
|
|
245
270
|
end
|
|
246
271
|
|
|
@@ -283,8 +308,8 @@ module ConnectRPC
|
|
|
283
308
|
raise Error.new(:internal, "Unsupported response content encoding")
|
|
284
309
|
end
|
|
285
310
|
|
|
286
|
-
def validate_response!(status, headers, body)
|
|
287
|
-
raise Protocol.parse_error(status, headers, body) unless status == 200
|
|
311
|
+
def validate_response!(status, headers, body, cause = nil)
|
|
312
|
+
raise Protocol.parse_error(status, headers, body), cause: cause unless status == 200
|
|
288
313
|
|
|
289
314
|
content_type = Protocol.single(headers, "content-type")
|
|
290
315
|
return if Protocol.content_codec(content_type) == @codec
|
|
@@ -304,7 +329,7 @@ module ConnectRPC
|
|
|
304
329
|
def accept_response(response, deadline, lifecycle)
|
|
305
330
|
headers = Protocol.headers(response.headers)
|
|
306
331
|
body = response_body(response, headers, deadline, lifecycle)
|
|
307
|
-
validate_response!(response.status, headers, body)
|
|
332
|
+
validate_response!(response.status, headers, body, response.cause)
|
|
308
333
|
[headers, body]
|
|
309
334
|
rescue ArgumentError => e
|
|
310
335
|
# Header names and values with invalid encodings fail String case and pattern checks.
|
data/lib/connectrpc/deadline.rb
CHANGED
|
@@ -4,10 +4,14 @@ module ConnectRPC
|
|
|
4
4
|
class Deadline
|
|
5
5
|
# Bound native time conversions without shortening the logical deadline.
|
|
6
6
|
MAX_NATIVE_WAIT = 9_999_999.999
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
# Deadlines on this shared default clock compare by absolute expiry.
|
|
8
|
+
MONOTONIC = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
|
|
9
|
+
private_constant :MONOTONIC
|
|
10
|
+
|
|
11
|
+
def initialize(timeout, clock: MONOTONIC)
|
|
12
|
+
# Zero and negative budgets are already expired, as in grpc-go.
|
|
13
|
+
unless timeout.is_a?(Numeric) && timeout.real? && timeout.finite?
|
|
14
|
+
raise ArgumentError, "Timeout must be finite real seconds"
|
|
11
15
|
end
|
|
12
16
|
|
|
13
17
|
@clock = clock
|
|
@@ -16,8 +20,8 @@ module ConnectRPC
|
|
|
16
20
|
|
|
17
21
|
def self.expired
|
|
18
22
|
deadline = allocate
|
|
19
|
-
deadline.instance_variable_set(:@clock,
|
|
20
|
-
deadline.instance_variable_set(:@expires_at,
|
|
23
|
+
deadline.instance_variable_set(:@clock, MONOTONIC)
|
|
24
|
+
deadline.instance_variable_set(:@expires_at, MONOTONIC.call)
|
|
21
25
|
deadline
|
|
22
26
|
end
|
|
23
27
|
private_class_method :expired
|
|
@@ -42,6 +46,23 @@ module ConnectRPC
|
|
|
42
46
|
check!
|
|
43
47
|
[remaining * 1000, 9_999_999_999].min.ceil.clamp(1, 9_999_999_999).to_s
|
|
44
48
|
end
|
|
49
|
+
|
|
50
|
+
protected
|
|
51
|
+
|
|
52
|
+
attr_reader :clock, :expires_at
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
# Whether this deadline expires strictly before other. A shared clock
|
|
57
|
+
# compares absolute expiries, so no gap between clock reads can reorder
|
|
58
|
+
# them. Distinct clocks can only compare remaining time, which can be off
|
|
59
|
+
# by the gap between the two reads.
|
|
60
|
+
def earlier_than?(other)
|
|
61
|
+
shared = clock #: (^() -> Numeric | _Clock) & _IdentityProbe
|
|
62
|
+
return expires_at < other.expires_at if shared.equal?(other.clock)
|
|
63
|
+
|
|
64
|
+
remaining < other.remaining
|
|
65
|
+
end
|
|
45
66
|
end
|
|
46
67
|
|
|
47
68
|
class Context
|
data/lib/connectrpc/error.rb
CHANGED
|
@@ -40,6 +40,23 @@ module ConnectRPC
|
|
|
40
40
|
UDPSocket UNIXServer UNIXSocket URI UnboundMethod UncaughtThrowError UnicodeNormalize Warning ZeroDivisionError
|
|
41
41
|
Zlib
|
|
42
42
|
].freeze
|
|
43
|
+
# Interpreter-defined plain modules that no other module includes or
|
|
44
|
+
# extends and that core does not load from the standard library. Official
|
|
45
|
+
# package modules reopen them safely, so packages may nest under them;
|
|
46
|
+
# replacing the root itself stays reserved through TOP_LEVEL_RESERVED.
|
|
47
|
+
REOPENABLE_ROOTS = %w[FileTest GC Marshal Math ObjectSpace Process Signal].freeze
|
|
48
|
+
# Existing constants of those roots on Ruby 3.4.12 and 4.0.9. A package may
|
|
49
|
+
# reopen a module child; nothing may be declared at or below a value or
|
|
50
|
+
# class child, which official output would replace or fail to reopen.
|
|
51
|
+
BUILTIN_MODULE_CHILDREN = { "GC" => %w[Profiler].freeze, "Process" => %w[GID Sys UID].freeze }.freeze
|
|
52
|
+
BUILTIN_VALUE_CHILDREN = {
|
|
53
|
+
"GC" => %w[INTERNAL_CONSTANTS OPTS].freeze,
|
|
54
|
+
"Marshal" => %w[MAJOR_VERSION MINOR_VERSION].freeze,
|
|
55
|
+
"Math" => %w[DomainError E PI].freeze,
|
|
56
|
+
"ObjectSpace" => %w[WeakKeyMap WeakMap].freeze,
|
|
57
|
+
# Clock, priority and resource-limit constants vary by platform.
|
|
58
|
+
"Process" => ["Status", "Tms", "WNOHANG", "WUNTRACED", "Waiter", /\A(?:CLOCK|PRIO|RLIMIT|RLIM)_/].freeze
|
|
59
|
+
}.freeze
|
|
43
60
|
|
|
44
61
|
def self.identifier!(name, description)
|
|
45
62
|
return if IDENTIFIER.match?(name)
|
|
@@ -49,7 +49,7 @@ module ConnectRPC
|
|
|
49
49
|
def render_client_signature(method, depth)
|
|
50
50
|
request, reply = types(method)
|
|
51
51
|
options = "?metadata: ::ConnectRPC::metadata_input, ?timeout: ::Numeric?, " \
|
|
52
|
-
"?cancellation: ::ConnectRPC::CancellationToken?"
|
|
52
|
+
"?deadline: ::ConnectRPC::Deadline?, ?cancellation: ::ConnectRPC::CancellationToken?"
|
|
53
53
|
name = Names.rpc(method.name)
|
|
54
54
|
case declaration_type(method)
|
|
55
55
|
when "ServerStreamMethod"
|
|
@@ -84,8 +84,9 @@ module ConnectRPC
|
|
|
84
84
|
values = methods.map do |method|
|
|
85
85
|
"::ConnectRPC::#{handler_type(method)}[#{types(method).join(', ')}]"
|
|
86
86
|
end.uniq
|
|
87
|
-
|
|
88
|
-
|
|
87
|
+
value = values.empty? ? "bot" : values.join(" | ")
|
|
88
|
+
line(depth + 1, "def self.handlers: (#{keywords}) -> ::Hash[::String, #{value}]")
|
|
89
|
+
line(depth + 1, "def self.handlers_for: (::Object impl, ?strict: bool) -> ::Hash[::String, #{value}]")
|
|
89
90
|
line(depth, "end")
|
|
90
91
|
end
|
|
91
92
|
end
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
module ConnectRPC
|
|
4
4
|
module Generator
|
|
5
|
-
class Renderer
|
|
5
|
+
class Renderer # rubocop:disable Metrics/ClassLength
|
|
6
6
|
include StreamingMethods
|
|
7
7
|
|
|
8
8
|
def initialize(schema, file)
|
|
@@ -12,7 +12,8 @@ module ConnectRPC
|
|
|
12
12
|
|
|
13
13
|
def render
|
|
14
14
|
@lines = ["# frozen_string_literal: true", "", "# Generated by protoc-gen-connectrpc-ruby. DO NOT EDIT!",
|
|
15
|
-
"# source: #{@file.name}", "", 'require "connectrpc"'
|
|
15
|
+
"# source: #{@file.name}", "", 'require "connectrpc"',
|
|
16
|
+
'require "connectrpc/bindings/google_protobuf"']
|
|
16
17
|
required_files.each { |name| @lines << "require #{"#{Names.stem(name)}_pb".dump}" }
|
|
17
18
|
@lines << ""
|
|
18
19
|
namespace = Names.namespace(@file)
|
|
@@ -51,10 +52,11 @@ module ConnectRPC
|
|
|
51
52
|
name = [@file.package, service.name].reject(&:empty?).join(".")
|
|
52
53
|
line(depth, "")
|
|
53
54
|
line(depth, "SERVICE = ::ConnectRPC::Service.new(")
|
|
54
|
-
line(depth + 1, "name: #{name.dump},
|
|
55
|
+
line(depth + 1, "name: #{name.dump}, rpcs: [#{methods.map { |_m, ruby| ruby.upcase }.join(', ')}]")
|
|
55
56
|
line(depth, ")")
|
|
56
57
|
render_client(methods, depth)
|
|
57
58
|
render_handlers(methods, depth)
|
|
59
|
+
render_handlers_for(methods, depth)
|
|
58
60
|
line(depth - 1, "end")
|
|
59
61
|
end
|
|
60
62
|
|
|
@@ -110,6 +112,36 @@ module ConnectRPC
|
|
|
110
112
|
line(depth + 1, methods.empty? ? "{}" : "{ #{entries} }")
|
|
111
113
|
line(depth, "end")
|
|
112
114
|
end
|
|
115
|
+
|
|
116
|
+
# Maps each RPC to the implementation's public method of the same snake
|
|
117
|
+
# case name. respond_to? decides presence, so private methods are missing,
|
|
118
|
+
# and a method owned by a core ancestor is never bound. Class.ancestors
|
|
119
|
+
# covers Object's ancestors, including later framework additions, plus
|
|
120
|
+
# Module and Class, which only module implementations inherit from. A
|
|
121
|
+
# handler mixin that is also mixed into one of those counts as core.
|
|
122
|
+
def render_handlers_for(methods, depth)
|
|
123
|
+
line(depth, "")
|
|
124
|
+
line(depth, "def self.handlers_for(#{'_' if methods.empty?}impl, strict: false)")
|
|
125
|
+
line(depth + 1, 'raise ::ArgumentError, "strict must be true or false" unless [true, false].include?(strict)')
|
|
126
|
+
line(depth, "")
|
|
127
|
+
if methods.empty?
|
|
128
|
+
line(depth + 1, "{}")
|
|
129
|
+
else
|
|
130
|
+
entries = methods.map { |_method, ruby| "#{ruby}: #{ruby.upcase}" }.join(", ")
|
|
131
|
+
line(depth + 1, "rpcs = { #{entries} }")
|
|
132
|
+
line(depth + 1, "core = ::Class.ancestors")
|
|
133
|
+
line(depth + 1, "found = rpcs.keys.filter_map do |name|")
|
|
134
|
+
line(depth + 2, "method = impl.public_method(name) if impl.respond_to?(name)")
|
|
135
|
+
line(depth + 2, "[name, method] if method && !core.include?(method.owner)")
|
|
136
|
+
line(depth + 1, "end.to_h")
|
|
137
|
+
line(depth + 1, "missing = rpcs.keys - found.keys")
|
|
138
|
+
line(depth + 1, "raise ::ArgumentError, \"Missing service methods: \#{missing.join(', ')}\" " \
|
|
139
|
+
"if strict && !missing.empty?")
|
|
140
|
+
line(depth, "")
|
|
141
|
+
line(depth + 1, "found.to_h { |name, method| [rpcs.fetch(name).path, method] }")
|
|
142
|
+
end
|
|
143
|
+
line(depth, "end")
|
|
144
|
+
end
|
|
113
145
|
end
|
|
114
146
|
end
|
|
115
147
|
end
|
|
@@ -38,10 +38,18 @@ module ConnectRPC
|
|
|
38
38
|
]
|
|
39
39
|
}.freeze
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
RUBY_PACKAGE_HINT = "set the ruby_package file option to choose another Ruby namespace"
|
|
42
|
+
|
|
43
|
+
def self.validate!(parts, kind, origin, file) # rubocop:disable Metrics/MethodLength
|
|
42
44
|
name = parts.join("::")
|
|
43
45
|
if reserved_root?(parts, kind)
|
|
44
|
-
|
|
46
|
+
# Below a reopenable root, only a builtin child is ever reserved.
|
|
47
|
+
constant = if parts.size > 1 && Names::REOPENABLE_ROOTS.include?(parts.first)
|
|
48
|
+
"builtin Ruby constant #{parts.take(2).join('::')}"
|
|
49
|
+
else
|
|
50
|
+
"top-level Ruby constant #{parts.first}"
|
|
51
|
+
end
|
|
52
|
+
raise InvalidDescriptor, "Reserved #{constant} for #{file}: #{origin}; #{RUBY_PACKAGE_HINT}"
|
|
45
53
|
end
|
|
46
54
|
|
|
47
55
|
protected_name = protected_runtime(parts, kind) || protected_protobuf_type(parts, kind, origin, file)
|
|
@@ -58,9 +66,19 @@ module ConnectRPC
|
|
|
58
66
|
parts.take(3).join("::")
|
|
59
67
|
end
|
|
60
68
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
69
|
+
# Google and the reopenable builtin roots accept package modules. Google
|
|
70
|
+
# nesting is otherwise left to the protobuf runtime checks; a builtin root
|
|
71
|
+
# also rejects replacing a module child and anything at or below a value
|
|
72
|
+
# or class child.
|
|
73
|
+
def self.reserved_root?(parts, kind) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
|
|
74
|
+
root, child = parts
|
|
75
|
+
return false unless Names::TOP_LEVEL_RESERVED.include?(root)
|
|
76
|
+
return true unless root == "Google" || Names::REOPENABLE_ROOTS.include?(root)
|
|
77
|
+
return kind != :package if child.nil?
|
|
78
|
+
return false if root == "Google"
|
|
79
|
+
return parts.size == 2 && kind != :package if Names::BUILTIN_MODULE_CHILDREN.fetch(root, []).include?(child)
|
|
80
|
+
|
|
81
|
+
Names::BUILTIN_VALUE_CHILDREN.fetch(root, []).any? { |entry| entry === child } # rubocop:disable Style/CaseEquality -- String or platform Regexp
|
|
64
82
|
end
|
|
65
83
|
|
|
66
84
|
def self.protected_protobuf_type(parts, kind, origin, file)
|
|
@@ -6,8 +6,9 @@ module ConnectRPC
|
|
|
6
6
|
attr_reader :targets, :types, :ruby_types, :rbs
|
|
7
7
|
|
|
8
8
|
def initialize(request)
|
|
9
|
-
unless ["", "rbs=true"].include?(request.parameter)
|
|
10
|
-
raise InvalidDescriptor,
|
|
9
|
+
unless ["", "rbs=false", "rbs=true"].include?(request.parameter)
|
|
10
|
+
raise InvalidDescriptor,
|
|
11
|
+
"Invalid plugin parameters #{request.parameter.inspect}; expected rbs=true, rbs=false or empty"
|
|
11
12
|
end
|
|
12
13
|
|
|
13
14
|
@rbs = request.parameter == "rbs=true"
|
|
@@ -141,17 +142,23 @@ module ConnectRPC
|
|
|
141
142
|
|
|
142
143
|
def validate_namespaces
|
|
143
144
|
loaded = loaded_files
|
|
144
|
-
loaded_names = loaded.
|
|
145
|
-
relevant = loaded.
|
|
145
|
+
loaded_names = loaded.to_set(&:name)
|
|
146
|
+
relevant = loaded.each_with_object(Set.new) do |file, result|
|
|
146
147
|
namespace = Names.namespace(file)
|
|
147
148
|
if namespace.empty?
|
|
148
|
-
[*file.message_type, *file.enum_type, *file.service].
|
|
149
|
+
[*file.message_type, *file.enum_type, *file.service].each { |type| result << [Names.rubify(type.name)] }
|
|
149
150
|
else
|
|
150
|
-
|
|
151
|
+
result << namespace
|
|
151
152
|
end
|
|
152
153
|
end
|
|
154
|
+
# A namespace is relevant when it starts with a relevant entry or is an
|
|
155
|
+
# ancestor of one. Sets keep this linear in large package-less files.
|
|
156
|
+
ancestors = relevant.each_with_object(Set.new) do |prefix, result|
|
|
157
|
+
prefix.each_index { |index| result << prefix.take(index + 1) }
|
|
158
|
+
end
|
|
153
159
|
@namespaces.each do |parts, declarations|
|
|
154
|
-
|
|
160
|
+
nested = parts.each_index.any? { |index| relevant.include?(parts.take(index + 1)) }
|
|
161
|
+
next unless nested || ancestors.include?(parts)
|
|
155
162
|
|
|
156
163
|
declarations.each do |kind, origin, file|
|
|
157
164
|
RuntimeNames.validate!(parts, kind, origin, file) if loaded_names.include?(file)
|
data/lib/connectrpc/grpc.rb
CHANGED
|
@@ -15,6 +15,8 @@ module ConnectRPC
|
|
|
15
15
|
|
|
16
16
|
module GRPCProtocol # rubocop:disable Metrics/ModuleLength
|
|
17
17
|
CONTENT_TYPE = "application/grpc+proto"
|
|
18
|
+
# Since 0.3.0, sent by gRPC clients unless metadata names a user-agent.
|
|
19
|
+
USER_AGENT = "grpc-ruby-connectrpc/#{VERSION} (ruby #{RUBY_VERSION})".freeze
|
|
18
20
|
FIELD_LIMIT = 65_536
|
|
19
21
|
UINT32_MAX = 4_294_967_295
|
|
20
22
|
CODES = ["OK", *Error::HTTP_STATUS.keys].freeze
|
|
@@ -132,10 +134,6 @@ module ConnectRPC
|
|
|
132
134
|
fields = status_fields(error, trailers, codec, limit)
|
|
133
135
|
check_fields!(fields, [wire_limit, FIELD_LIMIT].min)
|
|
134
136
|
[snapshot(fields), error]
|
|
135
|
-
rescue CodecError => e
|
|
136
|
-
on_error&.call(e)
|
|
137
|
-
terminal(Error.new(:internal, "Cannot encode gRPC status"), Metadata.new, codec: codec,
|
|
138
|
-
wire_limit: wire_limit, limit: limit)
|
|
139
137
|
rescue Error => e
|
|
140
138
|
raise unless e.code == "resource_exhausted"
|
|
141
139
|
|
|
@@ -143,6 +141,11 @@ module ConnectRPC
|
|
|
143
141
|
fields = { "grpc-status" => ["8"] }
|
|
144
142
|
check_fields!(fields, [wire_limit, FIELD_LIMIT].min)
|
|
145
143
|
[snapshot(fields), replacement]
|
|
144
|
+
rescue StandardError => e
|
|
145
|
+
# Any custom status codec failure, not only CodecError, as GRPCWeb.terminal.
|
|
146
|
+
on_error&.call(e)
|
|
147
|
+
terminal(Error.new(:internal, "Cannot encode gRPC status"), Metadata.new, codec: codec,
|
|
148
|
+
wire_limit: wire_limit, limit: limit)
|
|
146
149
|
end
|
|
147
150
|
|
|
148
151
|
def self.request_deadline(headers) # rubocop:disable Metrics/AbcSize
|
|
@@ -32,8 +32,8 @@ module ConnectRPC
|
|
|
32
32
|
"grpc-accept-encoding" => [@accept_encoding.join(",")])
|
|
33
33
|
headers["grpc-encoding"] = ["gzip"] if @encoding == :gzip
|
|
34
34
|
headers["grpc-timeout"] = [GRPCProtocol.timeout(deadline)] if deadline
|
|
35
|
-
StreamRequest.new(url: url, http_method: "POST", headers: headers,
|
|
36
|
-
cancellation: cancellation, lifecycle: lifecycle)
|
|
35
|
+
StreamRequest.new(url: url, http_method: "POST", headers: default_user_agent(headers, GRPCProtocol::USER_AGENT),
|
|
36
|
+
deadline: deadline, cancellation: cancellation, lifecycle: lifecycle)
|
|
37
37
|
end
|
|
38
38
|
end
|
|
39
39
|
end
|
|
@@ -4,7 +4,7 @@ module ConnectRPC
|
|
|
4
4
|
module GRPCProtocol
|
|
5
5
|
class ServerState
|
|
6
6
|
attr_reader :headers, :codec, :publish, :lifecycle, :cancellation
|
|
7
|
-
attr_accessor :context, :session, :encoding, :error, :published
|
|
7
|
+
attr_accessor :context, :session, :encoding, :error, :published, :head_attempted
|
|
8
8
|
|
|
9
9
|
def initialize(headers:, codec:, publish:, lifecycle:, cancellation:)
|
|
10
10
|
@headers = headers
|
|
@@ -13,7 +13,7 @@ module ConnectRPC
|
|
|
13
13
|
@lifecycle = lifecycle
|
|
14
14
|
@cancellation = cancellation
|
|
15
15
|
@encoding = :identity
|
|
16
|
-
@published = false
|
|
16
|
+
@published = @head_attempted = false
|
|
17
17
|
end
|
|
18
18
|
end
|
|
19
19
|
end
|
|
@@ -114,7 +114,8 @@ module ConnectRPC
|
|
|
114
114
|
context = state.context #: Context
|
|
115
115
|
if context.is_a?(StreamingContext)
|
|
116
116
|
context.send(:publish_headers, check: false)
|
|
117
|
-
|
|
117
|
+
elsif !state.head_attempted
|
|
118
|
+
state.head_attempted = true
|
|
118
119
|
context.response_metadata.freeze
|
|
119
120
|
publish_grpc_snapshot(state, context.response_metadata)
|
|
120
121
|
end
|
|
@@ -131,26 +132,25 @@ module ConnectRPC
|
|
|
131
132
|
end
|
|
132
133
|
|
|
133
134
|
def grpc_terminal_fields(state, context)
|
|
134
|
-
merge_stream_error_metadata(state.error, context)
|
|
135
135
|
codec = @status_codec #: _GRPCStatusCodec
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
wire_limit: @grpc_status_wire_limit, limit: @grpc_status_limit,
|
|
140
|
-
on_error:
|
|
141
|
-
state.lifecycle&.record_failure(error)
|
|
142
|
-
}
|
|
136
|
+
trailers = stream_trailers(state.error, context)
|
|
137
|
+
fields, effective = GRPCProtocol.terminal(
|
|
138
|
+
state.error, trailers,
|
|
139
|
+
codec: codec, wire_limit: @grpc_status_wire_limit, limit: @grpc_status_limit,
|
|
140
|
+
on_error: ->(error) { state.lifecycle&.record_failure(error) }
|
|
143
141
|
)
|
|
142
|
+
[fields, effective, emitted_fields(trailers, state.error, effective)]
|
|
144
143
|
end
|
|
145
144
|
|
|
146
145
|
def render_grpc_terminal(state, output)
|
|
147
146
|
context = state.context ||= grpc_context(state, headers: {})
|
|
148
|
-
|
|
149
|
-
|
|
147
|
+
fail_unpublished_head(state, "gRPC") if grpc_head_failed?(state, context)
|
|
148
|
+
fields, effective, trailers = grpc_terminal_fields(state, context)
|
|
149
|
+
observe_stream_result(state, effective, trailers) if state.error
|
|
150
150
|
publish_grpc_head(state)
|
|
151
151
|
output.finish(headers: fields)
|
|
152
152
|
context.commit! unless state.error
|
|
153
|
-
observe_stream_result(state, effective) unless state.error
|
|
153
|
+
observe_stream_result(state, effective, trailers) unless state.error
|
|
154
154
|
end
|
|
155
155
|
end
|
|
156
156
|
end
|
|
@@ -9,11 +9,12 @@ module ConnectRPC
|
|
|
9
9
|
BASE_REQUEST = %w[content-type x-grpc-web x-user-agent grpc-timeout accept].freeze
|
|
10
10
|
BASE_EXPOSE = %w[grpc-status grpc-message grpc-status-details-bin].freeze
|
|
11
11
|
TOKEN = /\A[!#$%&'*+.^_`|~0-9A-Za-z-]+\z/
|
|
12
|
-
|
|
12
|
+
MAX_AGE_LIMIT = 86_400
|
|
13
|
+
private_constant :BASE_REQUEST, :BASE_EXPOSE, :TOKEN, :MAX_AGE_LIMIT
|
|
13
14
|
|
|
14
|
-
attr_reader :origins, :credentials, :request_headers, :expose_headers
|
|
15
|
+
attr_reader :origins, :credentials, :request_headers, :expose_headers, :max_age
|
|
15
16
|
|
|
16
|
-
def initialize(origins:, credentials: false, request_headers: [], expose_headers: []) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
|
|
17
|
+
def initialize(origins:, credentials: false, request_headers: [], expose_headers: [], max_age: 0) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
|
|
17
18
|
unless [true, false].include?(credentials) && origins.is_a?(Array) && origins.size <= 32 &&
|
|
18
19
|
origins.all? { |origin| valid_origin?(origin) } && origins.uniq.size == origins.size
|
|
19
20
|
raise ArgumentError, "CORS requires distinct exact HTTP(S) origins and boolean credentials"
|
|
@@ -23,11 +24,18 @@ module ConnectRPC
|
|
|
23
24
|
@credentials = credentials
|
|
24
25
|
@request_headers = (BASE_REQUEST + names(request_headers)).uniq.freeze
|
|
25
26
|
@expose_headers = (BASE_EXPOSE + names(expose_headers)).uniq.freeze
|
|
27
|
+
@max_age = max_age!(max_age)
|
|
26
28
|
freeze
|
|
27
29
|
end
|
|
28
30
|
|
|
29
31
|
private
|
|
30
32
|
|
|
33
|
+
def max_age!(value)
|
|
34
|
+
return value if value.is_a?(Integer) && value.between?(0, MAX_AGE_LIMIT)
|
|
35
|
+
|
|
36
|
+
raise ArgumentError, "CORS max_age must be an Integer from 0 to #{MAX_AGE_LIMIT} seconds"
|
|
37
|
+
end
|
|
38
|
+
|
|
31
39
|
def valid_origin?(origin) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
|
|
32
40
|
return false unless origin.is_a?(String) && origin.ascii_only? && origin.bytesize <= 2048
|
|
33
41
|
return false unless %r{\Ahttps?://[^/?#\s]+\z}.match?(origin)
|
|
@@ -127,7 +135,7 @@ module ConnectRPC
|
|
|
127
135
|
fields.merge!(cors_fields(policy, origin))
|
|
128
136
|
fields["access-control-allow-methods"] = ["POST"]
|
|
129
137
|
fields["access-control-allow-headers"] = [policy.request_headers.join(", ")]
|
|
130
|
-
fields["access-control-max-age"] = [
|
|
138
|
+
fields["access-control-max-age"] = [policy.max_age.to_s]
|
|
131
139
|
end
|
|
132
140
|
TransportResponse.new(status: permitted ? 204 : 403, headers: fields, body: "")
|
|
133
141
|
end
|