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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +57 -21
  3. data/docs/design.md +245 -52
  4. data/docs/development.md +102 -14
  5. data/docs/grpc-web.md +30 -13
  6. data/docs/grpc.md +98 -5
  7. data/docs/rbs.md +56 -19
  8. data/docs/streaming.md +80 -34
  9. data/docs/unary.md +269 -45
  10. data/lib/connectrpc/bindings/google_protobuf.rb +20 -7
  11. data/lib/connectrpc/client.rb +47 -22
  12. data/lib/connectrpc/deadline.rb +27 -6
  13. data/lib/connectrpc/error.rb +2 -2
  14. data/lib/connectrpc/generator/names.rb +17 -0
  15. data/lib/connectrpc/generator/rbs_renderer.rb +4 -3
  16. data/lib/connectrpc/generator/renderer.rb +35 -3
  17. data/lib/connectrpc/generator/runtime_names.rb +23 -5
  18. data/lib/connectrpc/generator/schema.rb +14 -7
  19. data/lib/connectrpc/grpc.rb +7 -4
  20. data/lib/connectrpc/grpc_client.rb +2 -2
  21. data/lib/connectrpc/grpc_server.rb +14 -14
  22. data/lib/connectrpc/grpc_web_cors.rb +12 -4
  23. data/lib/connectrpc/grpc_web_server.rb +19 -13
  24. data/lib/connectrpc/instrumentation.rb +47 -7
  25. data/lib/connectrpc/keepalive.rb +40 -0
  26. data/lib/connectrpc/method.rb +8 -8
  27. data/lib/connectrpc/metrics/connection_observer.rb +46 -17
  28. data/lib/connectrpc/metrics/definitions.rb +6 -2
  29. data/lib/connectrpc/protocol.rb +64 -11
  30. data/lib/connectrpc/proxy.rb +425 -0
  31. data/lib/connectrpc/server.rb +97 -13
  32. data/lib/connectrpc/streaming/client.rb +22 -25
  33. data/lib/connectrpc/streaming/client_execution.rb +2 -1
  34. data/lib/connectrpc/streaming/client_scope.rb +14 -7
  35. data/lib/connectrpc/streaming/server.rb +1 -0
  36. data/lib/connectrpc/streaming/server_terminal.rb +57 -14
  37. data/lib/connectrpc/streaming/session_messages.rb +12 -5
  38. data/lib/connectrpc/streaming/streams.rb +17 -6
  39. data/lib/connectrpc/streaming/terminal.rb +3 -5
  40. data/lib/connectrpc/transports/net_http.rb +512 -52
  41. data/lib/connectrpc/version.rb +1 -1
  42. data/lib/connectrpc.rb +1 -0
  43. data/sig/connectrpc.rbs +63 -17
  44. metadata +6 -2
@@ -2,29 +2,28 @@
2
2
 
3
3
  module ConnectRPC
4
4
  class Client
5
- def server_stream(method, request, metadata: {}, timeout: 30, cancellation: nil, &block)
6
- validate_stream_call!(method, ServerStreamMethod, cancellation, block)
7
- stream_call(method, request, metadata, timeout, cancellation, &block)
5
+ def server_stream(method, request, metadata: {}, timeout: 30, deadline: nil, cancellation: nil, &block)
6
+ validate_stream_call!(method, ServerStreamMethod, deadline, cancellation, block)
7
+ stream_call(method, request, metadata, [timeout, deadline], cancellation, &block)
8
8
  end
9
9
 
10
- def client_stream(method, metadata: {}, timeout: 30, cancellation: nil, &block)
11
- validate_stream_call!(method, ClientStreamMethod, cancellation, block)
12
- stream_call(method, nil, metadata, timeout, cancellation, &block)
10
+ def client_stream(method, metadata: {}, timeout: 30, deadline: nil, cancellation: nil, &block)
11
+ validate_stream_call!(method, ClientStreamMethod, deadline, cancellation, block)
12
+ stream_call(method, nil, metadata, [timeout, deadline], cancellation, &block)
13
13
  end
14
14
 
15
- def bidi_stream(method, metadata: {}, timeout: 30, cancellation: nil, &block)
16
- validate_stream_call!(method, BidiStreamMethod, cancellation, block)
17
- stream_call(method, nil, metadata, timeout, cancellation, &block)
15
+ def bidi_stream(method, metadata: {}, timeout: 30, deadline: nil, cancellation: nil, &block)
16
+ validate_stream_call!(method, BidiStreamMethod, deadline, cancellation, block)
17
+ stream_call(method, nil, metadata, [timeout, deadline], cancellation, &block)
18
18
  end
19
19
 
20
20
  private
21
21
 
22
- def validate_stream_call!(method, type, cancellation, block)
22
+ def validate_stream_call!(method, type, deadline, cancellation, block)
23
23
  raise ArgumentError, "Wrong streaming declaration" unless method.is_a?(type)
24
24
  raise ArgumentError, "A streaming block is required" unless block
25
- unless cancellation.nil? || cancellation.is_a?(CancellationToken)
26
- raise ArgumentError, "cancellation must be a CancellationToken or nil"
27
- end
25
+
26
+ validate_call_options!(deadline, cancellation)
28
27
  return if stream_capability?(method)
29
28
 
30
29
  raise ArgumentError, "Transport does not support #{method.cardinality}"
@@ -48,23 +47,22 @@ module ConnectRPC
48
47
  transport.respond_to?(:streaming_capabilities) && transport.respond_to?(:open_stream)
49
48
  end
50
49
 
51
- def stream_call(method, request, metadata, timeout, cancellation, &)
50
+ def stream_call(method, request, metadata, limit, cancellation, &)
52
51
  injection = {} #: headers
53
52
  lifecycle = @instrumentation&.start(owner: self, role: :client, method: method, carrier: injection,
54
- protocol: @protocol,
55
- server_address: @base_url.hostname.freeze, server_port: @base_url.port)
53
+ protocol: @protocol, **request_facts(method))
56
54
  lifecycle&.begin_processing(self)
57
55
  work = lambda do
58
- run_stream(method, request, metadata, timeout: timeout, cancellation: cancellation,
56
+ run_stream(method, request, metadata, limit: limit, cancellation: cancellation,
59
57
  lifecycle: lifecycle, injection: injection, &)
60
58
  end
61
59
  lifecycle ? lifecycle.activate(&work) : work.call
62
60
  end
63
61
 
64
- def run_stream(method, request, metadata, timeout:, cancellation:, lifecycle:, injection:, &) # rubocop:disable Metrics/MethodLength
62
+ def run_stream(method, request, metadata, limit:, cancellation:, lifecycle:, injection:, &) # rubocop:disable Metrics/MethodLength
65
63
  scope = Streaming::ClientScope.new(lifecycle)
66
64
  chain = method.is_a?(Method) ? @unary_interceptors : @stream_interceptors
67
- scope.run(timeout, cancellation) do |state, deadline|
65
+ scope.run(limit, cancellation) do |state, deadline|
68
66
  if chain && method.is_a?(Method)
69
67
  intercept_grpc_unary(chain, method, request, metadata, scope, state, deadline, lifecycle, injection, &)
70
68
  elsif chain
@@ -81,7 +79,7 @@ module ConnectRPC
81
79
  def open_client_stream(method, request, outgoing, scope, state, lifecycle, call = nil, &) # rubocop:disable Metrics/ParameterLists, Metrics/MethodLength
82
80
  transport = @transport #: _StreamingTransport
83
81
  work = lambda do |exchange|
84
- session = new_client_stream_session(method, state, exchange, lifecycle)
82
+ session = scope.session = new_client_stream_session(method, state, exchange, lifecycle)
85
83
  with_stream_session(session, scope) { perform_stream_scope(method, request, session, scope, call, &) }
86
84
  end
87
85
  if @protocol == :grpc
@@ -99,10 +97,9 @@ module ConnectRPC
99
97
  metadata
100
98
  end
101
99
 
102
- def stream_request(method, metadata, deadline, cancellation, lifecycle) # rubocop:disable Metrics/MethodLength
100
+ def stream_request(method, metadata, deadline, cancellation, lifecycle)
103
101
  url = @base_url.dup
104
- base_path = @base_url.path #: String
105
- url.path = base_path.delete_suffix("/") + method.path
102
+ url.path = request_path(method)
106
103
  return grpc_stream_request(url, metadata, deadline, cancellation, lifecycle) if @protocol == :grpc
107
104
 
108
105
  headers = metadata.to_h.merge("content-type" => [Streaming::CONTENT_TYPES.fetch(@codec)],
@@ -110,8 +107,8 @@ module ConnectRPC
110
107
  "connect-accept-encoding" => [@accept_encoding.join(", ")])
111
108
  headers["connect-content-encoding"] = ["gzip"] if @encoding == :gzip
112
109
  headers["connect-timeout-ms"] = [deadline.timeout_ms] if deadline
113
- StreamRequest.new(url: url, http_method: "POST", headers: headers, deadline: deadline,
114
- cancellation: cancellation, lifecycle: lifecycle)
110
+ StreamRequest.new(url: url, http_method: "POST", headers: default_user_agent(headers, Protocol::USER_AGENT),
111
+ deadline: deadline, cancellation: cancellation, lifecycle: lifecycle)
115
112
  end
116
113
  end
117
114
  end
@@ -115,7 +115,8 @@ module ConnectRPC
115
115
  raise Error.new(:unimplemented, "Expected exactly one response"), cause: nil if message.nil?
116
116
 
117
117
  if @protocol == :grpc
118
- session.receive until session.consumed?
118
+ # Surplus messages are counted, not decoded; the trailers decide.
119
+ session.receive(skip_data: true) until session.consumed?
119
120
  else
120
121
  session.receive
121
122
  end
@@ -4,6 +4,8 @@ module ConnectRPC
4
4
  module Streaming
5
5
  class ClientScope # rubocop:disable Metrics/ClassLength
6
6
  attr_accessor :completed, :abandoned, :independent_error, :failure, :result, :delivered_error
7
+ # The opened session; its cached response metadata feeds the outcome.
8
+ attr_writer :session
7
9
 
8
10
  def initialize(lifecycle)
9
11
  @lifecycle = lifecycle
@@ -15,12 +17,12 @@ module ConnectRPC
15
17
  @interceptor_error = false
16
18
  end
17
19
 
18
- def run(timeout, cancellation, &)
20
+ def run(limit, cancellation, &)
19
21
  # @type var error: Exception?
20
22
  error = nil
21
23
  # @type var local_exit: bool
22
24
  local_exit = false
23
- execute(timeout, cancellation, &).tap { local_exit = true }
25
+ execute(limit, cancellation, &).tap { local_exit = true }
24
26
  rescue Exception => e # rubocop:disable Lint/RescueException -- Finalization needs the actual escape, including fatal exceptions.
25
27
  error = e
26
28
  local_exit = true
@@ -29,8 +31,8 @@ module ConnectRPC
29
31
  finish_preserving_user(error, local_exit)
30
32
  end
31
33
 
32
- def execute(timeout, cancellation)
33
- active, deadline = start(timeout, cancellation)
34
+ def execute(limit, cancellation)
35
+ active, deadline = start(limit, cancellation)
34
36
  yield active, deadline
35
37
  active.commit! if @completed
36
38
  @result
@@ -148,8 +150,9 @@ module ConnectRPC
148
150
  (@innermost_ok && @completed) || (!delivered.nil? && delivered.equal?(@innermost_failure))
149
151
  end
150
152
 
151
- def start(timeout, cancellation)
152
- deadline = Deadline.new(timeout) unless timeout.nil?
153
+ def start(limit, cancellation)
154
+ timeout, supplied = limit
155
+ deadline = Protocol.call_deadline(timeout, supplied)
153
156
  active = @state = CallCancellation.new(deadline: deadline, cancellation: cancellation)
154
157
  active.check!
155
158
  [active, deadline]
@@ -170,10 +173,14 @@ module ConnectRPC
170
173
  delivered.equal?(error)
171
174
  end
172
175
 
176
+ # Only metadata the session already accepted: finishing never reads.
173
177
  def report_processing(lifecycle, error)
174
178
  normalized = normalized_error(error)
179
+ session = @session
175
180
  lifecycle.processing_finished(code: normalized&.code || ("OK" if success?(error)),
176
- error: error, normalized_error: normalized)
181
+ error: error, normalized_error: normalized,
182
+ response_metadata: session&.cached_headers || Metadata.new,
183
+ response_trailers: session&.trailers || Metadata.new)
177
184
  end
178
185
 
179
186
  # An independent exception escaping the outermost interceptor sets the
@@ -120,6 +120,7 @@ module ConnectRPC
120
120
  state.lifecycle&.record_failure(e)
121
121
  safe = e.is_a?(Error) ? e : Error.new(:internal, "Internal error")
122
122
  state.error = terminal_error(safe, state.context, state.cancellation)
123
+ report_stream_error(e, safe, state)
123
124
  end
124
125
  end
125
126
  end
@@ -6,38 +6,79 @@ module ConnectRPC
6
6
 
7
7
  def render_stream_terminal(state, output)
8
8
  context = state.context ||= streaming_context(state, headers: {})
9
- merge_stream_error_metadata(state.error, context)
10
- bytes, effective = stream_terminal_bytes(state, context)
9
+ fail_unpublished_head(state, "Connect") if context.send(:head_failed?)
10
+ bytes, effective, trailers = stream_terminal_bytes(state, context)
11
11
  handler_error = state.error
12
12
  # A peer reset may reject terminal delivery. Retain the handler failure
13
13
  # independently of that later delivery error.
14
- observe_stream_result(state, effective) if handler_error
15
- context.send(:publish_headers, check: false)
14
+ observe_stream_result(state, effective, trailers) if handler_error
15
+ publish_stream_head(context, handler_error)
16
16
  emit_stream_terminal(bytes, output)
17
17
  context.commit! unless handler_error
18
- observe_stream_result(state, effective) unless handler_error
18
+ observe_stream_result(state, effective, trailers) unless handler_error
19
+ end
20
+
21
+ # A failed head publication is not retried and a stream never finishes
22
+ # without a head. Stop before serializing the terminal, so a terminal that
23
+ # exceeds its limits cannot replace the publication failure.
24
+ def fail_unpublished_head(state, protocol)
25
+ error = state.error
26
+ observe_stream_result(state, error) if error
27
+ raise(error || Error.new(:internal, "#{protocol} headers were not published"))
28
+ end
29
+
30
+ # Error-path observation runs first and can attempt the first publication,
31
+ # so check again after publishing; a failed attempt is never retried.
32
+ def publish_stream_head(context, error)
33
+ context.send(:publish_headers, check: false)
34
+ return unless context.send(:head_failed?)
35
+
36
+ raise(error || Error.new(:internal, "Connect headers were not published"))
37
+ end
38
+
39
+ def grpc_head_failed?(state, context)
40
+ return context.send(:head_failed?) if context.is_a?(StreamingContext)
41
+
42
+ state.head_attempted && !state.published
19
43
  end
20
44
 
21
45
  def stream_terminal_bytes(state, context)
22
46
  trailers = stream_trailers(state.error, context)
23
- Streaming.terminal_bytes(state.error, trailers, wire_limit: @terminal_wire_limit, limit: @terminal_limit)
47
+ bytes, effective = Streaming.terminal_bytes(state.error, trailers, wire_limit: @terminal_wire_limit,
48
+ limit: @terminal_limit)
49
+ [bytes, effective, emitted_trailers(trailers, state.error, effective)]
24
50
  end
25
51
 
26
- def merge_stream_error_metadata(error, context)
27
- return unless error && !context.response_metadata.frozen?
52
+ # Every replacement terminal (byte limit or status codec failure) carries
53
+ # a new error and none of the application trailers.
54
+ def emitted_trailers(trailers, error, effective)
55
+ effective.equal?(error) ? trailers : Metadata.new
56
+ end
28
57
 
29
- error.metadata.each do |key, values|
30
- context.response_metadata[key] = (context.response_metadata[key] || []) + values
31
- end
58
+ # gRPC and gRPC-Web write one field line per value, so a name without
59
+ # values is not on their wire. Connect's JSON terminal keeps it.
60
+ def emitted_fields(trailers, error, effective)
61
+ emitted_trailers(trailers, error, effective).to_h.reject { |_, values| values.empty? }
32
62
  end
33
63
 
64
+ # Error metadata joins a head that is still unpublished. Once the head is
65
+ # committed (frozen), it follows the response trailers in the terminal,
66
+ # ahead of the error's own trailers, as connect-go places it.
34
67
  def stream_trailers(error, context)
35
68
  trailers = Metadata.new(context.response_trailers)
36
- error&.trailers&.each { |key, values| trailers[key] = (trailers[key] || []) + values }
69
+ if error
70
+ head = context.response_metadata
71
+ append_metadata(head.frozen? ? trailers : head, error.metadata)
72
+ append_metadata(trailers, error.trailers)
73
+ end
37
74
  context.response_trailers.freeze
38
75
  trailers
39
76
  end
40
77
 
78
+ def append_metadata(target, source)
79
+ source.each { |key, values| target[key] = (target[key] || []) + values }
80
+ end
81
+
41
82
  def emit_stream_terminal(bytes, output)
42
83
  framing = Streaming::Framing.new(input: nil, output: output, request: false,
43
84
  limit: @response_limit, wire_limit: @response_wire_limit,
@@ -45,11 +86,13 @@ module ConnectRPC
45
86
  framing.emit(bytes, terminal: true)
46
87
  end
47
88
 
48
- def observe_stream_result(state, effective)
89
+ # Trailers are those the rendered terminal carries; none when no terminal is serialized.
90
+ def observe_stream_result(state, effective, trailers = Metadata.new)
49
91
  context = state.context #: StreamingContext
50
92
  state.lifecycle&.processing_finished(code: effective ? effective.code : "OK", error: state.error,
51
93
  normalized_error: effective, http_status: 200,
52
- response_metadata: Instrumentation.carrier(context.response_metadata))
94
+ response_metadata: Instrumentation.carrier(context.response_metadata),
95
+ response_trailers: Instrumentation.carrier(trailers))
53
96
  end
54
97
 
55
98
  def streaming_context(state, headers: state.headers)
@@ -11,8 +11,13 @@ module ConnectRPC
11
11
  @headers || operation(:reading) { leading }
12
12
  end
13
13
 
14
- def receive
15
- operation(:reading) { receive_message }
14
+ # Leading metadata already received and accepted; nil before then. Never reads.
15
+ def cached_headers = @headers
16
+
17
+ # skip_data counts a message without decoding, inflating or observing it.
18
+ # Envelope bounds still apply, and the terminal still decides the outcome.
19
+ def receive(skip_data: false)
20
+ operation(:reading) { receive_message(skip_data) }
16
21
  end
17
22
 
18
23
  # Server single-request methods: true only at a clean end of input.
@@ -55,19 +60,21 @@ module ConnectRPC
55
60
 
56
61
  private
57
62
 
58
- def receive_message
63
+ def receive_message(skip_data)
59
64
  raise StreamStateError, "Normal response consumption was relinquished" if @recovering
60
65
 
61
66
  return completed_receive if @eof
62
67
 
63
68
  leading
64
- frame = @reader.read_frame
69
+ frame = @reader.read_frame(skip_data: skip_data)
65
70
  return receive_eof unless frame
66
71
 
67
72
  flags, bytes, length = frame
68
73
  return accept_terminal(bytes) if flags.anybits?(2)
74
+ return decode_message(bytes, length) unless skip_data
69
75
 
70
- decode_message(bytes, length)
76
+ @received += 1
77
+ nil
71
78
  end
72
79
 
73
80
  def completed_receive
@@ -11,7 +11,7 @@ module ConnectRPC
11
11
  def initialize(publish:, request_metadata: {}, deadline: nil, lifecycle: nil, cancellation: nil)
12
12
  super(request_metadata: request_metadata, deadline: deadline, lifecycle: lifecycle, cancellation: cancellation)
13
13
  @publish = publish
14
- @headers_sent = false
14
+ @headers_sent = @headers_published = false
15
15
  @owner_thread = Thread.current
16
16
  @owner_scheduler = Fiber.scheduler
17
17
  @stream_closed = false
@@ -23,10 +23,7 @@ module ConnectRPC
23
23
 
24
24
  check!
25
25
  Metadata.new(metadata).each { |key, values| @response_metadata[key] = values }
26
- @response_metadata.freeze
27
- @headers_sent = true
28
- @publish.call(@response_metadata)
29
- nil
26
+ publish_snapshot
30
27
  end
31
28
 
32
29
  def close
@@ -43,15 +40,29 @@ module ConnectRPC
43
40
  raise StreamStateError, "Use the stream's owning reactor and thread"
44
41
  end
45
42
 
43
+ # A checked caller is about to write a message, which needs a published head.
46
44
  def publish_headers(check: true)
47
- return if @headers_sent
45
+ if @headers_sent
46
+ return if @headers_published || !check
47
+
48
+ raise Error.new(:internal, "Response headers were not published"), cause: nil
49
+ end
48
50
  return send_headers if check
49
51
 
52
+ publish_snapshot
53
+ end
54
+
55
+ # An attempt is recorded before the publisher runs, so a raising publisher
56
+ # is never invoked twice; head_failed? reports that failure.
57
+ def publish_snapshot
50
58
  @response_metadata.freeze
51
59
  @headers_sent = true
52
60
  @publish.call(@response_metadata)
61
+ @headers_published = true
53
62
  nil
54
63
  end
64
+
65
+ def head_failed? = @headers_sent && !@headers_published
55
66
  end
56
67
 
57
68
  class ResponseReader
@@ -23,12 +23,10 @@ module ConnectRPC
23
23
 
24
24
  def self.terminal_error(error, metadata, trailers)
25
25
  return if error.nil?
26
- raise ArgumentError unless Protocol.valid_wire_error?(error)
27
26
 
28
- empty = [] #: Array[ErrorDetail]
29
- details = Protocol.wire_details(error.fetch("details", empty))
30
- code = Error::HTTP_STATUS.key?(error["code"]) ? error["code"] : "unknown"
31
- Error.new(code, error.fetch("message", ""), details: details, metadata: metadata, trailers: trailers)
27
+ wire = Protocol.wire_error_fields(error, fallback: "unknown")
28
+ Error.new(wire.fetch(:code), wire.fetch(:message), details: wire.fetch(:details), metadata: metadata,
29
+ trailers: trailers)
32
30
  end
33
31
 
34
32
  def self.terminal_bytes(error, trailers, wire_limit:, limit:)