Files
mesh-catalog/modules/mesh-conditions/cmd/mesh-conditions/main.go
T

228 lines
8.6 KiB
Go

// mesh-conditions: the condition keeper, holder of the seat mesh-conditions (novox/hq ADR 0564 clauses 1-3, 9, 13). A
// Go bundle served by a runtime of its own, on its own bus account (`runs-as`), so that its account alone writes its
// states: `conditions` (one key per open condition), `history` (every transition, ninety days), `takeover` (the key the
// readers follow), `held` and `bounds` (what a delivery holds, and for how long). It hears every observer's
// findings as events (design 47 G §383), watches the healers' `attempts`, the assigner's wants, the nodes' haves and the controller's lease and, until the
// lease write, its `conditions`; it says every transition on its seat with the controller's body. stdout is the MCP
// channel; what this module says, it says on stderr.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
seat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshwantsclient"
catseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
meshwants "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-sdk/go/views"
)
func logf(format string, a ...any) { fmt.Fprintf(os.Stderr, format+"\n", a...) }
// runtimeStore is the bus, through the runtime that launched this bundle.
type runtimeStore struct{}
func (runtimeStore) Get(state, key string) ([]byte, uint64, bool, error) {
e, err := stdio.State(state).Get(key)
if err != nil || e == nil {
return nil, 0, false, err
}
return e.Value, e.Revision, true, nil
}
func (runtimeStore) Create(state, key string, value any) (uint64, error) {
return stdio.State(state).Create(key, value)
}
func (runtimeStore) Update(state, key string, value any, revision uint64) (uint64, error) {
return stdio.State(state).Update(key, value, revision)
}
func (runtimeStore) Delete(state, key string) error { return stdio.State(state).Delete(key) }
func (runtimeStore) Keys(state string) ([]string, error) { return stdio.State(state).Keys() }
// CreateTTL creates the key with its own time to live (`bounds` is key-ttl); its expiry is handed over as OpExpire.
func (runtimeStore) CreateTTL(state, key string, value any, ttl time.Duration) error {
_, err := stdio.State(state).CreateTTL(key, value, ttl)
return err
}
// sayOnSeat says a transition on the seat, as the controller says it on its own (ADR 0564 clause 3).
func sayOnSeat(e Event) error {
return stdio.SeatPublish("mesh.seat."+Seat+".event."+e.Event, e.Said(), "")
}
// NewKeeper is the keeper over the runtime.
func NewKeeper() *Keeper {
k := &Keeper{Store: runtimeStore{}, Say: sayOnSeat, Now: time.Now, Logf: logf}
k.Holder = k.catalogHolder
return k
}
// watch keeps a watch of one state, said blind while it cannot be read: a state not on the bus yet (an observer not
// delivered) is read again when it is.
func watch(k *Keeper, v *views.Reader, state, observer string, handle func(stdio.StateChange) error) {
go func() {
for wait := 5 * time.Second; ; wait = min(wait*2, 5*time.Minute) {
var err error
if v.Follows(state) {
// The assigner's and the indexer's states are asked once of their read tools and followed by their events (ADR 0615).
err = v.Watch(state, func(key string, value []byte, gone bool) {
op := stdio.OpPut
if gone {
op = stdio.OpDelete
}
_ = handle(stdio.StateChange{Key: key, Value: value, Op: op})
})
} else {
err = stdio.State(state).Watch("", handle)
}
if err == nil {
if observer != "" {
k.Blind(observer, "")
}
return
}
if observer != "" {
k.Blind(observer, err.Error())
}
logf("%s cannot be watched (%v); watched again in %s", state, err, wait)
time.Sleep(wait)
}
}()
}
// Keep starts every watch the keeper reads by (clauses 2, 8, 9, 13).
func Keep(k *Keeper, v *views.Reader) {
for _, s := range []string{HeldState} {
keys, _ := stdio.State(s).Keys()
for _, key := range keys {
if e, err := stdio.State(s).Get(key); err == nil && e != nil {
k.restoreHeld(key, e.Value)
}
}
}
// The kept sources are heard at once, before the first view of the catalog half (design 47 G §388).
k.RestoreViews()
said := func(err error) error {
if err != nil {
logf("%v", err)
}
return nil
}
// Once at start: what was carried from the controller's bucket while it ran is cleared (issue 1126); nothing raises
// those kinds again.
if n, err := k.EndCarried(); n > 0 || err != nil {
logf("cleared %d condition(s) of kinds that ended with the controller: %v", n, err)
}
watch(k, v, WantsRead, "", func(c stdio.StateChange) error { return said(k.Want(c.Key, c.Value, c.Op != "put")) })
watch(k, v, HavesRead, "", func(c stdio.StateChange) error { return said(k.Have(c.Key, c.Value, c.Op != "put")) })
watch(k, v, AttemptsRead, healersModule+" attempts", func(c stdio.StateChange) error {
return said(k.Attempt(c.Key, c.Value, c.Op != "put"))
})
hear(k)
go func() { <-stdio.Served(); ListBound(k, stdio.Ask) }()
watch(k, v, BoundsState, "", func(c stdio.StateChange) error {
if c.Op == stdio.OpExpire {
return said(k.BoundPassed(c.Key))
}
return nil
})
watch(k, v, AssignmentsRead, "", func(c stdio.StateChange) error {
k.Assignments(c.Key, c.Value, c.Op != stdio.OpPut)
return nil
})
}
// The assigner's read tools of the states the keeper follows, which the manifest invokes (ADR 0615).
const (
WantsTool = assignerModule + ".assigner_read_wants"
AssignmentsTool = assignerModule + ".assigner_read_assignments"
)
// NewViews is the keeper's pictures of the assigner's wants and assignments (the findings come as events, design 47 G §383). A first view it cannot get past its
// bound is a finding of its own, taken in as any observer's: the keeper raises the condition itself.
func NewViews(k *Keeper) *views.Reader {
v := &views.Reader{Module: Module, Logf: logf, Findings: ownFindings{k}, Acts: meshhandactsclient.Recorder{Ask: stdio.Ask}}
v.Follow(assignerModule, "wants", WantsTool)
v.Follow(assignerModule, "assignments", AssignmentsTool)
// The newest assignment graph revision, which says where a module that stopped is placed no more (design 47 G §365).
if _, err := meshwantsclient.WireAssignment(v, stdio.Ask, func(rev meshwants.AssignmentRevision) { _ = k.AssignmentHeld(rev) }); err != nil {
logf("the assignment half is not followed: %v", err)
}
// One view of the catalog half per watched branch, the branches the registrations name, adopted and dropped while the
// keeper runs (design 47 G §365, §532).
branches := followCatalog(k, v, stdio.Ask)
var regs *meshcatalogclient.Registrations
regs, err := meshcatalogclient.WireRegistrations(v, stdio.Ask, func(catseat.Registration, bool) { branches.Watched(regs.All()) })
if err != nil {
logf("the registrations are not followed: %v", err)
}
return v
}
// ownFindings takes the keeper's own finding straight into its picture of findings. It is the WireWriter a views reader
// writes through (design 47 G §687, A-22): the finding's wire form, read as the contract's Finding, as an observer's is.
type ownFindings struct{ k *Keeper }
func (o ownFindings) WriteWire(_ context.Context, wire map[string]any) error {
raw, err := json.Marshal(wire)
if err != nil {
return err
}
var f seat.Finding
if err := json.Unmarshal(raw, &f); err != nil {
return fmt.Errorf("the keeper's own finding is not readable: %w", err)
}
f.Observer = Module
if f.At.IsZero() {
f.At = o.k.Now().UTC()
}
if f.Since.IsZero() {
f.Since = f.At
}
if f.Evidence == nil {
f.Evidence = []seat.Evidence{}
}
if err := views.CheckFinding(f); err != nil {
return err
}
key, value, err := storedFinding(f)
if err != nil {
return err
}
return o.k.Finding(Module, key, value, false)
}
func (o ownFindings) Clear(_ context.Context, scope, id, kind, _ string) error {
return o.k.Finding(Module, meshconditionsclient.Key(scope, id, kind), nil, true)
}
func (ownFindings) ModuleNode() (string, string) { return Module, "" }
func main() {
k := NewKeeper()
v := NewViews(k)
go func() {
<-stdio.Served()
// The bounds are settings, read at the start once the runtime serves (design 47 G §557).
v.Bound = ReadSettings(k, stdio.Config)
v.Start(context.Background())
Keep(k, v)
}()
if err := stdio.Serve("", append(Tools(k), v.Tools("mesh_conditions")...)); err != nil {
logf("%v", err)
os.Exit(1)
}
}