e16076c89e
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Successful in 11s
CI / ui (pull_request) Successful in 31s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 55s
Close out Stage 17 round 6: - Landing page at / — one Vite build with two entries (index.html = game SPA, landing.html = a lightweight landing reusing the theme/i18n/ aboutContent leaf modules, not the app store). - Move the web game SPA to /app/; the Telegram Mini App stays at /telegram/ (gateway webui.Handler(stripPrefix, indexName): landing at /, SPA at /app/ + /telegram/). Per-language "Play in Telegram" link via new VITE_TELEGRAM_LINK_EN/_RU build vars (button hides when unset). - Cache headers: hash-named /assets/* immutable, HTML shells no-cache (the go:embed zero modtime emitted no validators, so the client re-downloaded the whole bundle every launch). - Live-stream 15s abort fix: an immediate heartbeat on open + a 10s default interval (the first tick at 15s raced the edge idle timeout -> reconnect storm). PLAN/ARCHITECTURE(§13)/FUNCTIONAL(+ru)/gateway+ui+deploy READMEs updated; round 6 closed. Tests: gateway webui/connectsrv units, ui landing unit + e2e, full e2e (60) green.
260 lines
8.6 KiB
Go
260 lines
8.6 KiB
Go
// Package connectsrv implements the public Connect edge service over h2c. Execute
|
|
// rate-limits, authenticates (resolving the Authorization bearer token to a user
|
|
// id for non-auth operations), and dispatches to the transcode registry; the
|
|
// domain outcome is carried back in the ExecuteResponse result_code. Subscribe
|
|
// bridges the gateway push hub to a client server-stream with a keep-alive
|
|
// heartbeat.
|
|
package connectsrv
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"connectrpc.com/connect"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"go.uber.org/zap"
|
|
"golang.org/x/net/http2"
|
|
"golang.org/x/net/http2/h2c"
|
|
|
|
"scrabble/gateway/internal/config"
|
|
"scrabble/gateway/internal/push"
|
|
"scrabble/gateway/internal/ratelimit"
|
|
"scrabble/gateway/internal/session"
|
|
"scrabble/gateway/internal/transcode"
|
|
"scrabble/gateway/internal/webui"
|
|
edgev1 "scrabble/gateway/proto/edge/v1"
|
|
"scrabble/gateway/proto/edge/v1/edgev1connect"
|
|
)
|
|
|
|
// heartbeatKind is the live-stream keep-alive event kind.
|
|
const heartbeatKind = "heartbeat"
|
|
|
|
// Server implements edgev1connect.GatewayHandler.
|
|
type Server struct {
|
|
registry *transcode.Registry
|
|
sessions *session.Cache
|
|
limiter *ratelimit.Limiter
|
|
hub *push.Hub
|
|
heartbeat time.Duration
|
|
log *zap.Logger
|
|
adminProxy http.Handler
|
|
metrics *serverMetrics
|
|
|
|
publicPolicy ratelimit.Policy
|
|
userPolicy ratelimit.Policy
|
|
emailPolicy ratelimit.Policy
|
|
}
|
|
|
|
// Deps carries the Server's dependencies.
|
|
type Deps struct {
|
|
Registry *transcode.Registry
|
|
Sessions *session.Cache
|
|
Limiter *ratelimit.Limiter
|
|
Hub *push.Hub
|
|
RateLimit config.RateLimitConfig
|
|
Heartbeat time.Duration
|
|
Logger *zap.Logger
|
|
AdminProxy http.Handler
|
|
Meter metric.Meter
|
|
}
|
|
|
|
// NewServer constructs the edge service.
|
|
func NewServer(d Deps) *Server {
|
|
log := d.Logger
|
|
if log == nil {
|
|
log = zap.NewNop()
|
|
}
|
|
return &Server{
|
|
registry: d.Registry,
|
|
sessions: d.Sessions,
|
|
limiter: d.Limiter,
|
|
hub: d.Hub,
|
|
heartbeat: d.Heartbeat,
|
|
log: log,
|
|
adminProxy: d.AdminProxy,
|
|
metrics: newServerMetrics(d.Meter),
|
|
publicPolicy: ratelimit.PerMinute(d.RateLimit.PublicPerMinute, d.RateLimit.PublicBurst),
|
|
userPolicy: ratelimit.PerMinute(d.RateLimit.UserPerMinute, d.RateLimit.UserBurst),
|
|
emailPolicy: ratelimit.Per(d.RateLimit.EmailPer10Min, 10*time.Minute, d.RateLimit.EmailBurst),
|
|
}
|
|
}
|
|
|
|
// HTTPHandler returns the h2c-wrapped Connect handler ready to serve.
|
|
func (s *Server) HTTPHandler() http.Handler {
|
|
mux := http.NewServeMux()
|
|
path, h := edgev1connect.NewGatewayHandler(s)
|
|
mux.Handle(path, h)
|
|
if s.adminProxy != nil {
|
|
// The admin console (backend /_gm) is served on the public listener behind
|
|
// the proxy's Basic-Auth, mounted below the h2c wrap so the Connect edge keeps
|
|
// working over h2c (docs/ARCHITECTURE.md §12). In the deployed contour the
|
|
// front caddy owns the /_gm Basic-Auth and Grafana routing; this mount serves
|
|
// a non-caddy (local) setup.
|
|
mux.Handle("/_gm/", s.adminProxy)
|
|
} else {
|
|
// With the console disabled here, keep /_gm a 404 so the SPA catch-all below
|
|
// does not serve the app shell at the operator path.
|
|
mux.Handle("/_gm/", http.NotFoundHandler())
|
|
}
|
|
// The embedded UI: the game SPA under /app/ (web) and /telegram/ (the Telegram Mini
|
|
// App), with a separate landing page at the catch-all "/" — the single-origin model
|
|
// (docs/ARCHITECTURE.md §13). All sit below the h2c wrap so the Connect edge (a more
|
|
// specific prefix) keeps priority. Each SPA mount falls back to the app shell
|
|
// (index.html) for the hash router; "/" falls back to the landing (landing.html).
|
|
mux.Handle("/telegram/", webui.Handler("/telegram/", "index.html"))
|
|
mux.Handle("/app/", webui.Handler("/app/", "index.html"))
|
|
mux.Handle("/", webui.Handler("", "landing.html"))
|
|
return h2c.NewHandler(mux, &http2.Server{})
|
|
}
|
|
|
|
// Execute runs one unary operation. Domain failures are returned in the envelope
|
|
// (result_code != "ok", HTTP 200); only edge failures (rate limit, missing
|
|
// session, unknown type, internal) become Connect errors.
|
|
func (s *Server) Execute(ctx context.Context, req *connect.Request[edgev1.ExecuteRequest]) (*connect.Response[edgev1.ExecuteResponse], error) {
|
|
start := time.Now()
|
|
msgType := req.Msg.GetMessageType()
|
|
result := "internal"
|
|
defer func() { s.metrics.recordEdge(ctx, msgType, result, start) }()
|
|
|
|
op, ok := s.registry.Lookup(msgType)
|
|
if !ok {
|
|
result = "unknown_type"
|
|
return nil, connect.NewError(connect.CodeNotFound, errUnknownMessageType(msgType))
|
|
}
|
|
clientIP := peerIP(req.Peer().Addr, req.Header())
|
|
|
|
tr := transcode.Request{Payload: req.Msg.GetPayload(), ClientIP: clientIP}
|
|
if op.Auth {
|
|
uid, err := s.resolve(ctx, req.Header())
|
|
if err != nil {
|
|
result = "unauthenticated"
|
|
return nil, err
|
|
}
|
|
// A valid session proving an authenticated request is an "action" for the
|
|
// active_users gauge, counted before the rate-limit/domain outcome.
|
|
s.metrics.recordActive(uid)
|
|
if !s.limiter.Allow("user:"+uid, s.userPolicy) {
|
|
result = "rate_limited"
|
|
return nil, connect.NewError(connect.CodeResourceExhausted, errRateLimited)
|
|
}
|
|
tr.UserID = uid
|
|
} else {
|
|
if !s.limiter.Allow("ip:"+clientIP, s.publicPolicy) {
|
|
result = "rate_limited"
|
|
return nil, connect.NewError(connect.CodeResourceExhausted, errRateLimited)
|
|
}
|
|
if op.Email && !s.limiter.Allow("email:"+clientIP, s.emailPolicy) {
|
|
result = "rate_limited"
|
|
return nil, connect.NewError(connect.CodeResourceExhausted, errRateLimited)
|
|
}
|
|
}
|
|
|
|
payload, err := op.Handler(ctx, tr)
|
|
if err != nil {
|
|
if code, domain := transcode.DomainCode(err); domain {
|
|
result = "domain"
|
|
return connect.NewResponse(&edgev1.ExecuteResponse{
|
|
RequestId: req.Msg.GetRequestId(),
|
|
ResultCode: code,
|
|
}), nil
|
|
}
|
|
s.log.Error("execute failed", zap.String("message_type", msgType), zap.Error(err))
|
|
return nil, connect.NewError(connect.CodeInternal, errInternal)
|
|
}
|
|
result = "ok"
|
|
return connect.NewResponse(&edgev1.ExecuteResponse{
|
|
RequestId: req.Msg.GetRequestId(),
|
|
ResultCode: "ok",
|
|
Payload: payload,
|
|
}), nil
|
|
}
|
|
|
|
// Subscribe streams the authenticated user's live events with a keep-alive
|
|
// heartbeat until the client disconnects.
|
|
func (s *Server) Subscribe(ctx context.Context, req *connect.Request[edgev1.SubscribeRequest], stream *connect.ServerStream[edgev1.Event]) error {
|
|
uid, err := s.resolve(ctx, req.Header())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !s.limiter.Allow("user:"+uid, s.userPolicy) {
|
|
return connect.NewError(connect.CodeResourceExhausted, errRateLimited)
|
|
}
|
|
|
|
events, cancel := s.hub.Subscribe(uid)
|
|
defer cancel()
|
|
|
|
// Send an immediate heartbeat so the stream's first byte flushes through the proxy chain
|
|
// right away and resets edge/client idle timers, instead of the connection sitting silent
|
|
// until the first tick — which otherwise raced a ~15 s idle timeout and forced a reconnect
|
|
// every interval (Stage 17).
|
|
if err := stream.Send(&edgev1.Event{Kind: heartbeatKind}); err != nil {
|
|
return err
|
|
}
|
|
|
|
ticker := time.NewTicker(s.heartbeat)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil
|
|
case <-ticker.C:
|
|
if err := stream.Send(&edgev1.Event{Kind: heartbeatKind}); err != nil {
|
|
return err
|
|
}
|
|
case e, ok := <-events:
|
|
if !ok {
|
|
return nil
|
|
}
|
|
if err := stream.Send(&edgev1.Event{Kind: e.Kind, Payload: e.Payload, EventId: e.EventID}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// resolve extracts and resolves the Authorization bearer token to an account id,
|
|
// returning a Connect Unauthenticated error when it is missing or unknown.
|
|
func (s *Server) resolve(ctx context.Context, h http.Header) (string, error) {
|
|
token := bearerToken(h.Get("Authorization"))
|
|
if token == "" {
|
|
return "", connect.NewError(connect.CodeUnauthenticated, errMissingToken)
|
|
}
|
|
uid, err := s.sessions.Resolve(ctx, token)
|
|
if err != nil {
|
|
return "", connect.NewError(connect.CodeUnauthenticated, errInvalidSession)
|
|
}
|
|
return uid, nil
|
|
}
|
|
|
|
// bearerToken extracts the token from an "Authorization: Bearer <token>" header,
|
|
// tolerating a bare token for convenience.
|
|
func bearerToken(header string) string {
|
|
header = strings.TrimSpace(header)
|
|
if header == "" {
|
|
return ""
|
|
}
|
|
if rest, ok := strings.CutPrefix(header, "Bearer "); ok {
|
|
return strings.TrimSpace(rest)
|
|
}
|
|
return header
|
|
}
|
|
|
|
// peerIP prefers the X-Forwarded-For client hop, falling back to the connection
|
|
// peer address (host part).
|
|
func peerIP(peerAddr string, h http.Header) string {
|
|
if xff := h.Get("X-Forwarded-For"); xff != "" {
|
|
if i := strings.IndexByte(xff, ','); i >= 0 {
|
|
return strings.TrimSpace(xff[:i])
|
|
}
|
|
return strings.TrimSpace(xff)
|
|
}
|
|
if host, _, err := net.SplitHostPort(peerAddr); err == nil {
|
|
return host
|
|
}
|
|
return peerAddr
|
|
}
|