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:

go
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.StreamServerInterceptor

The 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

  • GetOrder succeeds without authentication for order 7. Requesting order 99 returns NotFound.
  • PlaceOrder without a token returns Unauthenticated. With a valid token but no idempotency-key metadata, it returns InvalidArgument.
  • Two PlaceOrder calls using the same valid token and idempotency key k-1 return the same order ID.
  • Transition returns PermissionDenied when a customer sends ACCEPT, FailedPrecondition when a rider sends DELIVER from the placed state, OK when a restaurant sends ACCEPT, and NotFound for a missing order with ID 404.
  • WatchOrder forwards events with IDs e1 and e2 in that order, then terminates with EOF when the store channel closes.
  • The first Recv on an unauthenticated WatchOrder stream returns Unauthenticated.
  • Against a running API, the end-to-end tests verify that an unknown order returns NotFound. They also verify that PlaceOrder without authentication returns Unauthenticated, and that a request with authentication but without idempotency-key returns InvalidArgument.

Constraints

  • Use backend/proto/orders/v1/orders.proto, backend/buf.yaml, and backend/buf.gen.yaml as 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:

bash
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 W7

Run 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.

Finished Exercise 7.13?

Order RPC interface

2 items

  • 7.12Protobuf contracts in Gonot completed
  • 7.13gRPC order servicenot completed

Single-server capacity

Up next · Module 5 · 1 items · about 50 min

Start module 5

Implementation

Run locally

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

  1. Protobuf code regenerates cleanly.
  2. The gRPC Store, handlers, error conversion, and interceptors are implemented.
  3. All six bufconn tests pass with make test W=7B8.
  4. The gRPC server is wired into the API alongside HTTP.
  5. The gRPC end-to-end tests pass against the locally running API.

Commands

terminal
cd backend && buf lint && buf generate && git diff --exit-code gen/
terminal
cd backend && make test W=7B8
terminal
cd backend && TEST_GRPC_ADDR=localhost:9090 TEST_API_URL=http://localhost:8080 go test -tags grpc ./e2e -run W7

Tests

  • TestW7B8_GetOrderIsPublicAndMapsNotFound in backend/internal/grpcapi/server_test.go
  • TestW7B8_PlaceOrderRequiresTokenAndIdempotencyKey in backend/internal/grpcapi/server_test.go
  • TestW7B8_PlaceOrderTwiceWithSameKeyReturnsSameOrder in backend/internal/grpcapi/server_test.go
  • TestW7B8_TransitionMapsDomainErrorsToCodes in backend/internal/grpcapi/server_test.go
  • TestW7B8_WatchOrderStreamsUntilStoreCloses in backend/internal/grpcapi/server_test.go
  • TestW7B8_WatchOrderWithoutTokenIsUnauthenticated in backend/internal/grpcapi/server_test.go