Preview a drag with duplex

Before committing, Bob drags his king over 11, 10 and 18. For each square, the worker returns whether it is a legal first landing. Only 11 qualifies. The board stays unchanged while the two sides exchange previews and finish their streams.

Go example

go1.1 kB
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")
	}
}