The node-engine's composed, running, wait-held and wait-ended make the have the hold compares with the wants; the healers' attempt-changed makes an attempt, dropped at its until on the keeper's own clock (a bound with its own time to live) or when removed. The manifest's reads are gone and its consumes gain the five events. Builds: design 47 G §541, §665, §556, §499, §434 Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
501 lines
17 KiB
Go
501 lines
17 KiB
Go
package main
|
|
|
|
// The keeper hears each observer's findings as events on the observer's own stream (design 47 G §383): it reads no
|
|
// observer's state. `finding-written` raises or changes the condition of its key, `finding-cleared` clears it. The
|
|
// observer and the node are the event's subject (its envelope's key and node); the bus's grants keep another account
|
|
// from publishing there, and the keeper refuses a body that names another observer.
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
broker "git.novox.be/novox/mesh-contracts/go/seats/meshbroker"
|
|
engine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
|
cc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
|
seat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
|
meshhealers "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhealers"
|
|
watchdogs "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs"
|
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
|
)
|
|
|
|
// The events an observer says on its stream (design 47 G §383).
|
|
const (
|
|
EventFindingWritten = "finding-written"
|
|
EventFindingCleared = "finding-cleared"
|
|
EventFindingsStated = "findings-stated"
|
|
)
|
|
|
|
// emitterOf is the module an event's envelope key `<module>.<event>` names.
|
|
func emitterOf(key, event string) (string, bool) {
|
|
m, ok := strings.CutSuffix(key, "."+event)
|
|
return m, ok && m != "" && !strings.Contains(m, ".")
|
|
}
|
|
|
|
// subjectOf reads the observer, the event and the node out of an event's key in either form of a part's finding stream
|
|
// (design 47 G §529): the old form `mesh.stream.<module>.event.<event>.<node>`, which the runtime delivers as
|
|
// `<module>.<event>.<node>` (or as `<module>.<event>` with the node in the envelope), and the template form
|
|
// `mesh.bus.<module>.finding-events.<event>.<node>`. The node of the key is the subject's alone; the envelope's is the
|
|
// fallback of a key without one.
|
|
func subjectOf(key, envelopeNode string) (module, event, node string, ok bool) {
|
|
parts := strings.Split(key, ".")
|
|
switch {
|
|
case len(parts) == 6 && parts[0] == "mesh" && parts[1] == "bus" && parts[3] == FindingEventsTemplate:
|
|
return parts[2], parts[4], parts[5], true
|
|
case len(parts) == 3:
|
|
return parts[0], parts[1], parts[2], true
|
|
case len(parts) == 2:
|
|
return parts[0], parts[1], envelopeNode, true
|
|
}
|
|
return "", "", "", false
|
|
}
|
|
|
|
// FindingEvent is one `finding-written` or `finding-cleared` heard from an observer on a node.
|
|
func (k *Keeper) FindingEvent(e stdio.Envelope) error {
|
|
if module, event, node, ok := subjectOf(e.Key, e.Node); ok {
|
|
switch event {
|
|
case EventFindingWritten:
|
|
return k.FindingWritten(module, node, e.Body)
|
|
case EventFindingCleared:
|
|
return k.FindingCleared(module, node, e.Body)
|
|
case EventFindingsStated:
|
|
return k.FindingsStated(module, node, e.Body)
|
|
}
|
|
}
|
|
if _, ok := emitterOf(e.Key, watchdogs.EventMachineAway); ok && strings.HasPrefix(e.Key, watchdogs.Seat+".") {
|
|
return k.MachinePresence(e.Body, true)
|
|
}
|
|
if _, ok := emitterOf(e.Key, watchdogs.EventMachineBack); ok && strings.HasPrefix(e.Key, watchdogs.Seat+".") {
|
|
return k.MachinePresence(e.Body, false)
|
|
}
|
|
if _, _, _, ok := engineKey(e.Key); ok {
|
|
return k.EngineEvent(e)
|
|
}
|
|
if strings.HasPrefix(e.Key, meshhealers.Seat+".attempt-changed.") {
|
|
return k.AttemptChanged(e.Key, e.Body)
|
|
}
|
|
if e.Key == broker.Seat+"."+broker.EventCreated {
|
|
return k.BrokerCreated(e.Body)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// FindingWritten raises or changes the condition of the finding an observer says on a node. A body that is not a finding
|
|
// the keeper can raise, or names another observer, is said in the journal and changes nothing.
|
|
func (k *Keeper) FindingWritten(observer, node string, body []byte) error {
|
|
k.mu.Lock()
|
|
k.init()
|
|
k.mu.Unlock()
|
|
if !k.isSource(observer) {
|
|
k.Logf("%s says finding-written on %s, and is no source of findings: left out", observer, node)
|
|
return nil
|
|
}
|
|
var f seat.Finding
|
|
if err := json.Unmarshal(body, &f); err != nil {
|
|
k.Logf("%s's finding-written on %s is not readable: %v", observer, node, err)
|
|
return nil
|
|
}
|
|
if f.Observer != observer {
|
|
k.Logf("%s's finding-written on %s names the observer %q: refused", observer, node, f.Observer)
|
|
return nil
|
|
}
|
|
if f.Scope != f.Subject.Scope || f.ID != f.Subject.ID {
|
|
k.Logf("%s's finding-written on %s names the scope %q and id %q, and its subject %q and %q: refused", observer, node,
|
|
f.Scope, f.ID, f.Subject.Scope, f.Subject.ID)
|
|
return nil
|
|
}
|
|
if !k.accepts(observer, node, f.At) {
|
|
k.Logf("%s's finding-written on %s is not its holder's, or is older than the holder's last statement: left out", observer, node)
|
|
return nil
|
|
}
|
|
return k.take(observer, node, f)
|
|
}
|
|
|
|
// take holds one finding an observer says on a node, and raises or changes its condition.
|
|
func (k *Keeper) take(observer, node string, f seat.Finding) error {
|
|
key, value, err := storedFinding(f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
k.mu.Lock()
|
|
k.init()
|
|
if k.keyNode[observer] == nil {
|
|
k.keyNode[observer] = map[string]string{}
|
|
}
|
|
k.keyNode[observer][key] = node
|
|
named := k.view(observer, node).Pending[key]
|
|
delete(k.view(observer, node).Pending, key)
|
|
k.mu.Unlock()
|
|
if !named.IsZero() {
|
|
_ = k.Store.Delete(BoundsState, pendingKey(observer, node, key))
|
|
}
|
|
k.saveView(observer, node)
|
|
return k.Finding(observer, key, value, false)
|
|
}
|
|
|
|
// FindingCleared clears the condition of the finding an observer no longer observes.
|
|
func (k *Keeper) FindingCleared(observer, node string, body []byte) error {
|
|
if !k.isSource(observer) {
|
|
k.Logf("%s says finding-cleared on %s, and is no source of findings: left out", observer, node)
|
|
return nil
|
|
}
|
|
var c seat.FindingCleared
|
|
if err := json.Unmarshal(body, &c); err != nil {
|
|
k.Logf("%s's finding-cleared on %s is not readable: %v", observer, node, err)
|
|
return nil
|
|
}
|
|
if !k.accepts(observer, node, c.At) {
|
|
k.Logf("%s's finding-cleared on %s is not its holder's, or is older than the holder's last statement: left out", observer, node)
|
|
return nil
|
|
}
|
|
k.mu.Lock()
|
|
k.init()
|
|
key := cc.Key(c.Scope, c.ID, c.Kind)
|
|
if _, ok := k.findings[observer][key]; !ok {
|
|
// A finding whose key ends in its ref rather than its kind.
|
|
for other, f := range k.findings[observer] {
|
|
if f.Subject.Scope == c.Scope && f.Subject.ID == c.ID && f.Kind == c.Kind {
|
|
key = other
|
|
}
|
|
}
|
|
}
|
|
k.mu.Unlock()
|
|
return k.Finding(observer, key, nil, true)
|
|
}
|
|
|
|
// storedFinding is the event's finding as the keeper holds one, with its key: the finding as the contract has it (design 47
|
|
// G §437, A-22), under the key its scope, id and ref or kind make.
|
|
func storedFinding(f seat.Finding) (string, []byte, error) {
|
|
if f.Evidence == nil {
|
|
f.Evidence = []seat.Evidence{}
|
|
}
|
|
if f.Since.IsZero() {
|
|
f.Since = f.At
|
|
}
|
|
value, err := json.Marshal(f)
|
|
return findingKey(f), value, err
|
|
}
|
|
|
|
// findingKey is the key a finding is held under: its scope, its id, and its ref where it has one, else its kind (ADR 0564).
|
|
func findingKey(f seat.Finding) string {
|
|
token := f.Ref
|
|
if token == "" {
|
|
token = f.Kind
|
|
}
|
|
return cc.Key(f.Scope, f.ID, token)
|
|
}
|
|
|
|
// MachinePresence takes the watchman's word that a machine is away or back (design 47 G §389): an observer on a machine
|
|
// away is not named in findings-unstated, and an ask is said again to the modules of a machine back.
|
|
func (k *Keeper) MachinePresence(body []byte, away bool) error {
|
|
var m struct {
|
|
Machine string `json:"machine"`
|
|
}
|
|
if err := json.Unmarshal(body, &m); err != nil || m.Machine == "" {
|
|
k.Logf("the watchman's word on a machine's presence is not readable: %v", err)
|
|
return nil
|
|
}
|
|
k.mu.Lock()
|
|
k.init()
|
|
if k.away == nil {
|
|
k.away = map[string]bool{}
|
|
}
|
|
if away {
|
|
k.away[m.Machine] = true
|
|
k.mu.Unlock()
|
|
return nil
|
|
}
|
|
delete(k.away, m.Machine)
|
|
var modules []string
|
|
for _, v := range k.views {
|
|
if v.node == m.Machine && v.observer != "" && !slices.Contains(modules, v.observer) {
|
|
modules = append(modules, v.observer)
|
|
}
|
|
}
|
|
k.mu.Unlock()
|
|
sort.Strings(modules)
|
|
var problems []string
|
|
for _, module := range modules {
|
|
if _, err := k.Ask(Module, module); err != nil {
|
|
problems = append(problems, err.Error())
|
|
}
|
|
}
|
|
if len(problems) > 0 {
|
|
return errors.New(strings.Join(problems, "; "))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// hear subscribes to the observers' events once the runtime serves, asked again until it takes each.
|
|
func hear(k *Keeper) {
|
|
patterns := []string{"*." + EventFindingWritten, "*." + EventFindingCleared, "*." + EventFindingsStated,
|
|
watchdogs.Seat + "." + watchdogs.EventMachineAway, watchdogs.Seat + "." + watchdogs.EventMachineBack,
|
|
engine.Seat + "." + engine.EventRunning, engine.Seat + "." + engine.EventComposed, engine.Seat + "." + engine.EventWaitHeld,
|
|
engine.Seat + "." + engine.EventWaitEnded, meshhealers.Seat + "." + meshhealers.EventAttemptChanged,
|
|
broker.Seat + "." + broker.EventCreated}
|
|
for _, pattern := range patterns {
|
|
go func() {
|
|
<-stdio.Served()
|
|
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
|
|
err := stdio.Subscribe(pattern, k.FindingEvent)
|
|
if err == nil {
|
|
return
|
|
}
|
|
logf("%s", fmt.Sprintf("%s is not heard yet (%v); asked again in %s", pattern, err, wait))
|
|
time.Sleep(wait)
|
|
}
|
|
}()
|
|
}
|
|
}
|
|
|
|
// pendingPrefix starts the keys of the state `bounds` that are a pending key's bound.
|
|
const pendingPrefix = "pending="
|
|
|
|
func pendingKey(observer, node, key string) string {
|
|
return pendingPrefix + observer + "=" + node + "=" + key
|
|
}
|
|
|
|
// notJudged is why a pending key that nothing named within its bound is cleared.
|
|
const notJudged = "not judged within its bound"
|
|
|
|
// sourceView is what the keeper heard of one observer on one node.
|
|
type sourceView struct {
|
|
observer, node string
|
|
// At is the last findings-stated's at; Pending are its pending keys with the end of their bound.
|
|
At time.Time
|
|
Pending map[string]time.Time
|
|
Findings []seat.Finding
|
|
// Sets are the last findings-stated's at of each set of kinds a statement covers (design 47 G §580), keyed by the kinds
|
|
// sorted and joined by a comma; the empty key is a statement with no kinds, which covers every kind.
|
|
Sets map[string]time.Time
|
|
// Asks are the asks it has not answered, with the end of their bound (asks.go).
|
|
Asks map[string]time.Time
|
|
// kept says the source is in the state `findings-views` (catalog.go).
|
|
kept bool
|
|
}
|
|
|
|
// view is the observer's view on the node, made when there is none. Called with mu held.
|
|
func (k *Keeper) view(observer, node string) *sourceView {
|
|
v := k.views[observer+"."+node]
|
|
if v == nil {
|
|
v = &sourceView{observer: observer, node: node, Pending: map[string]time.Time{}, Asks: map[string]time.Time{}}
|
|
k.views[observer+"."+node] = v
|
|
}
|
|
return v
|
|
}
|
|
|
|
// holderOf says whether an observer's events are taken from node alone, and so from which (design 47 G §384).
|
|
func (k *Keeper) holderOf(observer string) (string, bool) {
|
|
if k.Holder == nil {
|
|
return "", false
|
|
}
|
|
return k.Holder(observer)
|
|
}
|
|
|
|
// accepts says whether an event of the observer on the node, said at at, is taken: for an observer held once, only the
|
|
// holder's, and only with an at later than the holder's last statement, so an old holder's late event changes nothing.
|
|
func (k *Keeper) accepts(observer, node string, at time.Time) bool {
|
|
holder, once := k.holderOf(observer)
|
|
if !once {
|
|
return true
|
|
}
|
|
if node != holder {
|
|
return false
|
|
}
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
k.init()
|
|
v := k.views[observer+"."+node]
|
|
return v == nil || at.After(v.At)
|
|
}
|
|
|
|
// FindingsStated sets the keeper's view of an observer on a node to the set it states (design 47 G §384): what is new is
|
|
// raised, each pending key keeps its condition unchanged, and every other condition of the observer on the node (of every
|
|
// node, for an observer held once) is cleared.
|
|
func (k *Keeper) FindingsStated(observer, node string, body []byte) error {
|
|
if !k.isSource(observer) {
|
|
k.Logf("%s says findings-stated on %s, and is no source of findings: left out", observer, node)
|
|
return nil
|
|
}
|
|
var s seat.FindingsStated
|
|
if err := json.Unmarshal(body, &s); err != nil {
|
|
k.Logf("%s's findings-stated on %s is not readable: %v", observer, node, err)
|
|
return nil
|
|
}
|
|
for _, f := range s.Findings {
|
|
if f.Observer != observer || f.Scope != f.Subject.Scope || f.ID != f.Subject.ID {
|
|
k.Logf("%s's findings-stated on %s names the observer %q for %s.%s: refused", observer, node, f.Observer, f.Scope, f.ID)
|
|
return nil
|
|
}
|
|
}
|
|
holder, once := k.holderOf(observer)
|
|
if once && node != holder {
|
|
k.Logf("%s's findings-stated on %s is not its holder's (%s): left out", observer, node, holder)
|
|
return nil
|
|
}
|
|
now := k.Now().UTC()
|
|
k.mu.Lock()
|
|
k.init()
|
|
v := k.view(observer, node)
|
|
last := v.Sets[setOf(s.Kinds)]
|
|
if len(s.Kinds) == 0 && last.IsZero() {
|
|
last = v.At
|
|
}
|
|
if !last.IsZero() && !s.At.After(last) {
|
|
k.mu.Unlock()
|
|
k.Logf("%s's findings-stated on %s at %s is not newer than the one at %s: left out", observer, node, s.At, last)
|
|
return nil
|
|
}
|
|
covered := func(kind string) bool { return len(s.Kinds) == 0 || slices.Contains(s.Kinds, kind) }
|
|
v.At = later(v.At, s.At)
|
|
if v.Sets == nil {
|
|
v.Sets = map[string]time.Time{}
|
|
}
|
|
v.Sets[setOf(s.Kinds)] = s.At
|
|
// Only the kinds the statement covers are replaced: another bundle's findings and pending keys stand (§580).
|
|
kept := v.Findings[:0:0]
|
|
for _, f := range v.Findings {
|
|
if !covered(f.Kind) {
|
|
kept = append(kept, f)
|
|
}
|
|
}
|
|
v.Findings = append(kept, s.Findings...)
|
|
answered := v.Asks
|
|
v.Asks = map[string]time.Time{}
|
|
named := map[string]bool{}
|
|
for _, f := range s.Findings {
|
|
named[findingKey(f)] = true
|
|
}
|
|
oldPending := v.Pending
|
|
v.Pending = map[string]time.Time{}
|
|
for key, until := range oldPending {
|
|
if !covered(keyKind(key)) {
|
|
v.Pending[key] = until
|
|
}
|
|
}
|
|
type pend struct {
|
|
key string
|
|
deadline time.Time
|
|
}
|
|
var pending []pend
|
|
for _, p := range s.Pending {
|
|
bound, err := time.ParseDuration(p.Bound)
|
|
if err != nil {
|
|
bound = 0
|
|
}
|
|
named[p.Key] = true
|
|
v.Pending[p.Key] = s.At.Add(bound)
|
|
pending = append(pending, pend{p.Key, s.At.Add(bound)})
|
|
}
|
|
var drop []string
|
|
for key, f := range k.findings[observer] {
|
|
if !named[key] && covered(f.Kind) && (once || k.keyNode[observer][key] == node) {
|
|
drop = append(drop, key)
|
|
}
|
|
}
|
|
k.mu.Unlock()
|
|
for ask := range answered {
|
|
_ = k.Store.Delete(BoundsState, askedKey(observer, node, ask))
|
|
}
|
|
k.clearUnstated(observer, node)
|
|
k.saveView(observer, node)
|
|
sort.Strings(drop)
|
|
for key := range oldPending {
|
|
if _, still := v.Pending[key]; !still {
|
|
_ = k.Store.Delete(BoundsState, pendingKey(observer, node, key))
|
|
}
|
|
}
|
|
var problems []string
|
|
for _, f := range s.Findings {
|
|
if err := k.take(observer, node, f); err != nil {
|
|
problems = append(problems, err.Error())
|
|
}
|
|
}
|
|
why := "not stated when asked"
|
|
if s.Asked == "" {
|
|
why = "not stated at " + observer + "'s start"
|
|
}
|
|
for _, key := range drop {
|
|
k.mu.Lock()
|
|
k.whys[key] = why
|
|
k.mu.Unlock()
|
|
if err := k.Finding(observer, key, nil, true); err != nil {
|
|
problems = append(problems, err.Error())
|
|
}
|
|
k.mu.Lock()
|
|
delete(k.whys, key)
|
|
delete(k.keyNode[observer], key)
|
|
k.mu.Unlock()
|
|
}
|
|
for _, p := range pending {
|
|
_ = k.Store.Delete(BoundsState, pendingKey(observer, node, p.key))
|
|
ttl := p.deadline.Sub(now)
|
|
if ttl < time.Second {
|
|
if err := k.PendingPassed(pendingKey(observer, node, p.key)); err != nil {
|
|
problems = append(problems, err.Error())
|
|
}
|
|
continue
|
|
}
|
|
if err := k.Store.CreateTTL(BoundsState, pendingKey(observer, node, p.key), map[string]any{"observer": observer, "node": node,
|
|
"key": p.key, "until": p.deadline}, ttl); err != nil && !errors.Is(err, stdio.ErrChanged) {
|
|
problems = append(problems, err.Error())
|
|
}
|
|
}
|
|
if len(problems) > 0 {
|
|
return errors.New(strings.Join(problems, "; "))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// setOf is the key of a set of kinds: the kinds sorted and joined by a comma; none is the empty key, every kind.
|
|
func setOf(kinds []string) string {
|
|
sorted := slices.Clone(kinds)
|
|
sort.Strings(sorted)
|
|
return strings.Join(sorted, ",")
|
|
}
|
|
|
|
// keyKind is the last token of a finding's key, its kind (or its ref, §14 of ADR 0564).
|
|
func keyKind(key string) string {
|
|
if i := strings.LastIndex(key, "."); i >= 0 {
|
|
return key[i+1:]
|
|
}
|
|
return key
|
|
}
|
|
|
|
func later(a, b time.Time) time.Time {
|
|
if b.After(a) {
|
|
return b
|
|
}
|
|
return a
|
|
}
|
|
|
|
// PendingPassed is a pending key's bound passing: unless a finding or a later set named it since, its condition is cleared.
|
|
func (k *Keeper) PendingPassed(bound string) error {
|
|
rest := strings.TrimPrefix(bound, pendingPrefix)
|
|
observer, rest, ok1 := strings.Cut(rest, "=")
|
|
node, key, ok2 := strings.Cut(rest, "=")
|
|
if !ok1 || !ok2 {
|
|
return nil
|
|
}
|
|
k.mu.Lock()
|
|
k.init()
|
|
v := k.views[observer+"."+node]
|
|
if v == nil || v.Pending[key].IsZero() {
|
|
k.mu.Unlock()
|
|
return nil
|
|
}
|
|
delete(v.Pending, key)
|
|
k.whys[key] = notJudged
|
|
k.mu.Unlock()
|
|
err := k.Finding(observer, key, nil, true)
|
|
k.mu.Lock()
|
|
delete(k.whys, key)
|
|
delete(k.keyNode[observer], key)
|
|
k.mu.Unlock()
|
|
return err
|
|
}
|