gRPC order service
You build a gRPC order service that accepts protobuf requests and returns order responses or a stream of order events. Protected calls reuse the JWT signer, and PlaceOrder requires idempotency metadata.
Ticket
Build the gRPC order service beside the existing HTTP API. It exposes GetOrder, PlaceOrder, Transition, and WatchOrder through the Protocol Buffers contract, while delegating order decisions to the existing order domain.
Other services need a typed RPC boundary without a second implementation of order behaviour. The Single-server capacity module follows this one, so you can measure a stack whose API includes both HTTP and gRPC.
The tests call these exported declarations directly:
var ErrNotFound error
type Store interface {
Get(ctx context.Context, id int64) (*ordersv1.Order, error)
Place(ctx context.Context, userID int64, key string, req *ordersv1.PlaceOrderRequest) (*ordersv1.Order, error)
Transition(ctx context.Context, p auth.Principal, orderID int64, eventID string, ev order.Event) (*ordersv1.Order, error)
Subscribe(ctx context.Context, orderID int64) (<-chan *ordersv1.WatchOrderResponse, error)
}
func New(store Store) *Server // *Server implements ordersv1.OrderServiceServer
func LogUnary(log *slog.Logger) grpc.UnaryServerInterceptor
func AuthUnary(signer *auth.Signer, public map[string]bool) grpc.UnaryServerInterceptor
func AuthStream(signer *auth.Signer) grpc.StreamServerInterceptorThe test builds the server with grpc.ChainUnaryInterceptor(LogUnary(...), AuthUnary(signer, map[string]bool{ordersv1.OrderService_GetOrder_FullMethodName: true})) and grpc.StreamInterceptor(AuthStream(signer)), so GetOrder is public and every other method needs a bearer token in the authorization metadata; a store that returns ErrNotFound maps to NotFound.
Acceptance criteria
GetOrdersucceeds without authentication for order7. Requesting order99returnsNotFound.PlaceOrderwithout a token returnsUnauthenticated. With a valid token but noidempotency-keymetadata, it returnsInvalidArgument.- Two
PlaceOrdercalls using the same valid token and idempotency keyk-1return the same order ID. TransitionreturnsPermissionDeniedwhen a customer sendsACCEPT,FailedPreconditionwhen a rider sendsDELIVERfrom the placed state,OKwhen a restaurant sendsACCEPT, andNotFoundfor a missing order with ID404.WatchOrderforwards events with IDse1ande2in that order, then terminates with EOF when the store channel closes.- The first
Recvon an unauthenticatedWatchOrderstream returnsUnauthenticated. - Against a running API, the end-to-end tests verify that an unknown order returns
NotFound. They also verify thatPlaceOrderwithout authentication returnsUnauthenticated, and that a request with authentication but withoutidempotency-keyreturnsInvalidArgument.
Constraints
- Use
backend/proto/orders/v1/orders.proto,backend/buf.yaml, andbackend/buf.gen.yamlas the generation inputs. Do not change their contracts or configuration. - Do not hand-edit generated files under
backend/gen/orders/v1/. Keep generated output reproducible from the provided inputs. - Do not modify the provided tests.
Design direction
Keep the transport adapter separate from the order domain. One reasonable layout puts the Store interface in internal/grpcapi/store.go, RPC handlers in server.go, error conversion in status.go, and authentication and logging in interceptors.go. Put gRPC server construction and registration in cmd/api/grpc.go. Any layout that meets the contract passes.
Keep the handlers thin. They should translate protobuf requests into calls to the existing store and translate returned orders into protobuf responses. Let the existing order domain own state transitions and business rules.
Think about where each responsibility belongs:
- Unary and streaming RPCs have different handler contexts. Use separate authentication interceptors and make the authenticated principal available to each handler.
- Centralized error conversion gives every RPC the same client-facing status for a given domain failure. Keep internal error details on the server side.
- A server stream can outlive an individual handler operation. Tie the store subscription to the stream context so cancellation can stop the subscription.
How to check your work
Run these commands from the backend/ directory in sequence:
cd backend
buf lint
buf generate
make test W=7B8
TEST_GRPC_ADDR=localhost:9090 TEST_API_URL=http://localhost:8080 go test -tags grpc ./e2e -run W7Run the end-to-end command with the API already running locally, including its HTTP endpoint on port 8080 and gRPC endpoint on port 9090. make e2e-grpc runs the same end-to-end tests. When a test fails, read the first failing assertion: it identifies the RPC, observed status or event sequence, and expected result.
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.
Order RPC interface
2 items
- 7.12Protobuf contracts in Gonot completed
- 7.13gRPC order servicenot completed
Up next · Module 5 · 1 items · about 50 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Protobuf code regenerates cleanly.
- The gRPC Store, handlers, error conversion, and interceptors are implemented.
- All six bufconn tests pass with
make test W=7B8. - The gRPC server is wired into the API alongside HTTP.
- The gRPC end-to-end tests pass against the locally running API.
Commands
cd backend && buf lint && buf generate && git diff --exit-code gen/cd backend && make test W=7B8cd backend && TEST_GRPC_ADDR=localhost:9090 TEST_API_URL=http://localhost:8080 go test -tags grpc ./e2e -run W7Tests
TestW7B8_GetOrderIsPublicAndMapsNotFoundinbackend/internal/grpcapi/server_test.goTestW7B8_PlaceOrderRequiresTokenAndIdempotencyKeyinbackend/internal/grpcapi/server_test.goTestW7B8_PlaceOrderTwiceWithSameKeyReturnsSameOrderinbackend/internal/grpcapi/server_test.goTestW7B8_TransitionMapsDomainErrorsToCodesinbackend/internal/grpcapi/server_test.goTestW7B8_WatchOrderStreamsUntilStoreClosesinbackend/internal/grpcapi/server_test.goTestW7B8_WatchOrderWithoutTokenIsUnauthenticatedinbackend/internal/grpcapi/server_test.go