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
+33 -3
View File
@@ -1,6 +1,8 @@
// Package account owns durable internal accounts and their platform/email
// identities. First contact from a platform auto-provisions an account bound to
// that identity; guests are session-only and never reach this package.
// that identity. An ephemeral guest is also a durable account row (the sessions
// and game_players foreign keys both require one) but carries no identity and is
// flagged is_guest, which excludes it from statistics, friends and history.
package account
import (
@@ -52,8 +54,11 @@ type Account struct {
HintBalance int
BlockChat bool
BlockFriendRequests bool
CreatedAt time.Time
UpdatedAt time.Time
// IsGuest marks an ephemeral guest account: a durable row with no identity,
// excluded from statistics, friends and history.
IsGuest bool
CreatedAt time.Time
UpdatedAt time.Time
}
// Store is the Postgres-backed query surface for accounts and identities.
@@ -176,6 +181,30 @@ func (s *Store) create(ctx context.Context, kind, externalID string) (Account, e
return created, nil
}
// guestDisplayName is the display name stamped on a freshly provisioned guest.
const guestDisplayName = "Guest"
// ProvisionGuest creates a fresh ephemeral guest account: a durable row carrying
// no identity, flagged is_guest, so it can hold a session and a game seat (both
// foreign-key the accounts table) while being excluded from statistics, friends
// and history. Guests are not reused — each bootstrap mints a new account.
func (s *Store) ProvisionGuest(ctx context.Context) (Account, error) {
accountID, err := uuid.NewV7()
if err != nil {
return Account{}, fmt.Errorf("account: new guest id: %w", err)
}
stmt := table.Accounts.
INSERT(table.Accounts.AccountID, table.Accounts.DisplayName, table.Accounts.IsGuest).
VALUES(accountID, guestDisplayName, true).
RETURNING(table.Accounts.AllColumns)
var row model.Accounts
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
return Account{}, fmt.Errorf("account: provision guest: %w", err)
}
return modelToAccount(row), nil
}
// SpendHint atomically decrements the account's hint wallet by one, returning
// true when a hint was spent and false when the balance was already empty. The
// guarded UPDATE keeps it safe under concurrent spends across the player's games.
@@ -210,6 +239,7 @@ func modelToAccount(row model.Accounts) Account {
HintBalance: int(row.HintBalance),
BlockChat: row.BlockChat,
BlockFriendRequests: row.BlockFriendRequests,
IsGuest: row.IsGuest,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
+94
View File
@@ -126,6 +126,72 @@ func (s *EmailService) ConfirmCode(ctx context.Context, accountID uuid.UUID, ema
return s.store.GetByID(ctx, accountID)
}
// RequestLoginCode issues a login confirm-code to the account that owns email,
// provisioning a fresh (unconfirmed) durable account when the email is new. It is
// the unauthenticated email-login entry point (Stage 6) and, unlike RequestCode,
// does not refuse an already-confirmed email — that is the ordinary returning-user
// login. The code is mailed to the address, so only its real owner can complete
// the login. It returns the target account id for the subsequent LoginWithCode.
func (s *EmailService) RequestLoginCode(ctx context.Context, email string) (uuid.UUID, error) {
addr, err := normalizeEmail(email)
if err != nil {
return uuid.UUID{}, err
}
acc, err := s.store.ProvisionByIdentity(ctx, KindEmail, addr)
if err != nil {
return uuid.UUID{}, err
}
code, hash, err := generateCode()
if err != nil {
return uuid.UUID{}, err
}
if err := s.store.replacePendingConfirmation(ctx, acc.ID, addr, hash, s.now().Add(emailCodeTTL)); err != nil {
return uuid.UUID{}, err
}
subject := "Your Scrabble login code"
body := fmt.Sprintf("Your login code is %s. It expires in %d minutes.", code, int(emailCodeTTL/time.Minute))
if err := s.mailer.Send(ctx, addr, subject, body); err != nil {
return uuid.UUID{}, err
}
return acc.ID, nil
}
// LoginWithCode verifies a login code for email and returns the owning account,
// marking the email identity confirmed on first success (idempotent for a
// returning user). It mirrors ConfirmCode's checks but updates the existing
// identity rather than inserting one, since RequestLoginCode already provisioned
// it. It returns ErrNotFound when no account owns the email.
func (s *EmailService) LoginWithCode(ctx context.Context, email, code string) (Account, error) {
addr, err := normalizeEmail(email)
if err != nil {
return Account{}, err
}
acc, err := s.store.findByIdentity(ctx, KindEmail, addr)
if err != nil {
return Account{}, err
}
conf, err := s.store.latestPendingConfirmation(ctx, acc.ID, addr)
if err != nil {
return Account{}, err
}
if s.now().After(conf.expiresAt) {
return Account{}, ErrCodeExpired
}
if conf.attempts >= emailCodeMaxAttempts {
return Account{}, ErrTooManyAttempts
}
if hashCode(code) != conf.codeHash {
if err := s.store.bumpConfirmationAttempts(ctx, conf.id); err != nil {
return Account{}, err
}
return Account{}, ErrCodeMismatch
}
if err := s.store.confirmEmailLogin(ctx, conf.id, acc.ID, addr, s.now()); err != nil {
return Account{}, err
}
return s.store.GetByID(ctx, acc.ID)
}
// emailConfirmation is a pending confirm-code row in domain form.
type emailConfirmation struct {
id uuid.UUID
@@ -252,6 +318,34 @@ func (s *Store) confirmEmailIdentity(ctx context.Context, confirmationID, accoun
return nil
}
// confirmEmailLogin consumes the login code and marks the existing email
// identity confirmed, inside one transaction. The identity already exists (a
// login provisioned it), so this updates rather than inserts and is idempotent
// for a returning user whose identity is already confirmed.
func (s *Store) confirmEmailLogin(ctx context.Context, confirmationID, accountID uuid.UUID, email string, now time.Time) error {
return withTx(ctx, s.db, func(tx *sql.Tx) error {
upd := table.EmailConfirmations.
UPDATE(table.EmailConfirmations.ConsumedAt).
SET(postgres.TimestampzT(now)).
WHERE(table.EmailConfirmations.ConfirmationID.EQ(postgres.UUID(confirmationID)))
if _, err := upd.ExecContext(ctx, tx); err != nil {
return fmt.Errorf("consume login code: %w", err)
}
confirm := table.Identities.
UPDATE(table.Identities.Confirmed).
SET(postgres.Bool(true)).
WHERE(
table.Identities.AccountID.EQ(postgres.UUID(accountID)).
AND(table.Identities.Kind.EQ(postgres.String(KindEmail))).
AND(table.Identities.ExternalID.EQ(postgres.String(email))),
)
if _, err := confirm.ExecContext(ctx, tx); err != nil {
return fmt.Errorf("confirm email identity: %w", err)
}
return nil
})
}
// normalizeEmail parses and lower-cases an email address, or returns ErrInvalidEmail.
func normalizeEmail(email string) (string, error) {
addr, err := mail.ParseAddress(strings.TrimSpace(email))