Stage 8: UI social/account/history surfaces
Tests · Go / test (push) Successful in 7s
Tests · Integration / integration (push) Successful in 13s
Tests · UI / test (push) Successful in 16s

Wire the deferred Stage 7 surfaces end-to-end (UI -> gateway transcode ->
backend REST -> existing domain services): friends (incl. one-time friend
codes), per-user blocks, friend-game invitations, profile editing + email
binding, the statistics screen, and the in-game history + GCG export.

Friends gain two add paths (interview decision, a deliberate plan change):
one-time 6-digit codes (friend_codes table, 12h TTL, single-use, rate-limited
redeem); and play-gated requests (shared game required) where an explicit
decline is permanent, an ignored request lapses after 30 days, and a code
bypasses a decline. Migration 00006 widens friendships_status_chk and adds
friend_codes.

Lobby notification badge is poll + push: a new generic `notify` event drives
it live; the client polls on open/focus. Language stays a single Settings
control that writes through to the durable account's preferred_language. GCG
export is finished-only (game.ErrGameActive) and shares/downloads the .gcg file.

Tests: backend unit + inttest (friend gate/decline/code, ListInvitations,
GetStats, GCG gate), gateway transcode round-trips + notify constructor, UI
vitest (codecs, win-rate, share choice) + Playwright social specs. Docs: PLAN
(Stage 8 done + refinements + TODO-5), ARCHITECTURE, FUNCTIONAL(+ru), UI_DESIGN,
TESTING, module READMEs.
This commit is contained in:
Ilia Denisov
2026-06-03 19:47:40 +02:00
parent 539e24fba1
commit d733ce3119
114 changed files with 8210 additions and 149 deletions
+4
View File
@@ -43,6 +43,8 @@ func encodeProfile(p backendclient.ProfileResp) []byte {
name := b.CreateString(p.DisplayName)
lang := b.CreateString(p.PreferredLanguage)
tz := b.CreateString(p.TimeZone)
awayStart := b.CreateString(p.AwayStart)
awayEnd := b.CreateString(p.AwayEnd)
fb.ProfileStart(b)
fb.ProfileAddUserId(b, uid)
fb.ProfileAddDisplayName(b, name)
@@ -52,6 +54,8 @@ func encodeProfile(p backendclient.ProfileResp) []byte {
fb.ProfileAddBlockChat(b, p.BlockChat)
fb.ProfileAddBlockFriendRequests(b, p.BlockFriendRequests)
fb.ProfileAddIsGuest(b, p.IsGuest)
fb.ProfileAddAwayStart(b, awayStart)
fb.ProfileAddAwayEnd(b, awayEnd)
b.Finish(fb.ProfileEnd(b))
return b.FinishedBytes()
}
+179
View File
@@ -0,0 +1,179 @@
package transcode
import (
flatbuffers "github.com/google/flatbuffers/go"
"scrabble/gateway/internal/backendclient"
fb "scrabble/pkg/fbs/scrabblefb"
)
// Stage 8 encoders: friends, blocks, invitations, statistics and GCG. They follow
// encode.go's bottom-up rule (build every string/child vector before the table).
// buildAccountRef builds an AccountRef table and returns its offset.
func buildAccountRef(b *flatbuffers.Builder, r backendclient.AccountRefResp) flatbuffers.UOffsetT {
id := b.CreateString(r.AccountID)
name := b.CreateString(r.DisplayName)
fb.AccountRefStart(b)
fb.AccountRefAddAccountId(b, id)
fb.AccountRefAddDisplayName(b, name)
return fb.AccountRefEnd(b)
}
// buildAccountRefVector builds a [AccountRef] vector using the table-specific
// StartXVector function and returns the vector offset.
func buildAccountRefVector(b *flatbuffers.Builder, refs []backendclient.AccountRefResp, start func(*flatbuffers.Builder, int) flatbuffers.UOffsetT) flatbuffers.UOffsetT {
offs := make([]flatbuffers.UOffsetT, len(refs))
for i, r := range refs {
offs[i] = buildAccountRef(b, r)
}
start(b, len(offs))
for i := len(offs) - 1; i >= 0; i-- {
b.PrependUOffsetT(offs[i])
}
return b.EndVector(len(offs))
}
// encodeFriendList builds a FriendList payload.
func encodeFriendList(r backendclient.FriendListResp) []byte {
b := flatbuffers.NewBuilder(256)
v := buildAccountRefVector(b, r.Friends, fb.FriendListStartFriendsVector)
fb.FriendListStart(b)
fb.FriendListAddFriends(b, v)
b.Finish(fb.FriendListEnd(b))
return b.FinishedBytes()
}
// encodeIncomingList builds an IncomingRequestList payload.
func encodeIncomingList(r backendclient.IncomingListResp) []byte {
b := flatbuffers.NewBuilder(256)
v := buildAccountRefVector(b, r.Requests, fb.IncomingRequestListStartRequestsVector)
fb.IncomingRequestListStart(b)
fb.IncomingRequestListAddRequests(b, v)
b.Finish(fb.IncomingRequestListEnd(b))
return b.FinishedBytes()
}
// encodeBlockList builds a BlockList payload.
func encodeBlockList(r backendclient.BlockListResp) []byte {
b := flatbuffers.NewBuilder(256)
v := buildAccountRefVector(b, r.Blocked, fb.BlockListStartBlockedVector)
fb.BlockListStart(b)
fb.BlockListAddBlocked(b, v)
b.Finish(fb.BlockListEnd(b))
return b.FinishedBytes()
}
// encodeFriendCode builds a FriendCode payload.
func encodeFriendCode(r backendclient.FriendCodeResp) []byte {
b := flatbuffers.NewBuilder(64)
code := b.CreateString(r.Code)
fb.FriendCodeStart(b)
fb.FriendCodeAddCode(b, code)
fb.FriendCodeAddExpiresAtUnix(b, r.ExpiresAtUnix)
b.Finish(fb.FriendCodeEnd(b))
return b.FinishedBytes()
}
// encodeRedeemResult builds a RedeemResult payload.
func encodeRedeemResult(r backendclient.RedeemResultResp) []byte {
b := flatbuffers.NewBuilder(128)
friend := buildAccountRef(b, r.Friend)
fb.RedeemResultStart(b)
fb.RedeemResultAddFriend(b, friend)
b.Finish(fb.RedeemResultEnd(b))
return b.FinishedBytes()
}
// encodeStats builds a StatsView payload.
func encodeStats(r backendclient.StatsResp) []byte {
b := flatbuffers.NewBuilder(64)
fb.StatsViewStart(b)
fb.StatsViewAddWins(b, int32(r.Wins))
fb.StatsViewAddLosses(b, int32(r.Losses))
fb.StatsViewAddDraws(b, int32(r.Draws))
fb.StatsViewAddMaxGamePoints(b, int32(r.MaxGamePoints))
fb.StatsViewAddMaxWordPoints(b, int32(r.MaxWordPoints))
b.Finish(fb.StatsViewEnd(b))
return b.FinishedBytes()
}
// buildInvitation builds an Invitation table and returns its offset.
func buildInvitation(b *flatbuffers.Builder, inv backendclient.InvitationResp) flatbuffers.UOffsetT {
inviteeOffs := make([]flatbuffers.UOffsetT, len(inv.Invitees))
for i, iv := range inv.Invitees {
aid := b.CreateString(iv.AccountID)
name := b.CreateString(iv.DisplayName)
resp := b.CreateString(iv.Response)
fb.InvitationInviteeStart(b)
fb.InvitationInviteeAddAccountId(b, aid)
fb.InvitationInviteeAddDisplayName(b, name)
fb.InvitationInviteeAddSeat(b, int32(iv.Seat))
fb.InvitationInviteeAddResponse(b, resp)
inviteeOffs[i] = fb.InvitationInviteeEnd(b)
}
fb.InvitationStartInviteesVector(b, len(inviteeOffs))
for i := len(inviteeOffs) - 1; i >= 0; i-- {
b.PrependUOffsetT(inviteeOffs[i])
}
invitees := b.EndVector(len(inviteeOffs))
inviter := buildAccountRef(b, inv.Inviter)
id := b.CreateString(inv.ID)
variant := b.CreateString(inv.Variant)
dropout := b.CreateString(inv.DropoutTiles)
status := b.CreateString(inv.Status)
gameID := b.CreateString(inv.GameID)
fb.InvitationStart(b)
fb.InvitationAddId(b, id)
fb.InvitationAddInviter(b, inviter)
fb.InvitationAddInvitees(b, invitees)
fb.InvitationAddVariant(b, variant)
fb.InvitationAddTurnTimeoutSecs(b, int32(inv.TurnTimeoutSecs))
fb.InvitationAddHintsAllowed(b, inv.HintsAllowed)
fb.InvitationAddHintsPerPlayer(b, int32(inv.HintsPerPlayer))
fb.InvitationAddDropoutTiles(b, dropout)
fb.InvitationAddStatus(b, status)
fb.InvitationAddGameId(b, gameID)
fb.InvitationAddExpiresAtUnix(b, inv.ExpiresAtUnix)
return fb.InvitationEnd(b)
}
// encodeInvitation builds an Invitation payload.
func encodeInvitation(inv backendclient.InvitationResp) []byte {
b := flatbuffers.NewBuilder(512)
b.Finish(buildInvitation(b, inv))
return b.FinishedBytes()
}
// encodeInvitationList builds an InvitationList payload.
func encodeInvitationList(r backendclient.InvitationListResp) []byte {
b := flatbuffers.NewBuilder(1024)
offs := make([]flatbuffers.UOffsetT, len(r.Invitations))
for i, inv := range r.Invitations {
offs[i] = buildInvitation(b, inv)
}
fb.InvitationListStartInvitationsVector(b, len(offs))
for i := len(offs) - 1; i >= 0; i-- {
b.PrependUOffsetT(offs[i])
}
v := b.EndVector(len(offs))
fb.InvitationListStart(b)
fb.InvitationListAddInvitations(b, v)
b.Finish(fb.InvitationListEnd(b))
return b.FinishedBytes()
}
// encodeGcg builds a GcgExport payload.
func encodeGcg(r backendclient.GcgResp) []byte {
b := flatbuffers.NewBuilder(1024)
gid := b.CreateString(r.GameID)
fn := b.CreateString(r.Filename)
content := b.CreateString(r.Content)
fb.GcgExportStart(b)
fb.GcgExportAddGameId(b, gid)
fb.GcgExportAddFilename(b, fn)
fb.GcgExportAddContent(b, content)
b.Finish(fb.GcgExportEnd(b))
return b.FinishedBytes()
}
+1
View File
@@ -91,6 +91,7 @@ func NewRegistry(backend *backendclient.Client, tg auth.TelegramValidator) *Regi
r.ops[MsgGameHistory] = Op{Handler: historyHandler(backend), Auth: true}
r.ops[MsgChatList] = Op{Handler: chatListHandler(backend), Auth: true}
r.ops[MsgChatNudge] = Op{Handler: nudgeHandler(backend), Auth: true}
registerStage8(r, backend)
return r
}
@@ -0,0 +1,302 @@
package transcode
import (
"context"
"scrabble/gateway/internal/backendclient"
fb "scrabble/pkg/fbs/scrabblefb"
)
// Stage 8 message types: friends (incl. the one-time code path), per-user blocks,
// friend-game invitations, profile editing + email binding, statistics and GCG
// export. All are authenticated. Registered by registerStage8 from NewRegistry.
const (
MsgFriendsList = "friends.list"
MsgFriendsIncoming = "friends.incoming"
MsgFriendRequest = "friends.request"
MsgFriendRespond = "friends.respond"
MsgFriendCancel = "friends.cancel"
MsgFriendUnfriend = "friends.unfriend"
MsgFriendCodeIssue = "friends.code.issue"
MsgFriendCodeRedeem = "friends.code.redeem"
MsgBlocksList = "blocks.list"
MsgBlockAdd = "blocks.add"
MsgBlockRemove = "blocks.remove"
MsgInvitationsList = "invitation.list"
MsgInvitationCreate = "invitation.create"
MsgInvitationAccept = "invitation.accept"
MsgInvitationDecline = "invitation.decline"
MsgInvitationCancel = "invitation.cancel"
MsgProfileUpdate = "profile.update"
MsgEmailBindReq = "email.bind.request"
MsgEmailBindConfirm = "email.bind.confirm"
MsgStatsGet = "stats.get"
MsgGameGCG = "game.gcg"
)
// registerStage8 adds the Stage 8 social, account and history operations to the
// registry (all authenticated; the email-bind ops carry the costly-email flag).
func registerStage8(r *Registry, backend *backendclient.Client) {
r.ops[MsgFriendsList] = Op{Handler: friendsListHandler(backend), Auth: true}
r.ops[MsgFriendsIncoming] = Op{Handler: friendsIncomingHandler(backend), Auth: true}
r.ops[MsgFriendRequest] = Op{Handler: friendRequestHandler(backend), Auth: true}
r.ops[MsgFriendRespond] = Op{Handler: friendRespondHandler(backend), Auth: true}
r.ops[MsgFriendCancel] = Op{Handler: friendCancelHandler(backend), Auth: true}
r.ops[MsgFriendUnfriend] = Op{Handler: friendUnfriendHandler(backend), Auth: true}
r.ops[MsgFriendCodeIssue] = Op{Handler: friendCodeIssueHandler(backend), Auth: true}
r.ops[MsgFriendCodeRedeem] = Op{Handler: friendCodeRedeemHandler(backend), Auth: true}
r.ops[MsgBlocksList] = Op{Handler: blocksListHandler(backend), Auth: true}
r.ops[MsgBlockAdd] = Op{Handler: blockAddHandler(backend), Auth: true}
r.ops[MsgBlockRemove] = Op{Handler: blockRemoveHandler(backend), Auth: true}
r.ops[MsgInvitationsList] = Op{Handler: invitationsListHandler(backend), Auth: true}
r.ops[MsgInvitationCreate] = Op{Handler: invitationCreateHandler(backend), Auth: true}
r.ops[MsgInvitationAccept] = Op{Handler: invitationRespondHandler(backend, true), Auth: true}
r.ops[MsgInvitationDecline] = Op{Handler: invitationRespondHandler(backend, false), Auth: true}
r.ops[MsgInvitationCancel] = Op{Handler: invitationCancelHandler(backend), Auth: true}
r.ops[MsgProfileUpdate] = Op{Handler: profileUpdateHandler(backend), Auth: true}
r.ops[MsgEmailBindReq] = Op{Handler: emailBindRequestHandler(backend), Auth: true, Email: true}
r.ops[MsgEmailBindConfirm] = Op{Handler: emailBindConfirmHandler(backend), Auth: true, Email: true}
r.ops[MsgStatsGet] = Op{Handler: statsHandler(backend), Auth: true}
r.ops[MsgGameGCG] = Op{Handler: gcgHandler(backend), Auth: true}
}
// --- friends ---
func friendsListHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.ListFriends(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeFriendList(res), nil
}
}
func friendsIncomingHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.ListIncoming(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeIncomingList(res), nil
}
}
func friendRequestHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsTargetRequest(req.Payload, 0)
if err := backend.SendFriendRequest(ctx, req.UserID, string(in.AccountId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func friendRespondHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsFriendRespondRequest(req.Payload, 0)
if err := backend.RespondFriendRequest(ctx, req.UserID, string(in.RequesterId()), in.Accept()); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func friendCancelHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsTargetRequest(req.Payload, 0)
if err := backend.CancelFriendRequest(ctx, req.UserID, string(in.AccountId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func friendUnfriendHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsTargetRequest(req.Payload, 0)
if err := backend.Unfriend(ctx, req.UserID, string(in.AccountId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func friendCodeIssueHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.IssueFriendCode(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeFriendCode(res), nil
}
}
func friendCodeRedeemHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsRedeemCodeRequest(req.Payload, 0)
res, err := backend.RedeemFriendCode(ctx, req.UserID, string(in.Code()))
if err != nil {
return nil, err
}
return encodeRedeemResult(res), nil
}
}
// --- blocks ---
func blocksListHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.ListBlocks(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeBlockList(res), nil
}
}
func blockAddHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsTargetRequest(req.Payload, 0)
if err := backend.Block(ctx, req.UserID, string(in.AccountId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func blockRemoveHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsTargetRequest(req.Payload, 0)
if err := backend.Unblock(ctx, req.UserID, string(in.AccountId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
// --- invitations ---
func invitationsListHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.ListInvitations(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeInvitationList(res), nil
}
}
func invitationCreateHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsCreateInvitationRequest(req.Payload, 0)
params := backendclient.InvitationParams{
InviteeIDs: decodeInviteeIDs(in),
Variant: string(in.Variant()),
TurnTimeoutSecs: int(in.TurnTimeoutSecs()),
HintsAllowed: in.HintsAllowed(),
HintsPerPlayer: int(in.HintsPerPlayer()),
DropoutTiles: string(in.DropoutTiles()),
}
res, err := backend.CreateInvitation(ctx, req.UserID, params)
if err != nil {
return nil, err
}
return encodeInvitation(res), nil
}
}
func invitationRespondHandler(backend *backendclient.Client, accept bool) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsInvitationActionRequest(req.Payload, 0)
res, err := backend.RespondInvitation(ctx, req.UserID, string(in.InvitationId()), accept)
if err != nil {
return nil, err
}
return encodeInvitation(res), nil
}
}
func invitationCancelHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsInvitationActionRequest(req.Payload, 0)
if err := backend.CancelInvitation(ctx, req.UserID, string(in.InvitationId())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
// --- profile, email, stats, gcg ---
func profileUpdateHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsUpdateProfileRequest(req.Payload, 0)
p := backendclient.ProfileResp{
DisplayName: string(in.DisplayName()),
PreferredLanguage: string(in.PreferredLanguage()),
TimeZone: string(in.TimeZone()),
AwayStart: string(in.AwayStart()),
AwayEnd: string(in.AwayEnd()),
BlockChat: in.BlockChat(),
BlockFriendRequests: in.BlockFriendRequests(),
}
out, err := backend.UpdateProfile(ctx, req.UserID, p)
if err != nil {
return nil, err
}
return encodeProfile(out), nil
}
}
func emailBindRequestHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsEmailBindRequest(req.Payload, 0)
if err := backend.EmailBindRequest(ctx, req.UserID, string(in.Email())); err != nil {
return nil, err
}
return encodeAck(true), nil
}
}
func emailBindConfirmHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsEmailConfirmRequest(req.Payload, 0)
out, err := backend.EmailBindConfirm(ctx, req.UserID, string(in.Email()), string(in.Code()))
if err != nil {
return nil, err
}
return encodeProfile(out), nil
}
}
func statsHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
res, err := backend.Stats(ctx, req.UserID)
if err != nil {
return nil, err
}
return encodeStats(res), nil
}
}
func gcgHandler(backend *backendclient.Client) Handler {
return func(ctx context.Context, req Request) ([]byte, error) {
in := fb.GetRootAsGameActionRequest(req.Payload, 0)
res, err := backend.ExportGCG(ctx, req.UserID, string(in.GameId()))
if err != nil {
return nil, err
}
return encodeGcg(res), nil
}
}
// decodeInviteeIDs reads the invitee id vector from a CreateInvitationRequest.
func decodeInviteeIDs(in *fb.CreateInvitationRequest) []string {
n := in.InviteeIdsLength()
out := make([]string, 0, n)
for i := range n {
out = append(out, string(in.InviteeIds(i)))
}
return out
}
@@ -0,0 +1,238 @@
package transcode_test
import (
"context"
"net/http"
"testing"
flatbuffers "github.com/google/flatbuffers/go"
"scrabble/gateway/internal/transcode"
fb "scrabble/pkg/fbs/scrabblefb"
)
// targetPayload builds a TargetRequest payload (friend request/cancel, block).
func targetPayload(accountID string) []byte {
b := flatbuffers.NewBuilder(32)
id := b.CreateString(accountID)
fb.TargetRequestStart(b)
fb.TargetRequestAddAccountId(b, id)
b.Finish(fb.TargetRequestEnd(b))
return b.FinishedBytes()
}
func TestFriendsListRoundTripDecodesNames(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-User-ID"); got != "u-1" {
t.Errorf("X-User-ID = %q, want u-1", got)
}
if r.URL.Path != "/api/v1/user/friends" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"friends":[{"account_id":"a-1","display_name":"Ann"},{"account_id":"a-2","display_name":"Bob"}]}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, ok := reg.Lookup(transcode.MsgFriendsList)
if !ok {
t.Fatal("friends.list not registered")
}
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
if err != nil {
t.Fatalf("handler: %v", err)
}
fl := fb.GetRootAsFriendList(payload, 0)
if fl.FriendsLength() != 2 {
t.Fatalf("friends length = %d, want 2", fl.FriendsLength())
}
var f fb.AccountRef
fl.Friends(&f, 1)
if string(f.AccountId()) != "a-2" || string(f.DisplayName()) != "Bob" {
t.Fatalf("friend[1] = (%q, %q), want (a-2, Bob)", f.AccountId(), f.DisplayName())
}
}
func TestFriendRequestForwardsTarget(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-User-ID"); got != "u-1" {
t.Errorf("X-User-ID = %q, want u-1", got)
}
if r.URL.Path != "/api/v1/user/friends/request" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"ok":true}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgFriendRequest)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: targetPayload("b-1")})
if err != nil {
t.Fatalf("handler: %v", err)
}
if ack := fb.GetRootAsAck(payload, 0); !ack.Ok() {
t.Fatal("ack not ok")
}
}
func TestFriendCodeIssueAndRedeem(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/user/friends/code":
_, _ = w.Write([]byte(`{"code":"123456","expires_at_unix":1717000000}`))
case "/api/v1/user/friends/code/redeem":
_, _ = w.Write([]byte(`{"friend":{"account_id":"a-7","display_name":"Kaya"}}`))
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
issue, _ := reg.Lookup(transcode.MsgFriendCodeIssue)
p1, err := issue.Handler(context.Background(), transcode.Request{UserID: "u-1"})
if err != nil {
t.Fatalf("issue: %v", err)
}
fc := fb.GetRootAsFriendCode(p1, 0)
if string(fc.Code()) != "123456" || fc.ExpiresAtUnix() != 1717000000 {
t.Fatalf("friend code = (%q, %d)", fc.Code(), fc.ExpiresAtUnix())
}
b := flatbuffers.NewBuilder(32)
code := b.CreateString("123456")
fb.RedeemCodeRequestStart(b)
fb.RedeemCodeRequestAddCode(b, code)
b.Finish(fb.RedeemCodeRequestEnd(b))
redeem, _ := reg.Lookup(transcode.MsgFriendCodeRedeem)
p2, err := redeem.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: b.FinishedBytes()})
if err != nil {
t.Fatalf("redeem: %v", err)
}
rr := fb.GetRootAsRedeemResult(p2, 0)
if f := rr.Friend(nil); f == nil || string(f.AccountId()) != "a-7" || string(f.DisplayName()) != "Kaya" {
t.Fatalf("redeem friend decoded wrong: %+v", f)
}
}
func TestInvitationCreateRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/user/invitations" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"id":"i-1","inviter":{"account_id":"u-1","display_name":"Me"},"invitees":[{"account_id":"inv-1","display_name":"Friend","seat":1,"response":"pending"}],"variant":"english","turn_timeout_secs":86400,"hints_allowed":true,"hints_per_player":1,"dropout_tiles":"remove","status":"pending","expires_at_unix":42}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgInvitationCreate)
b := flatbuffers.NewBuilder(128)
inviteeID := b.CreateString("inv-1")
fb.CreateInvitationRequestStartInviteeIdsVector(b, 1)
b.PrependUOffsetT(inviteeID)
ids := b.EndVector(1)
variant := b.CreateString("english")
dropout := b.CreateString("remove")
fb.CreateInvitationRequestStart(b)
fb.CreateInvitationRequestAddInviteeIds(b, ids)
fb.CreateInvitationRequestAddVariant(b, variant)
fb.CreateInvitationRequestAddTurnTimeoutSecs(b, 86400)
fb.CreateInvitationRequestAddHintsAllowed(b, true)
fb.CreateInvitationRequestAddHintsPerPlayer(b, 1)
fb.CreateInvitationRequestAddDropoutTiles(b, dropout)
b.Finish(fb.CreateInvitationRequestEnd(b))
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: b.FinishedBytes()})
if err != nil {
t.Fatalf("handler: %v", err)
}
inv := fb.GetRootAsInvitation(payload, 0)
if string(inv.Id()) != "i-1" || inv.InviteesLength() != 1 || string(inv.Variant()) != "english" {
t.Fatalf("invitation decoded wrong: id=%q invitees=%d variant=%q", inv.Id(), inv.InviteesLength(), inv.Variant())
}
if iv := inv.Inviter(nil); iv == nil || string(iv.DisplayName()) != "Me" {
t.Fatalf("inviter decoded wrong: %+v", iv)
}
}
func TestStatsRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/user/stats" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"wins":5,"losses":3,"draws":1,"max_game_points":420,"max_word_points":90}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgStatsGet)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1"})
if err != nil {
t.Fatalf("handler: %v", err)
}
st := fb.GetRootAsStatsView(payload, 0)
if st.Wins() != 5 || st.Losses() != 3 || st.Draws() != 1 || st.MaxGamePoints() != 420 || st.MaxWordPoints() != 90 {
t.Fatalf("stats decoded wrong: %+v", st)
}
}
func TestGcgRoundTrip(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v1/user/games/g-1/gcg" {
t.Errorf("unexpected path %q", r.URL.Path)
}
_, _ = w.Write([]byte(`{"game_id":"g-1","filename":"game-g-1.gcg","content":"#character-encoding UTF-8\n"}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgGameGCG)
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: gameActionPayload("g-1")})
if err != nil {
t.Fatalf("handler: %v", err)
}
gcg := fb.GetRootAsGcgExport(payload, 0)
if string(gcg.Filename()) != "game-g-1.gcg" || len(gcg.Content()) == 0 {
t.Fatalf("gcg decoded wrong: filename=%q content=%q", gcg.Filename(), gcg.Content())
}
}
func TestProfileUpdateRoundTripAway(t *testing.T) {
backend, cleanup := fakeBackend(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut || r.URL.Path != "/api/v1/user/profile" {
t.Errorf("unexpected %s %q", r.Method, r.URL.Path)
}
_, _ = w.Write([]byte(`{"user_id":"u-1","display_name":"Kaya","preferred_language":"ru","time_zone":"Europe/Moscow","away_start":"00:00","away_end":"07:30"}`))
})
defer cleanup()
reg := transcode.NewRegistry(backend, nil)
op, _ := reg.Lookup(transcode.MsgProfileUpdate)
b := flatbuffers.NewBuilder(128)
name := b.CreateString("Kaya")
lang := b.CreateString("ru")
tz := b.CreateString("Europe/Moscow")
as := b.CreateString("00:00")
ae := b.CreateString("07:30")
fb.UpdateProfileRequestStart(b)
fb.UpdateProfileRequestAddDisplayName(b, name)
fb.UpdateProfileRequestAddPreferredLanguage(b, lang)
fb.UpdateProfileRequestAddTimeZone(b, tz)
fb.UpdateProfileRequestAddAwayStart(b, as)
fb.UpdateProfileRequestAddAwayEnd(b, ae)
b.Finish(fb.UpdateProfileRequestEnd(b))
payload, err := op.Handler(context.Background(), transcode.Request{UserID: "u-1", Payload: b.FinishedBytes()})
if err != nil {
t.Fatalf("handler: %v", err)
}
p := fb.GetRootAsProfile(payload, 0)
if string(p.AwayStart()) != "00:00" || string(p.AwayEnd()) != "07:30" || string(p.PreferredLanguage()) != "ru" {
t.Fatalf("profile away round-trip wrong: start=%q end=%q lang=%q", p.AwayStart(), p.AwayEnd(), p.PreferredLanguage())
}
}