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:
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.UnaryServerInterceptorAcceptance criteria
- When a unary handler panics with
boom: db password is hunter2,RecoverUnaryreturns a nil response and an error with status codecodes.Internal. Its client-facing message is exactlyinternal errorand does not exposehunter2. - When a unary handler panics with
boom-value, recovery logs contain the panic value, the full RPC method name fromunaryInfo.FullMethod, and a stack trace containingstackandgoroutine. - When a unary handler returns
"ok", nil, the response and error remain unchanged. When it returnsstatus.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,RecoverStreamreturns an error with status codecodes.Internaland messageinternal error. The panic value appears in the server-side logs. - When a streaming handler returns
nil,RecoverStreampreserves 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 codecodes.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.WithTimeoutfor 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.Isto recognize wrappedcontext.DeadlineExceedederrors. 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:
cd backend
make test W=7O2The 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.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
RecoverUnaryhandles unary handler panics.RecoverStreamhandles streaming handler panics.- Recovery logs contain diagnostic information without exposing it to clients.
TimeoutUnaryrespects existing client deadlines.- Deadline errors receive the correct gRPC status.
make test W=7O2passes all 10 tests.
Commands
cd backend && make test W=7O2Tests
TestW7O2_RecoverUnaryTurnsAPanicIntoInternalWithoutLeakingItinbackend/internal/grpcapi/resilience_test.goTestW7O2_RecoverUnaryLogsThePanicValueAndAStackTraceinbackend/internal/grpcapi/resilience_test.goTestW7O2_RecoverUnaryPassesResponsesAndErrorsThroughinbackend/internal/grpcapi/resilience_test.goTestW7O2_RecoverStreamTurnsAPanicIntoInternalinbackend/internal/grpcapi/resilience_test.goTestW7O2_RecoverStreamPassesNormalReturnsThroughinbackend/internal/grpcapi/resilience_test.goTestW7O2_TimeoutUnaryAddsADeadlineWhenTheClientSentNoneinbackend/internal/grpcapi/resilience_test.goTestW7O2_TimeoutUnaryKeepsAShorterClientDeadlineinbackend/internal/grpcapi/resilience_test.goTestW7O2_TimeoutUnaryCapsALongerClientDeadlineinbackend/internal/grpcapi/resilience_test.goTestW7O2_TimeoutUnaryReportsDeadlineExceededWhenTheHandlerGivesUpinbackend/internal/grpcapi/resilience_test.goTestW7O2_TimeoutUnaryWithAZeroLimitAddsNoDeadlineinbackend/internal/grpcapi/resilience_test.go