Stream legal landings with pull

It is now Black's turn. Bob selects black1, and a pull exchange sends that one selection to the rules worker. The worker runs checkers/legal against the current revision and sends each candidate as a response message. It calls finish after the last candidate.

Bob reads until he receives kind: finish. The candidate for this position lands on 13 and captures red2. Bob collects candidates in a map keyed by landing square. The collection has no order, even though the transport delivers messages in sequence.

This fixture has one candidate for Black's first jump. A larger result can use the same send-and-finish pattern without changing the request. Treat the result as a preview of the queried revision. The commit mutation must still check the board because another turn could change it before Bob acts.

The streamed candidate is:

json58 B
{
  "landing": 13,
  "captures": {
    "red2": true
  }
}

Define the messages

The game data installs pull/checkers/legal in the events definition folder:

json583 B
{
  "request": {
    "type": "object",
    "required": [
      "piece"
    ],
    "additionalProperties": false,
    "properties": {
      "piece": {
        "type": "string"
      }
    }
  },
  "response": {
    "type": "object",
    "required": [
      "landing",
      "captures"
    ],
    "additionalProperties": false,
    "properties": {
      "landing": {
        "type": "integer",
        "minimum": 0,
        "maximum": 31
      },
      "captures": {
        "type": "object",
        "additionalProperties": {
          "type": "boolean"
        }
      }
    }
  }
}

The SDK plugin derives the payload types and route helpers from this definition. The Events plugin validates each message against its stored schema. The example below imports the generated SDK.

Code

go915 B
func listLegalMoves(game *Game, bob, rules *events.Owner) {
	worker, err := events.ServeCheckersLegal(rules)
	check(game.t, err)
	defer worker.Close()

	caller, err := events.OpenCheckersLegal(bob, events.CheckersLegalRequest{Piece: "black1"})
	check(game.t, err)

	exchange, err := worker.Accept(time.Second)
	check(game.t, err)

	movesToSend := game.legal(exchange.Request().Piece)
	for index := range movesToSend {
		move := movesToSend[index]
		check(game.t, exchange.Send(events.CheckersLegalResponse{
			Landing:  move.Landing,
			Captures: move.Captures,
		}))
	}
	check(game.t, exchange.Finish())

	moves := map[int64]map[string]any{}
	for {
		move, finished, err := caller.Read(time.Second)
		check(game.t, err)
		if finished {
			break
		}

		moves[move.Landing] = move.Captures
	}

	if !reflect.DeepEqual(moves, map[int64]map[string]any{13: {"red2": true}}) {
		game.t.Fatal("incorrect legal moves")
	}
}