Subscribe to the board

Rosie must see the board after Bob's move. The generated SDK has a SubscribeTo method for each exported query. The first result of a subscription is the current result. Commits that change a field that the query reads cause the subscription to prepare a new complete result.

The subscription keeps only the newest unread result. If several moves commit before the program reads again, it receives one result for those moves: the newest board.

The board query reads the square field of each piece, and each move writes that field. Thus the subscription keeps Rosie's board current. This step adds no definitions, because SubscribeToBoard is already in the SDK.

Create subscribe/main.go with this program. It subscribes to board, and a goroutine prints the square numbers of each result. The goroutine stops when a piece is on square 23. The main program moves the Black piece from 27 to 23 and then waits for the goroutine to stop.

go1.2 kB
package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"example.com/checkers/sdk"
)

func main() {
	db, err := sdk.Open(sdk.Config{Plugins: &sdk.Plugins{
		Stdlib:   true,
		Database: &sdk.DatabaseSettings{Path: "checkers.db"},
	}})
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := db.Close(); err != nil {
			log.Print(err)
		}
	}()
	sub, err := db.CheckersBoards.SubscribeToBoard()
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := sub.Close(); err != nil {
			log.Print(err)
		}
	}()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for event, err := range sub.Events(ctx) {
			if err != nil {
				log.Print(err)
				return
			}
			squares := ""
			moved := false
			for i := range event.Result {
				squares += fmt.Sprintf(" %d", event.Result[i].Number)
				moved = moved || event.Result[i].Number == 23
			}
			fmt.Printf("board:%s\n", squares)
			if moved {
				return
			}
		}
	}()

	// Black moves from 27 to 23.
	result, err := db.CheckersBoards.Move(27, 23)
	if err != nil {
		log.Fatal(err)
	}
	if result.Transaction == nil {
		log.Fatal("27-23: rejected")
	}
	wg.Wait()
}

Run go run ./subscribe. It prints:

text37 B
board: 15 18 27 32
board: 15 18 23 32

The first line is the board before Bob's move, and the second line is the board after it. When the first result includes the move, the program prints only the second line.

Only one process can have the database file open at a time. Here that process subscribes and also makes Bob's move, so one program shows both sides of the game.