Files
mesh-sdk/go/seatlist/holder.go
T

53 lines
2.1 KiB
Go

// Who holds a seat now (design 47 G A-126, beside the seat list): the module on record as the holder of a seat, asked of
// the seat that places modules (`mesh-module-assigner`) through its verb `assignments` with `seats` true, which answers the
// seat's holders. It is the one such reading: a module that reads a seat holder's state (a `reads` of `seat:<seat>.<state>`,
// A-116) and the asker of the operator (operatorask) call it, and no part keeps its own copy. It names the one seat and
// verb it asks, as this package names the seat that serves the seat list, and no module.
package seatlist
import (
"encoding/json"
"fmt"
)
const (
// HolderSeat is the seat whose verb answers who holds each seat.
HolderSeat = "mesh-module-assigner"
// HolderVerb is its verb, asked with `seats` true.
HolderVerb = "assignments"
)
// HolderCaller calls a seat verb or module tool as `seat:<seat>.<verb>` or `<module>.<tool>` and returns its answer (stdio.Ask is
// one; so is a process's calls).
type HolderCaller func(key string, body any) (json.RawMessage, error)
// HolderKey is the address asked, as stdio.Ask takes it; a host's manifest `invokes` lists it.
func HolderKey() string { return "seat:" + HolderSeat + "." + HolderVerb }
// HolderOf is the module holding the seat now: the first holder the seat's answer lists. It is an error while the answer cannot be
// read or no module holds the seat.
func HolderOf(call HolderCaller, seat string) (string, error) {
raw, err := call(HolderKey(), map[string]string{"seats": "true"})
if err != nil {
return "", fmt.Errorf("who holds the seat %s is not asked of %s: %w", seat, HolderKey(), err)
}
var held struct {
Seats []struct {
Seat string `json:"seat"`
Holders []struct {
Module string `json:"module"`
} `json:"holders"`
} `json:"seats"`
}
if err := json.Unmarshal(raw, &held); err != nil {
return "", fmt.Errorf("the answer of %s is not the seat holders': %w", HolderKey(), err)
}
for _, s := range held.Seats {
if s.Seat == seat && len(s.Holders) > 0 {
return s.Holders[0].Module, nil
}
}
return "", fmt.Errorf("no module holds the seat %s on record", seat)
}