gRPC resilience interceptors

You build three gRPC interceptors that wrap unary and streaming handlers, recover panics as generic Internal errors, and enforce unary deadlines without extending client deadlines.

Ticket

You build three interceptors in the existing grpcapi package: unary panic recovery, streaming panic recovery and unary timeout enforcement. They wrap existing handlers and return appropriate gRPC errors when a panic or deadline failure occurs.

Your gRPC service must survive unexpected handler failures without exposing internal details to clients. A server timeout must also respect the time budget established by the client. The tests invoke your interceptors directly with fake handlers, so you do not need to start a gRPC server.

The tests call these exported declarations:

go
package grpcapi

import (
    "log/slog"
    "time"

    "google.golang.org/grpc"
)

func RecoverUnary(log *slog.Logger) grpc.UnaryServerInterceptor
func RecoverStream(log *slog.Logger) grpc.StreamServerInterceptor
func TimeoutUnary(d time.Duration) grpc.UnaryServerInterceptor

Acceptance criteria

  • When a unary handler panics with boom: db password is hunter2, RecoverUnary returns a nil response and an error with status code codes.Internal. Its client-facing message is exactly internal error and does not expose hunter2.
  • When a unary handler panics with boom-value, recovery logs contain the panic value, the full RPC method name from unaryInfo.FullMethod, and a stack trace containing stack and goroutine.
  • When a unary handler returns "ok", nil, the response and error remain unchanged. When it returns status.Error(codes.NotFound, "no such order"), the original error is preserved. Neither normal execution nor an ordinary handler error produces recovery logs.
  • When a streaming handler panics with stream-boom, RecoverStream returns an error with status code codes.Internal and message internal error. The panic value appears in the server-side logs.
  • When a streaming handler returns nil, RecoverStream preserves the nil error.
  • When the incoming context has no deadline, TimeoutUnary(2*time.Second) gives the handler a deadline between one and three seconds after the test starts.
  • When the client context has a 50-millisecond deadline and the interceptor timeout is five seconds, the handler retains the client's earlier deadline. The observed deadline must be less than one second after the test starts.
  • When the client context has a one-hour deadline and the interceptor timeout is one second, the handler receives the server's shorter deadline, no later than two seconds after the test starts.
  • When a handler waits for its context to expire and returns ctx.Err() under a 20-millisecond timeout, the interceptor returns an error with status code codes.DeadlineExceeded.
  • When the interceptor timeout is zero, the handler receives the original context without a deadline.

Constraints

  • Do not modify the provided tests.

Design direction

Keep the three interceptors in the existing grpcapi package. A natural location is backend/internal/grpcapi/resilience.go. Any layout that meets the contract passes.

Consider these design choices:

  • Give unary and streaming recovery separate handler boundaries because their signatures differ. Keep their error policy consistent.
  • Put deferred recovery in the same function scope as the handler invocation. This lets recover() observe a panic while the handler is unwinding.
  • Use context.WithTimeout for positive durations. Go preserves the earlier deadline automatically, so you do not need to calculate which deadline wins yourself. Cancel the derived context after the handler returns.
  • Use errors.Is to recognize wrapped context.DeadlineExceeded errors. Preserve other handler errors rather than converting every failure into a timeout.

You may optionally register the interceptors in backend/cmd/api/grpc.go. When composing the unary chain, place RecoverUnary first, followed by TimeoutUnary, then the existing interceptors. This wiring is not required or tested. Keep existing authentication and logging behavior intact.

How to check your work

Run the optional exercise tests from the backend directory:

bash
cd backend
make test W=7O2

The runner applies the w7o2 build tag automatically. Read the first failing assertion and identify whether the failure concerns panic recovery, logged diagnostics, context deadlines or error classification.

Finished Exercise 7.17?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. RecoverUnary handles unary handler panics.
  2. RecoverStream handles streaming handler panics.
  3. Recovery logs contain diagnostic information without exposing it to clients.
  4. TimeoutUnary respects existing client deadlines.
  5. Deadline errors receive the correct gRPC status.
  6. make test W=7O2 passes all 10 tests.

Commands

terminal
cd backend && make test W=7O2

Tests

  • TestW7O2_RecoverUnaryTurnsAPanicIntoInternalWithoutLeakingIt in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_RecoverUnaryLogsThePanicValueAndAStackTrace in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_RecoverUnaryPassesResponsesAndErrorsThrough in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_RecoverStreamTurnsAPanicIntoInternal in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_RecoverStreamPassesNormalReturnsThrough in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_TimeoutUnaryAddsADeadlineWhenTheClientSentNone in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_TimeoutUnaryKeepsAShorterClientDeadline in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_TimeoutUnaryCapsALongerClientDeadline in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_TimeoutUnaryReportsDeadlineExceededWhenTheHandlerGivesUp in backend/internal/grpcapi/resilience_test.go
  • TestW7O2_TimeoutUnaryWithAZeroLimitAddsNoDeadline in backend/internal/grpcapi/resilience_test.go