package game import ( "context" "slices" "testing" "time" "example.com/checkers/sdk" "stardust" ) const table = "checkers/boards" type choice struct { From int64 `json:"from"` Landing int64 `json:"landing"` } type candidate struct { Landing int64 `json:"landing"` Captures int64 `json:"captures"` } type piece struct { Number int64 `json:"number"` Color string `json:"color"` Rank string `json:"rank"` } // A failed assertion unwinds the test and closes its event streams. func must[T any](value T, err error) T { if err != nil { panic(err) } return value } func check(err error) { if err != nil { panic(err) } } func board(db *stardust.Database) []piece { return must(stardust.CallAs[[]piece](db, table, "board")) } // lesson:publish func publish(t *testing.T, ctx context.Context, db *stardust.Database) { type cursor struct { Player string `json:"player"` X float64 `json:"x"` Y float64 `json:"y"` } watch := must(stardust.SubscribeEvents[cursor](db, "checkers/table/cursor")) defer watch.Close() before := board(db) hand := cursor{"rosie", 6.2, 3.1} delivery := must(stardust.Publish(db, "checkers/table/cursor", hand)) event := must(watch.Next(ctx)) if delivery.Delivered != 1 || event.Data != hand || event.Dropped != 0 || !slices.Equal(board(db), before) { t.Fatal("cursor delivery changed or missed the position", delivery, event) } } // end:publish // lesson:request func request(t *testing.T, ctx context.Context, db *stardust.Database) { worker := must(stardust.Accept[choice](db, "request", "checkers/move")) defer worker.Close() board(db) // Wait for registration on the single request worker. move := choice{10, 7} for _, want := range []bool{true, false} { type response struct { committed bool err error } replies := make(chan response, 1) go func() { ok, err := stardust.CallEvent[bool](db, "checkers/move", move) replies <- response{ok, err} }() open := must(worker.Next(ctx)) input := open.Data result := must(stardust.CallAs[stardust.MutationResult](db, table, "move", input.From, input.Landing)) committed := result.Transaction != nil if committed { must(stardust.Publish(db, "checkers/table/turn", input.Landing)) must(stardust.Publish(db, "checkers/table/animate", []int64{10, 7})) } check(worker.Send(open.Handle, committed)) select { case reply := <-replies: check(reply.err) if reply.committed != want { t.Fatal("unexpected move reply", reply) } case <-ctx.Done(): t.Fatal(ctx.Err()) } } } // end:request // lesson:pull func pull(t *testing.T, ctx context.Context, db *stardust.Database) { worker := must(stardust.Accept[int64](db, "pull", "checkers/legal")) defer worker.Close() board(db) call := must(stardust.OpenExchange[candidate](ctx, db, "pull", "checkers/legal", int64(2))) defer call.Close() open := must(worker.Next(ctx)) for _, row := range must(stardust.CallAs[[]candidate](db, table, "king-jumps", open.Data)) { check(worker.Send(open.Handle, row)) } check(worker.Finish(open.Handle)) item := must(call.Next(ctx)) if item.Kind != "message" || item.Data != (candidate{11, 7}) { t.Fatal(item) } if must(call.Next(ctx)).Kind != "finish" || must(call.Next(ctx)).Kind != "complete" { t.Fatal("incomplete pull") } } // end:pull // lesson:push func push(t *testing.T, ctx context.Context, db *stardust.Database) { worker := must(stardust.Accept[choice](db, "push", "checkers/jump")) defer worker.Close() before := board(db) call := must(stardust.OpenExchange[bool](ctx, db, "push", "checkers/jump")) defer call.Close() open := must(worker.Next(ctx)) for _, square := range []int64{11, 18} { check(call.Send(choice{2, square})) } check(call.Finish()) var path []int64 for { step := must(worker.Next(ctx)) if step.Handle != open.Handle { t.Fatal("unexpected exchange", step) } if step.Kind == "finish" { break } if step.Kind != "message" || step.Data.From != 2 || len(path) >= 12 { check(worker.Cancel(open.Handle)) t.Fatal("invalid jump draft", step) } path = append(path, step.Data.Landing) if !slices.Equal(board(db), before) { t.Fatal("partial jump was committed") } } if len(path) != 2 { t.Fatal("this turn needs two landings", path) } // The first capture must roll back if the second landing is illegal. rejected := must(stardust.CallAs[stardust.MutationResult](db, table, "double-jump", 2, path[0], 19)) if rejected.Transaction != nil || !slices.Equal(board(db), before) { t.Fatal("invalid second landing changed the board") } result := must(stardust.CallAs[stardust.MutationResult](db, table, "double-jump", 2, path[0], path[1])) if result.Transaction == nil { t.Fatal("jump rejected") } must(stardust.Publish(db, "checkers/table/turn", path[1])) must(stardust.Publish(db, "checkers/table/animate", append([]int64{2}, path...))) check(worker.Send(open.Handle, true)) if !must(call.Next(ctx)).Data || must(call.Next(ctx)).Kind != "complete" { t.Fatal("incomplete push") } } // end:push // lesson:duplex func duplex(t *testing.T, ctx context.Context, db *stardust.Database) { worker := must(stardust.Accept[int64](db, "duplex", "checkers/drag")) defer worker.Close() before := board(db) call := must(stardust.OpenExchange[bool](ctx, db, "duplex", "checkers/drag")) defer call.Close() open := must(worker.Next(ctx)) for _, square := range []int64{11, 10, 18} { check(call.Send(square)) drag := must(worker.Next(ctx)) allowed := false for _, row := range must(stardust.CallAs[[]candidate](db, table, "king-jumps", 2)) { allowed = allowed || row.Landing == drag.Data } check(worker.Send(open.Handle, allowed)) preview := must(call.Next(ctx)) if preview.Kind != "message" || preview.Data != (square == 11) { t.Fatal(square, preview) } } check(call.Finish()) if must(worker.Next(ctx)).Kind != "finish" { t.Fatal("worker missed caller finish") } check(worker.Finish(open.Handle)) if must(call.Next(ctx)).Kind != "finish" || must(call.Next(ctx)).Kind != "complete" || !slices.Equal(board(db), before) { t.Fatal("drag changed the board or exchange did not finish") } } // end:duplex // lesson:recover func recoverBoard(t *testing.T, config stardust.Config) { reopened := must(sdk.Open(config)) defer reopened.Close() rows := must(reopened.CheckersBoards.Board()) if len(rows) != 1 { t.Fatal(rows) } b := rows[0] if b.Number != 18 || b.Rank != "king" || b.Color != "black" { t.Fatal("unexpected recovered board", b) } } // end:recover func TestGame(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() config := stardust.Config{Workers: 1, Plugins: &stardust.Plugins{ Stdlib: true, Events: true, Database: &stardust.DatabaseSettings{Path: "../checkers.db"}, }} func() { db := must(stardust.OpenConfig(config)) defer db.Close() // Continue from the crown lesson. Black reaches square 2 and becomes a king. for _, move := range [][2]int64{{24, 19}, {27, 23}, {19, 16}, {23, 18}, {16, 11}, {18, 14}, {11, 7}, {14, 10}, {7, 2}} { if must(stardust.CallAs[stardust.MutationResult](db, table, "move", move[0], move[1])).Transaction == nil { t.Fatalf("rejected move %v", move) } } publish(t, ctx, db) turns := must(stardust.SubscribeEvents[int64](db, "checkers/table/turn")) defer turns.Close() request(t, ctx, db) if must(turns.Next(ctx)).Data != 7 { t.Fatal("missing move notification") } pull(t, ctx, db) duplex(t, ctx, db) push(t, ctx, db) // Leave the final turn notification unread before closing the database. }() recoverBoard(t, config) }