Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,22 @@ Ruby clients reject that unadvertised response. There is no full-conformance cla

Wire protocol, HTTP transport, and message binding remain separate choices.
[Native gRPC](grpc.md) and [gRPC-Web](grpc-web.md) have distinct implemented
profiles. Interceptors and Faraday remain future work; production readiness
remains subject to the support contract's adoption gates. Unsupported
modes/options are rejected rather than represented as buffered streaming.
profiles. Typed unary [interceptors](unary.md#interceptors) wrap Client
dispatch and the Server invoker on every unary protocol; streaming interceptors
and Faraday remain future work. Production readiness remains subject to the
support contract's adoption gates. Unsupported modes/options are rejected
rather than represented as buffered streaming.

Interceptors are application code inside core's call ownership. A client chain
runs inside the lifecycle activation and the call's deadline and cancellation
arbiter, before metadata injection and encoding; the arbiter commits once
after the outermost interceptor. A server chain wraps the invoker after bounded
decode, so host policy that an invoker carries, such as the Rails controller
lifecycle, still runs for every successful call. Each layer gets a guarded,
single-use continuation; no layer can return success after its continuation
failed, and core records each escaping failure for observers. The
[interceptor design](plans/interceptors.md) records the full rules and the
remaining streaming and Rails work.

The optional [connectrpc-on-rails gem](../gems/connectrpc-on-rails/README.md) uses the
invoker boundary to run native controller callbacks, authentication,
Expand Down
10 changes: 10 additions & 0 deletions docs/grpc-web.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,16 @@ invoker, callbacks, authentication, sessions, cookies, CSRF and security headers
remain active. Preflight does not bypass actual POST checks. A valid CSRF token
does not override Rails' origin policy. No CSRF exemption is installed.

## Interceptors

Web unary calls run the Server's [unary interceptors](unary.md#interceptors)
with `call.protocol == :grpc_web`, after the single request frame is read and
decoded and around the invoker. Response metadata written before or after
`yield` is published with the head after the chain returns; trailers and error
metadata reach the terminal frame. Server-streaming Web calls do not run
interceptors yet, and a Server rejects an interceptor that defines
`server_stream`.

## Bounds and host SPI

Message and independent message-wire limits default to 4 MiB. Framing adds five
Expand Down
23 changes: 23 additions & 0 deletions docs/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,26 @@ Native unary executes the configured invoker with a normal Context, including
custom invokers that have no handler-map entry. As on every server Context,
`context.request_metadata` is mutable per-call metadata; writes do not change
what instrumentation recorded for the request.

## Interceptors

[Unary interceptors](unary.md#interceptors) cover native gRPC unary calls on
both roles, with `call.protocol == :grpc`. Streaming interceptors are not
implemented yet; a Client or Server rejects an interceptor that defines
`client_stream` or `server_stream`.

On the client, the chain runs inside the call's deadline and cancellation scope
and before the stream opens. Request metadata is final when the innermost
continuation opens the stream, and a cancellation accepted before then fails
the call with `canceled` without opening a stream. The returned `Response`, its
metadata and its trailers are frozen, with or without interceptors. Delivery
comes from the exchange, not from the code that raised: a short-circuit or a
rejection before `yield` reports `:unobserved`; an interceptor exception after a
completed exchange, or after a remote error the peer delivered, reports
`:completed`; an interceptor that translates a transport or cleanup failure
leaves it `:aborted`.

On the server, interceptors run after the single request message is read and
decoded, around the configured invoker. The head is published after the chain
returns, so response metadata written before or after `yield` reaches the
client, and trailers stay writable until the terminal status.
16 changes: 16 additions & 0 deletions docs/rbs.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,22 @@ unions. `_Cancellation` is the read-only transport/host extension SPI, with
and own separate processing arbitration. Deadline remains an actual Deadline or
nil. Runtime cancellation, reactor and blocking-I/O limits still apply.

## Interceptor types

`Client.new(interceptors:)` takes `Array[client_interceptor]` and
`Server.new(interceptors:)` takes `Array[server_interceptor]`. In this release
these aliases are `_ClientUnaryInterceptor` and `_ServerUnaryInterceptor`.
Their methods take a `ClientUnaryCall` or `ServerUnaryCall` and a no-argument
continuation block. A client interceptor returns `Response[untyped]`; message
types are `untyped` because one interceptor serves many methods, like
`_Invoker`. A registration check accepts any object that satisfies the
interface, so declare `include ConnectRPC::_ClientUnaryInterceptor` (or the
server interface) in an interceptor class's own signature to have Steep check
its return type and continuation calls. Runtime checks cover unsigned
interceptors. Exact negatives reject wrong-role registration, a non-`Response`
client return, a continuation called with an argument and `wrap_stream` on a
unary call.

## Streaming types

The invariant streaming declarations are siblings of unary Method. Generated
Expand Down
17 changes: 10 additions & 7 deletions docs/support.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,9 @@ ownership and constraints.

Supported APIs include method and service declarations, core and generated
client operations, Server configuration, metadata, errors, contexts and their
`on_cancel` listeners, cancellation sources/tokens, scoped readers/writers/duplex
`on_cancel` listeners, cancellation sources/tokens, unary interceptor
registration (`interceptors:`) with the `ClientUnaryCall` and `ServerUnaryCall`
call objects and `InterceptorStateError`, scoped readers/writers/duplex
endpoints, the health registry and its generated `grpc.health.v1` client, and the
optional packages' documented constructors, lifecycle and configuration
operations. Generated service factories, typed handlers and installed generated
Expand All @@ -271,8 +273,9 @@ message bridges remain explicit opt-ins with their documented finite coverage.
The extension SPIs cover these boundaries. Binding, cancellation and lifecycle
interfaces are shared with streaming and gRPC execution.

- Shared interfaces and unary execution: `_Binding`, `_Transport`, `_Input`, invokers and
`_Cancellation`.
- Shared interfaces and unary execution: `_Binding`, `_Transport`, `_Input`, invokers,
`_Cancellation`, and the `_ClientUnaryInterceptor` and `_ServerUnaryInterceptor`
interceptor interfaces.
- Streaming and gRPC: `_StreamingTransport`, `_StreamExchange`, streaming I/O,
`_GRPCTransport`, `_GRPCStreamExchange` and `_GRPCStatusCodec`.
- Server hosting and observation: native publication/output interfaces,
Expand All @@ -287,10 +290,10 @@ readers as `spi`.
Use each interface within its documented bounded reads, completion, reactor
affinity and original-processor ownership rules. An SPI does not grant access
to private objects its implementation happens to expose. Protocol, compression
and parser helpers, cancellation arbitration, private lifecycle bookkeeping,
native socket/lease/session helpers and generator implementation are internal
unless explicitly classified otherwise. Their observable supported behavior
still falls under patch compatibility.
and parser helpers, cancellation arbitration, interceptor continuations and
chains, private lifecycle bookkeeping, native socket/lease/session helpers and
generator implementation are internal unless explicitly classified otherwise.
Their observable supported behavior still falls under patch compatibility.

The [strict source list](../typecheck/source.rb) is finite. Consumer coverage
does not mean all optional implementation is checked.
Expand Down
156 changes: 154 additions & 2 deletions docs/unary.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,10 @@ watchdog. Native TCP/TLS/read/write waits remain independently capped at
`9_999_999.999` seconds; a native timeout returns `unavailable`. Sustained
progress can outlast that per-operation cap.

For finite values, one monotonic budget starts before encoding and covers
network I/O and checks around codec work.
For finite values, one monotonic budget starts before the
[interceptor chain](#interceptors) and covers interceptor time, encoding, network
I/O and checks around codec work. The wire timeout is computed at dispatch from
the remaining budget.

The default NetHTTP transport:

Expand Down Expand Up @@ -424,6 +426,156 @@ cancellation. Rack/Rails and Falcon HTTP/1 add no peer detection or token env
injection. Synchronous adapters cannot interrupt blocked application code.
See [design](design.md) for ownership and transport limits.

## Interceptors

Interceptors put one policy, such as authentication, validation, metadata
injection or error translation, around every unary call of a Client or Server.
An interceptor is any object with a `client_unary(call)` or `server_unary(call)`
method. Its block is the continuation: `yield` runs the next interceptor, or
dispatch for the innermost one.

```ruby
class BearerAuth
def initialize(tokens) = @tokens = tokens

def client_unary(call)
call.request_metadata["authorization"] = "Bearer #{@tokens.current}"
yield
end
end

class RequireTenant
def server_unary(call)
tenant = call.context.request_metadata["x-tenant"]
raise ConnectRPC::Error.new(:unauthenticated, "Missing tenant") unless tenant

yield
end
end

client = ConnectRPC::Client.new(base_url: url, binding: binding, interceptors: [BearerAuth.new(tokens)])
server = ConnectRPC::Server.new(services: services, binding: binding, handlers: handlers,
interceptors: [RequireTenant.new])
```

`interceptors:` defaults to an empty Array. Core discovers each element's method
once at construction and raises `ArgumentError` for an element without the
method for that role, so a server-only interceptor passed to a Client is
rejected. Streaming interceptors are not implemented yet: an element that
defines `client_stream` or `server_stream` also raises `ArgumentError`, rather
than being accepted and skipped on streams. Interceptor objects are shared by
concurrent calls; per-call state belongs in the call object. With no
interceptors, dispatch takes the same path as before.

The first interceptor listed is the outermost on both roles. It sees the call
first and the response or error last. Interceptors work with generated clients,
every unary transport, custom bindings and custom invokers, on Connect POST and
GET, [native gRPC](grpc.md#interceptors) and [gRPC-Web](grpc-web.md#interceptors).

### Continuation rules

Core enforces these rules and raises `ConnectRPC::InterceptorStateError` when
one is broken:

- Call the continuation at most once, on the fiber that called the interceptor,
and only before the interceptor returns. A second call, a call from another
thread, fiber or `Async` task, and a captured block called later all raise
and dispatch nothing. A second call or a call from another thread or fiber
also fails the call when the interceptor returns, even if the interceptor
swallows the error, and instrumentation records that misuse as the call's
error even if the interceptor translates it. A captured block called after
its interceptor returned only raises to its caller.
- A continuation fails when its block raises or is left by a `throw` or other
non-local exit. If a layer catches such a `throw` inside the chain and
returns, the call fails with the exception the continuation raised, or with
`InterceptorStateError` if it did not raise. A `throw` that leaves the
outermost interceptor propagates as it would without interceptors, and a
killed thread or fiber keeps dying.
- A client interceptor may return a `ConnectRPC::Response` without yielding,
for example from a local cache. Every other layer must yield; a server
interceptor that returns without yielding fails the call with `internal`.
- A client interceptor's normal return must be a `Response` whose `metadata` and
`trailers` are `ConnectRPC::Metadata`.
- No interceptor can turn a failed continuation into success. It may raise a
different exception to translate the failure. If it returns normally after
the continuation raised, core discards the return value and re-raises the
continuation's exception. On the server, a successful response therefore
always means the invoker returned successfully. To supply a client fallback,
rescue around `client.call`.

On the client an `InterceptorStateError` reaches the caller. On the server it is
recorded and becomes `internal`, like any unexpected handler exception.

### Client calls

`ClientUnaryCall` exposes `method`, `protocol` (`:connect` or `:grpc`),
`request`, `request_metadata`, `deadline` and `cancellation`. Until the
innermost continuation starts dispatch, `request=` replaces the message and
`request_metadata` accepts validated writes. Afterwards `request=` raises
`InterceptorStateError` and metadata writes raise `FrozenError`.

- The deadline and the call's cancellation arbiter start before the outermost
interceptor, so interceptor time counts against `timeout:`. `cancellation` is
a read-only view with `cancelled?`, `reason`, `check!` and `on_cancel`.
Interceptors cannot change the deadline. Core cannot interrupt an interceptor;
one that blocks on I/O should observe `deadline` or `cancellation` itself.
- Instrumentation injects its propagation headers after the chain, merging them
with interceptor-added metadata as caller metadata. The lifecycle records the
caller metadata before the chain and the metadata actually sent at dispatch.
- Every client unary `Response` is frozen, with or without interceptors: the
struct, its `metadata` and its `trailers`. Core freezes a short-circuit or
replacement `Response` before the next outer layer receives it. The message is
not copied or frozen, so a cached `Response` shares its message between
callers; return a fresh `Response` with a copied message when callers may
mutate it.
- A short-circuit records an outcome with no HTTP facts and `delivery:
:unobserved`. A rejection raised before `yield` never reaches the transport.

Core commits the call's outcome once, after the outermost interceptor returns
or raises. A cancellation or expiry accepted before then replaces a successful
result, and replaces a failure that came from dispatch: transport, codec,
metadata and status failures. An exception an interceptor raises, including a
translation of a dispatch failure, reaches the caller with its identity, and
the outcome reports its own code. Error-mapping interceptors should check
`call.cancellation.cancelled?` before translating, so an accepted cancellation
is not hidden.

### Server calls

Server interceptors run after the bounded read and decode, and around the
invoker, so a custom invoker is the innermost layer. They do not run for 405,
415, CORS preflight, undeclared methods or header, timeout, read and decode
failures. A declared method without a handler reaches the chain and fails with
the invoker's `unimplemented` error.

`ServerUnaryCall` exposes `method`, `protocol` (`:connect`, `:grpc` or
`:grpc_web`), `request`, `request=` (until dispatch) and `context`, the same
`Context` the handler receives:

- `context.request_metadata` is shared with the handler, so an interceptor can
add derived values such as a verified principal. Writes do not change the
request metadata that instrumentation recorded.
- Response metadata and trailers are written after the chain returns, so
writes before and after `yield` both reach the response, including the
error response when the call fails.
- A raised `ConnectRPC::Error` becomes the wire error with its details,
metadata and trailers. Any other exception becomes `internal`.
- After a successful continuation, the return value is the response message.
A nil return follows the handler nil path.
- The request deadline started when headers were parsed. The context's
`cancelled?`, `check!` and `on_cancel` work inside interceptors. Once the
context accepts cancellation or expiry, that reason is the wire error,
whatever the interceptor raises or returns.

### Failures and observation

Interceptors run inside the instrumentation activation, so observer spans are
current while they run and processing durations include their time. Core
records the exception escaping each continuation before the outer interceptor
sees it, and recording keeps the first failure. Observers therefore receive a
handler's or transport's original exception even after an interceptor
translated it, while the caller or wire receives the translation.

## Instrumentation

Pass `instrumentation: ConnectRPC::Instrumentation.new(subscribers: [recorder])`
Expand Down
2 changes: 1 addition & 1 deletion gems/connectrpc-async/scripts/package.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
lib/connectrpc/deadline.rb
lib/connectrpc/compression.rb lib/connectrpc/message_io.rb
lib/connectrpc/get_query.rb lib/connectrpc/protocol.rb
lib/connectrpc/client.rb lib/connectrpc/server.rb lib/connectrpc/instrumentation.rb
lib/connectrpc/client.rb lib/connectrpc/server.rb lib/connectrpc/instrumentation.rb lib/connectrpc/interceptors.rb
lib/connectrpc/metrics.rb lib/connectrpc/metrics/connection_observer.rb
lib/connectrpc/metrics/definitions.rb lib/connectrpc/metrics/subscriber.rb
lib/connectrpc/bindings/google_protobuf.rb lib/connectrpc/transports/net_http.rb
Expand Down
Loading