Stage 6: gateway edge (Connect/FlatBuffers over h2c, platform/email/guest auth, sessions, rate-limit, admin passthrough, live push bridge)
Tests · Go / test (push) Successful in 8s
Tests · Integration / integration (push) Successful in 11s
Tests · Go / test (pull_request) Successful in 6s
Tests · Integration / integration (pull_request) Successful in 10s

New public ingress and the first network edge. Framework + a vertical slice of
operations end-to-end; remaining ops reuse the same transcode pattern in Stage 7.

Contracts (new module scrabble/pkg):
- push.proto (backend->gateway gRPC server-stream) + scrabble.fbs (FlatBuffers
  edge payloads), committed generated Go; buf/flatc Makefiles (dev-time codegen).

Backend:
- REST handlers on the /api/v1 groups: internal session endpoints
  (telegram/guest/email login -> mint, resolve, revoke) and the user slice
  (profile, submit_play, state, lobby enqueue/poll, chat).
- internal/notify in-process Publisher hub + internal/pushgrpc gRPC server
  (BACKEND_GRPC_ADDR) streaming your_turn/opponent_moved/chat/nudge/match_found;
  emission in game.commit, social, matchmaker.
- migration 00005 accounts.is_guest; guests are durable rows excluded from stats;
  ProvisionGuest; email-as-login (RequestLoginCode/LoginWithCode).

Gateway (new module scrabble/gateway):
- Connect Gateway service over h2c (Execute + Subscribe), FlatBuffers<->JSON
  transcode registry, Telegram initData HMAC validator (seam), session cache,
  token-bucket rate limiter (3 classes), push fan-out hub, backend REST + push
  gRPC client, admin Basic-Auth reverse proxy.

go.work: use ./pkg, ./gateway + replace scrabble/pkg. CI: gateway/**, pkg/**
path filters; unit build/vet/test span all three modules. Docs (PLAN,
ARCHITECTURE, FUNCTIONAL+ru, TESTING, READMEs) updated; gateway/pkg unit tests +
guest/email-login integration tests.
This commit is contained in:
Ilia Denisov
2026-06-02 22:38:24 +02:00
parent 104eb2a978
commit 408da3f201
98 changed files with 8134 additions and 57 deletions
+191
View File
@@ -0,0 +1,191 @@
package backendclient
import (
"context"
"net/http"
"net/url"
)
// The structs below mirror the backend's JSON DTOs (backend/internal/server
// /dto.go). The transcode layer maps them to and from the FlatBuffers edge
// payloads.
// SessionResp is the credential minted by an auth operation.
type SessionResp struct {
Token string `json:"token"`
UserID string `json:"user_id"`
IsGuest bool `json:"is_guest"`
DisplayName string `json:"display_name"`
}
// ProfileResp is an account's own profile.
type ProfileResp struct {
UserID string `json:"user_id"`
DisplayName string `json:"display_name"`
PreferredLanguage string `json:"preferred_language"`
TimeZone string `json:"time_zone"`
HintBalance int `json:"hint_balance"`
BlockChat bool `json:"block_chat"`
BlockFriendRequests bool `json:"block_friend_requests"`
IsGuest bool `json:"is_guest"`
}
// TileJSON is one placed tile, used in both play requests and move responses.
type TileJSON struct {
Row int `json:"row"`
Col int `json:"col"`
Letter string `json:"letter"`
Blank bool `json:"blank"`
}
// MoveRecordResp is a decoded move.
type MoveRecordResp struct {
Player int `json:"player"`
Action string `json:"action"`
Dir string `json:"dir"`
MainRow int `json:"main_row"`
MainCol int `json:"main_col"`
Tiles []TileJSON `json:"tiles"`
Words []string `json:"words"`
Count int `json:"count"`
Score int `json:"score"`
Total int `json:"total"`
}
// SeatResp is one seat's public standing.
type SeatResp struct {
Seat int `json:"seat"`
AccountID string `json:"account_id"`
Score int `json:"score"`
HintsUsed int `json:"hints_used"`
IsWinner bool `json:"is_winner"`
}
// GameResp is the shared game summary.
type GameResp struct {
ID string `json:"id"`
Variant string `json:"variant"`
DictVersion string `json:"dict_version"`
Status string `json:"status"`
Players int `json:"players"`
ToMove int `json:"to_move"`
TurnTimeoutSecs int `json:"turn_timeout_secs"`
MoveCount int `json:"move_count"`
EndReason string `json:"end_reason"`
Seats []SeatResp `json:"seats"`
}
// MoveResultResp is the outcome of a committed move.
type MoveResultResp struct {
Move MoveRecordResp `json:"move"`
Game GameResp `json:"game"`
}
// StateResp is a player's view of a game.
type StateResp struct {
Game GameResp `json:"game"`
Seat int `json:"seat"`
Rack []string `json:"rack"`
BagLen int `json:"bag_len"`
HintsRemaining int `json:"hints_remaining"`
}
// MatchResp reports an auto-match outcome.
type MatchResp struct {
Matched bool `json:"matched"`
Game *GameResp `json:"game,omitempty"`
}
// ChatResp is a stored chat message.
type ChatResp struct {
ID string `json:"id"`
GameID string `json:"game_id"`
SenderID string `json:"sender_id"`
Kind string `json:"kind"`
Body string `json:"body"`
CreatedAtUnix int64 `json:"created_at_unix"`
}
// TelegramAuth provisions/finds the Telegram account and mints a session.
func (c *Client) TelegramAuth(ctx context.Context, externalID string) (SessionResp, error) {
var out SessionResp
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/telegram", "", "",
map[string]string{"external_id": externalID}, &out)
return out, err
}
// GuestAuth provisions a guest account and mints a session.
func (c *Client) GuestAuth(ctx context.Context) (SessionResp, error) {
var out SessionResp
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/guest", "", "", struct{}{}, &out)
return out, err
}
// EmailRequest asks the backend to mail a login code.
func (c *Client) EmailRequest(ctx context.Context, email string) error {
return c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/email/request", "", "",
map[string]string{"email": email}, nil)
}
// EmailLogin verifies a login code and mints a session.
func (c *Client) EmailLogin(ctx context.Context, email, code string) (SessionResp, error) {
var out SessionResp
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/email/login", "", "",
map[string]string{"email": email, "code": code}, &out)
return out, err
}
// ResolveSession maps a token to its account id (gateway session-cache miss).
func (c *Client) ResolveSession(ctx context.Context, token string) (string, error) {
var out struct {
UserID string `json:"user_id"`
}
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/resolve", "", "",
map[string]string{"token": token}, &out)
return out.UserID, err
}
// Profile returns the authenticated account's profile.
func (c *Client) Profile(ctx context.Context, userID string) (ProfileResp, error) {
var out ProfileResp
err := c.do(ctx, http.MethodGet, "/api/v1/user/profile", userID, "", nil, &out)
return out, err
}
// SubmitPlay commits a placement on the player's turn.
func (c *Client) SubmitPlay(ctx context.Context, userID, gameID, dir string, tiles []TileJSON) (MoveResultResp, error) {
var out MoveResultResp
body := map[string]any{"dir": dir, "tiles": tiles}
err := c.do(ctx, http.MethodPost, "/api/v1/user/games/"+url.PathEscape(gameID)+"/play", userID, "", body, &out)
return out, err
}
// GameState returns the player's view of a game.
func (c *Client) GameState(ctx context.Context, userID, gameID string) (StateResp, error) {
var out StateResp
err := c.do(ctx, http.MethodGet, "/api/v1/user/games/"+url.PathEscape(gameID)+"/state", userID, "", nil, &out)
return out, err
}
// Enqueue joins the auto-match pool for a variant.
func (c *Client) Enqueue(ctx context.Context, userID, variant string) (MatchResp, error) {
var out MatchResp
err := c.do(ctx, http.MethodPost, "/api/v1/user/lobby/enqueue", userID, "",
map[string]string{"variant": variant}, &out)
return out, err
}
// Poll reports whether the caller has been paired since queueing.
func (c *Client) Poll(ctx context.Context, userID string) (MatchResp, error) {
var out MatchResp
err := c.do(ctx, http.MethodGet, "/api/v1/user/lobby/poll", userID, "", nil, &out)
return out, err
}
// ChatPost stores a chat message, forwarding the client IP for moderation.
func (c *Client) ChatPost(ctx context.Context, userID, gameID, body, clientIP string) (ChatResp, error) {
var out ChatResp
err := c.do(ctx, http.MethodPost, "/api/v1/user/games/"+url.PathEscape(gameID)+"/chat", userID, clientIP,
map[string]string{"body": body}, &out)
return out, err
}
+122
View File
@@ -0,0 +1,122 @@
// Package backendclient is the gateway's typed client for the backend: REST/JSON
// for synchronous operations (injecting X-User-ID) and a gRPC subscription for
// the live push stream. The response structs mirror the backend's JSON DTOs; the
// transcode layer turns them into FlatBuffers for the client.
package backendclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pushv1 "scrabble/pkg/proto/push/v1"
)
// Client calls the backend's REST API and opens its push gRPC stream.
type Client struct {
baseURL string
http *http.Client
conn *grpc.ClientConn
push pushv1.PushClient
}
// New dials the backend push gRPC endpoint and prepares the REST client. The
// backend lives on a trusted network segment, so the gRPC connection uses
// insecure (plaintext) transport credentials (ARCHITECTURE.md §12).
func New(httpURL, grpcAddr string, timeout time.Duration) (*Client, error) {
conn, err := grpc.NewClient(grpcAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("backendclient: dial push %s: %w", grpcAddr, err)
}
return &Client{
baseURL: strings.TrimRight(httpURL, "/"),
http: &http.Client{Timeout: timeout},
conn: conn,
push: pushv1.NewPushClient(conn),
}, nil
}
// Close releases the gRPC connection.
func (c *Client) Close() error { return c.conn.Close() }
// APIError carries a backend error response so the transcode layer can surface a
// stable result code to the client.
type APIError struct {
Status int
Code string
Message string
}
func (e *APIError) Error() string {
return fmt.Sprintf("backend %d (%s): %s", e.Status, e.Code, e.Message)
}
// do performs one REST call. userID, when non-empty, is forwarded as X-User-ID;
// clientIP, when non-empty, as X-Forwarded-For (for chat moderation). A non-2xx
// response is returned as an *APIError carrying the backend error code.
func (c *Client) do(ctx context.Context, method, path, userID, clientIP string, body, out any) error {
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("backendclient: marshal request: %w", err)
}
reader = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
if err != nil {
return fmt.Errorf("backendclient: new request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if userID != "" {
req.Header.Set("X-User-ID", userID)
}
if clientIP != "" {
req.Header.Set("X-Forwarded-For", clientIP)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("backendclient: %s %s: %w", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("backendclient: read response: %w", err)
}
if resp.StatusCode >= http.StatusMultipleChoices {
return parseAPIError(resp.StatusCode, data)
}
if out != nil {
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("backendclient: decode response: %w", err)
}
}
return nil
}
// parseAPIError extracts the backend's {error:{code,message}} envelope.
func parseAPIError(status int, data []byte) *APIError {
var env struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(data, &env); err == nil && env.Error.Code != "" {
return &APIError{Status: status, Code: env.Error.Code, Message: env.Error.Message}
}
return &APIError{Status: status, Code: "backend_error", Message: strings.TrimSpace(string(data))}
}
// SubscribePush opens the backend live-event stream.
func (c *Client) SubscribePush(ctx context.Context, gatewayID string) (grpc.ServerStreamingClient[pushv1.Event], error) {
return c.push.Subscribe(ctx, &pushv1.SubscribeRequest{GatewayId: gatewayID})
}