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
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ architecture.

- `health` owns HTTP liveness/readiness behavior and dependency checks.
- `observability` owns opt-in request correlation and log enrichment, not sinks or product telemetry policy.
- `rpc` owns Connect unary server error normalization, not domain classification.
- `rpc` owns Connect v1 unary server error normalization, not domain classification.
It is deprecated; remove it in the next major release.
- `rpc/connectv2` owns the same normalization for Connect v2 servers.
- `service` owns process-serving and graceful-shutdown behavior.
- `cmd/example` demonstrates composition and may depend on every public package.
- Public library packages must not depend on `cmd`, examples, or a consumer.
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ debug information for development.
| [`database`](./database) | Bounded SQL startup, pool configuration, and readiness checks |
| [`health`](./health) | Liveness and readiness probes with bounded dependency checks |
| [`observability`](./observability) | Trusted-proxy-aware request IDs and context-aware log correlation |
| [`rpc`](./rpc) | Safe Connect unary server error boundaries |
| [`rpc`](./rpc) | Deprecated: safe Connect v1 unary server error boundaries |
| [`rpc/connectv2`](./rpc/connectv2) | Safe Connect v2 server error boundaries |
| [`service`](./service) | HTTP serving, graceful shutdown, and post-drain resource cleanup |

The foundations cover process lifecycle, health, driver-neutral SQL pools,
request/log correlation, and unary RPC error boundaries. Further RPC conventions, queries, authentication mechanisms, shared
request/log correlation, and RPC error boundaries for Connect v1 and v2. Further RPC conventions, queries, authentication mechanisms, shared
contracts, and test infrastructure will be extracted only when a real consumer
gives us a concrete API to design.

Expand Down
7 changes: 7 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ database health observability service
└──────────┴────────────┴─────────────┴── Go standard library

rpc ── Connect ── Protobuf
rpc/connectv2 ── Connect v2 ── Protobuf
```

`database`, `health`, `observability`, and `service` are independent foundations. The example application
Expand All @@ -29,6 +30,12 @@ and interceptors directly rather than introducing a parallel status abstraction.
The other foundations retain their standard-library-only imports. Consumers
that do not import `rpc` do not link Connect into their binaries.

`rpc/connectv2` is the same boundary for `connectrpc.com/connect/v2`, a separate
module path with a stream-based server API. It does not import `rpc`; the shared
rules are duplicated deliberately so neither Connect major version links the
other. Keeping both preserves the v1 API for existing consumers; `rpc` is
deprecated and will be removed in the next major release.

The concrete extraction is a unary error boundary: repeated transport handlers
were wrapping unexpected storage and authorization-check failures with raw error
messages. Normalization removes internal diagnostics while leaving domain status
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ go 1.27.0

require (
connectrpc.com/connect v1.21.1
connectrpc.com/connect/v2 v2.0.2
google.golang.org/protobuf v1.36.12
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
connectrpc.com/connect v1.21.1 h1:h2kacdlzXpZU2OQFSv98xkjYXNUSr/ptxmGVbS/+CRM=
connectrpc.com/connect v1.21.1/go.mod h1:fhMcVJ5w6r/yTYhnkEbW6+sIF7OZ5Ay7KYgmfebh2ek=
connectrpc.com/connect/v2 v2.0.2 h1:PoPDmOlhc46elsuCdKCKTxjNBb3HJlKF+s/sP2oucPw=
connectrpc.com/connect/v2 v2.0.2/go.mod h1:N32OLrstcPUzkykFynnefFro3+xzSdOrZlK2jHmS/xo=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
Expand Down
44 changes: 26 additions & 18 deletions observability/rpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,50 +6,58 @@ import (
"encoding/json/v2"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"

"connectrpc.com/connect"
"connectrpc.com/connect/v2"
"connectrpc.com/connect/v2/connecthttp"
"github.com/fuf-stack/hardcore/observability"
"github.com/fuf-stack/hardcore/rpc"
"github.com/fuf-stack/hardcore/rpc/connectv2"
"google.golang.org/protobuf/types/known/emptypb"
)

// TestConnectErrorCorrelation logs once inside normalization without wire leakage.
func TestConnectErrorCorrelation(t *testing.T) {
var output bytes.Buffer
logger := slog.New(observability.NewLogHandler(slog.NewJSONHandler(&output, nil)))
logErrors := connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
res, err := next(ctx, req)
logErrors := func(next connect.ServerFunc) connect.ServerFunc {
return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
err := next(ctx, spec, stream)
if err != nil {
// The application deliberately selects a safe diagnostic, not raw error text.
logger.ErrorContext(ctx, "operation failed", "error_class", "internal")
}
return res, err
return err
}
})
}
correlate, err := observability.NewRequestIDMiddleware()
if err != nil {
t.Fatal(err)
}
handler := connect.NewUnaryHandler("/example.v1.Service/Call",
func(context.Context, *connect.Request[emptypb.Empty]) (*connect.Response[emptypb.Empty], error) {
return nil, errors.New("private backend detail")
}, connect.WithInterceptors(rpc.UnaryErrorInterceptor(), logErrors))
server := httptest.NewServer(correlate(handler))
defer server.Close()
client := connect.NewClient[emptypb.Empty, emptypb.Empty](server.Client(), server.URL+"/example.v1.Service/Call")
_, err = client.CallUnary(t.Context(), connect.NewRequest(&emptypb.Empty{}))
spec := connect.Spec{StreamType: connect.StreamTypeUnary, Procedure: "/example.v1.Service/Call"}
server := connect.NewServer(connectv2.ServerErrorInterceptor(), logErrors)
server.Register(connect.Method{Spec: spec, Handler: func(_ context.Context, _ connect.Spec, stream connect.ServerStream) error {
if err := stream.Receive(&emptypb.Empty{}); err != nil {
return err
}
return errors.New("private backend detail")
}})
mux := http.NewServeMux()
connecthttp.Mount(mux, server)
httpServer := httptest.NewServer(correlate(mux))
defer httpServer.Close()
client := connect.NewClient(connecthttp.NewTransport(httpServer.Client(), httpServer.URL))
ctx, info := connect.NewClientContext(t.Context())
err = client.CallUnary(ctx, spec, &emptypb.Empty{}, &emptypb.Empty{})
if connect.CodeOf(err) != connect.CodeInternal || strings.Contains(err.Error(), "private") {
t.Fatalf("unexpected wire error: %v", err)
}
wire, ok := errors.AsType[*connect.Error](err)
if !ok {
if _, ok := errors.AsType[*connect.Error](err); !ok {
t.Fatal("missing Connect error")
}
id := wire.Meta().Get(observability.RequestIDHeader)
id := info.ResponseHeader().Get(observability.RequestIDHeader)
lines := strings.Split(strings.TrimSpace(output.String()), "\n")
if len(lines) != 1 {
t.Fatalf("log count = %d; want 1", len(lines))
Expand Down
4 changes: 4 additions & 0 deletions rpc/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# RPC error boundaries

> **Deprecated:** this package targets Connect v1. New servers should use
> [`rpc/connectv2`](./connectv2) with `connectrpc.com/connect/v2`. This package
> will be removed in the next major release.

`rpc` provides `NormalizeError` and `UnaryErrorInterceptor` for Connect unary
servers. It contains no service contracts, domain error mappings, or access policy.

Expand Down
47 changes: 47 additions & 0 deletions rpc/connectv2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Connect v2 error boundaries

`connectv2` provides `NormalizeError` and `ServerErrorInterceptor` for servers
built on `connectrpc.com/connect/v2`. It is the Connect v2 counterpart of
[`rpc`](..), which keeps serving Connect v1. It contains no service contracts,
domain error mappings, or access policy.

```go
server := connect.NewServer(connectv2.ServerErrorInterceptor(), logging)
examplev1connect.RegisterEchoServiceHandler(server, echo)
connecthttp.Mount(mux, server)
```

Pass the interceptor first (outermost). Inner logging interceptors can record
the original error before normalization. Nothing is logged automatically.

- Cancellation and deadline errors receive their corresponding Connect codes.
- Explicit local Connect errors are trusted public responses; their wrapper
text is removed, but their messages and details are otherwise preserved.
- Internal and unknown Connect errors are exceptions: only their code survives,
with the public message `internal error` and no details or cause.
- Remote Connect errors, a peer's verdict returned unchanged by the handler,
become internal errors without the peer's code, message, or details.
- Unclassified errors become internal errors without exposing their cause.

## Differences from `rpc`

Connect v2 server interceptors surround the whole call, so the boundary covers
unary and streaming RPCs alike. On streams it replaces only the final error;
messages already sent are unaffected. Connect v2 errors carry no metadata, so
response headers and trailers set by handlers pass through unchanged. Remote
errors are handled explicitly because v2 marks them; `rpc` has no such signal.

An explicit Connect status takes precedence over wrapped context errors. For
joined context errors without an explicit status, deadline takes precedence.
Applications must supply safe public messages and details for other explicit
status codes; wrapping a database failure as unavailable does **not** make its
text safe.

Domain classification stays in the application. Return a safe Connect error for
expected failures and an ordinary error for unexpected failures. There are no
settings or environment variables. Do not use this boundary on clients.

Panic recovery, HTTP middleware errors, and protocol-level errors raised before
the interceptor chain runs are not covered. Test the complete application's HTTP
boundary separately. Run `make check` for unit and real HTTP round-trip tests of
unary and server-streaming calls.
60 changes: 60 additions & 0 deletions rpc/connectv2/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Package connectv2 provides product-neutral Connect v2 server error boundaries.
// It mirrors package rpc, which targets Connect v1, for servers built on
// connectrpc.com/connect/v2.
package connectv2

import (
"context"
"errors"

"connectrpc.com/connect/v2"
)

// internalMessage is the only public message for redacted failures.
const internalMessage = "internal error"

// NormalizeError prepares a handler error for public transport. Nil stays nil.
// Explicit local Connect errors are trusted public responses, except Internal
// and Unknown: their messages, details, and causes are discarded. Remote errors,
// a peer's verdict returned unchanged by the handler, become Internal without
// their code, message, or details. Wrapped Connect errors retain only the
// underlying Connect error, not wrapper text. Otherwise context errors receive
// stable codes and all other errors become Internal. The original error is not
// retained; log it before this boundary. Consumers remain responsible for safe
// messages and details on other explicit status codes.
func NormalizeError(err error) error {
if err == nil {
return nil
}
if wire, ok := errors.AsType[*connect.Error](err); ok && wire != nil {
switch {
case wire.IsRemote():
return connect.NewError(connect.CodeInternal, internalMessage)
case wire.Code() == connect.CodeInternal, wire.Code() == connect.CodeUnknown:
return connect.NewError(wire.Code(), internalMessage)
default:
return wire
}
}
if errors.Is(err, context.DeadlineExceeded) {
return connect.NewError(connect.CodeDeadlineExceeded, context.DeadlineExceeded.Error())
}
if errors.Is(err, context.Canceled) {
return connect.NewError(connect.CodeCanceled, context.Canceled.Error())
}
return connect.NewError(connect.CodeInternal, internalMessage)
}

// ServerErrorInterceptor normalizes the error that ends any server RPC, unary
// or streaming. Pass it first to connect.NewServer so it surrounds the other
// interceptors; inner logging can observe the original error. Messages already
// sent on a stream are not affected. It does not recover panics or cover HTTP
// middleware or protocol errors raised before the interceptor chain runs.
// Do not use it on clients: it deliberately discards diagnostic information.
func ServerErrorInterceptor() connect.ServerInterceptor {
return func(next connect.ServerFunc) connect.ServerFunc {
return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
return NormalizeError(next(ctx, spec, stream))
}
}
}
Loading
Loading