t1k:nakama:rpc
| Field | Value |
|---|---|
| Module | base |
| Version | 1.6.2 |
| Effort | low |
| Tools | — |
Keywords: gRPC, JSON, nakama, proxy, remote procedure call, rpc, server
How to invoke
Section titled “How to invoke”/t1k:nakama:rpcNakama RPC Development
Section titled “Nakama RPC Development”Overview
Section titled “Overview”RPCs are the primary client-server communication channel. Each RPC receives a JSON string payload from the client and returns a JSON string response. In the proxy architecture, RPCs convert JSON to gRPC requests, call the Gameplay service, and convert responses back.
Key Patterns
Section titled “Key Patterns”RPC Registration
Section titled “RPC Registration”initializer.RegisterRpc("rpc_name", handlerFunc)RPC Handler Signature
Section titled “RPC Handler Signature”func handler(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, payload string) (string, error) { // 1. Check gRPC connection // 2. Parse JSON payload // 3. Extract user ID from ctx // 4. Convert to gRPC request // 5. Call Gameplay service // 6. Convert response to JSON // 7. Return JSON string}Proxy Pattern (internal/gameplay/)
Section titled “Proxy Pattern (internal/gameplay/)”if !client.IsConnected() { return "", runtime.NewError("gameplay service unavailable", 14) // UNAVAILABLE}userID, _ := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string)// ... build gRPC request with userIDresp, err := client.SomeMethod(ctx, req)if err != nil { return "", mapGRPCError(err)}jsonBytes, _ := json.Marshal(convertResponse(resp))return string(jsonBytes), nilError Mapping
Section titled “Error Mapping”gRPC status codes map to Nakama runtime error codes:
codes.NotFound→runtime.NewError(msg, 5)(NOT_FOUND)codes.InvalidArgument→runtime.NewError(msg, 3)(INVALID_ARGUMENT)codes.Unavailable→runtime.NewError(msg, 14)(UNAVAILABLE)codes.Internal→runtime.NewError(msg, 13)(INTERNAL)
Gotchas
Section titled “Gotchas”- RPC
payloadis a raw JSON string — always validate/unmarshal before use - Return empty string
""with error for failures, not("{}", error) - RPC names must be globally unique across all registered RPCs
- Context keys like
RUNTIME_CTX_USER_IDmay be empty for unauthenticated RPCs - Always check
client.IsConnected()before gRPC calls - Unexported fields: Go’s JSON marshaling silently skips unexported struct fields. Always use uppercase field names or
json:"tag". - gRPC deadline propagation: Always propagate context deadlines from Nakama to gRPC calls. Missing deadlines cause requests to hang forever.
- Context cancellation: Check
ctx.Err()before expensive operations. Client disconnects cancel the context.
Checklist
Section titled “Checklist”- RPC registered in
InitModuleviainitializer.RegisterRpc - Handler validates payload before processing
- User ID extracted from context where needed
- gRPC errors mapped to appropriate Nakama error codes
- Response serialized as compact JSON string
- Mock endpoint added in
gameplay_mock.goif applicable