Files
mesh-delivery/modules/mesh-delivery-indexer/internal/index/holds.go
T

564 lines
22 KiB
Go

package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"sort"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/process"
)
// The indexer's mesh-wide hold (novox/hq ADR 0632 §2, ADR 0624 §1). Every node-engine reads the store holder's manifest
// wherever the store runs, to find the store (mesh-host internal/compose/frombus), and an engine before the reading
// form:seat-reach finds it only through a module serving the retired provision artifact-store. A manifest that needs a
// reader capability read mesh-wide (MeshWideReads) is therefore not written to a module's entry in the modules state
// while some counted node-engine does not state it: the entry keeps its previous manifest, fingerprint and inputs, and
// the new one waits in the state holds, one key per module, until every counted node-engine states what it needs. Then
// it is written as its merge would have written it, judged and said. The assigner's hold of ADR 0614 §4 holds a want on
// one node; this one holds the entry itself, which every node reads.
//
// "Counted" is ADR 0624 §1's set: every node the assignments names, present or away, each read as its engine last stated
// through the node-engine seat's verb manifest-reads (a node with no statement read as the baseline; the indexer's state
// engine-reads, nodeengineclient/enginereads). Until the assignments is read no node is counted and every hold stays. The hold moves
// on the event manifest-reads-changed, the assignments's change, a person's ask again, and a merge; never on a timer.
const (
// HoldsState is the indexer's state of held entries: the bucket mesh-delivery-indexer_holds, keyed as the modules state.
HoldsState = "holds"
HoldsBucket = Module + "_" + HoldsState
// HoldsTool reads the holds, asks one again now, or moves one by a person's word.
HoldsTool = "indexer_holds"
// EngineReadsState is the indexer's state of what each counted node's engine states it reads (nodeengineclient/enginereads).
EngineReadsState = "engine-reads"
EngineReadsBucket = Module + "_" + EngineReadsState
// EngineReadsTool lists, asks again and drops those statements.
EngineReadsTool = "indexer_engine_reads"
)
// MeshWideReads are the reader capabilities whose need holds a module's new entry from the whole mesh, not only from the
// nodes it is placed on: form:seat-reach, which catalogue.ManifestNeeds marks for the store holder's own manifest (a
// claim of container-image-registry at the mesh's scope) and for a manifest naming a seat's reach (ADR 0632 §1, §2).
var MeshWideReads = []string{catalogue.ReadForm + catalogue.ReferenceFormSeatReach}
// A hold standing past HoldBound is the indexer's finding HoldStandingKind about its module, which the condition keeper
// raises (ADR 0564 §2): the module's new entry is delivered nowhere while it stands, and a counted node that is away for
// long (ADR 0624 §1) keeps it so. The finding names who lacks what; it is cleared when the hold moves or is dropped.
// The bound is a key of the indexer's state hold-bounds that expires at Since+HoldBound (a key's time to live on the
// bus, as the builder's bounds): its expiry weighs the holds again, which raises the finding, and a restarted indexer
// weighs every hold at its start, so a bound that ended while it was down is raised then. No timer runs.
const (
HoldStandingKind = "manifest-held"
HoldBound = 30 * time.Minute
HoldBoundsState = "hold-bounds"
HoldBoundsBucket = Module + "_" + HoldBoundsState
)
// Bounds is the state hold-bounds: Arm writes key to expire at ends, a standing key keeping its end; Disarm deletes it.
type Bounds interface {
Arm(ctx context.Context, key string, ends time.Time) error
Disarm(ctx context.Context, key string) error
}
// HoldVersion is the version of a holds value this indexer writes and reads.
const HoldVersion = 1
// Hold is one module's held entry: what the new manifest needs of MeshWideReads, which counted nodes lack which of it
// (or why no node is counted), the manifest the modules state keeps and the one held, the merge that brought it, since
// when, and the entry written once it moves.
type Hold struct {
V int `json:"v"`
Module string `json:"module"`
Needs []string `json:"needs"`
Lacking map[string][]string `json:"lacking,omitempty"`
Unknown string `json:"unknown,omitempty"`
Kept string `json:"kept"`
Manifest string `json:"manifest"`
Repository string `json:"repository"`
Commit string `json:"commit"`
Since time.Time `json:"since"`
Next json.RawMessage `json:"next"`
}
// EncodeHold is h at HoldVersion.
func EncodeHold(h Hold) ([]byte, error) {
if h.Module == "" || len(h.Next) == 0 {
return nil, errors.New("a hold names its module and the entry it holds")
}
h.V = HoldVersion
return json.Marshal(h)
}
// DecodeHold reads a holds value; it refuses another version and one holding no entry.
func DecodeHold(raw []byte) (Hold, error) {
var h Hold
if err := json.Unmarshal(raw, &h); err != nil {
return h, err
}
if h.V != HoldVersion {
return h, fmt.Errorf("a holds value of version %d, not %d", h.V, HoldVersion)
}
if h.Module == "" || len(h.Next) == 0 {
return h, errors.New("a holds value naming no module or no entry")
}
return h, nil
}
// meshWide is what of needs MeshWideReads names, sorted.
func meshWide(needs []string) []string {
var out []string
for _, n := range needs {
if slices.Contains(MeshWideReads, n) {
out = append(out, n)
}
}
sort.Strings(out)
return slices.Compact(out)
}
// noneCounted is why a hold stays while no node is counted.
const noneCounted = "no node is counted yet (the assignments is not read), so the hold stays until it is"
// lacking is, of the counted nodes, each whose engine lacks some of needs, with what it lacks; or why no node is counted.
func (ix *Indexer) lacking(needs []string) (map[string][]string, string) {
counted, known := ix.Counted()
if !known || len(counted) == 0 {
return nil, noneCounted
}
out := map[string][]string{}
for node, stated := range counted {
if miss := catalogue.MissingManifestReads(needs, stated); len(miss) > 0 {
out[node] = miss
}
}
if len(out) == 0 {
return nil, ""
}
return out, ""
}
// lackingWords says who lacks what, or why no node is counted.
func lackingWords(lacking map[string][]string, unknown string) string {
if unknown != "" {
return unknown
}
var parts []string
for _, node := range slices.Sorted(maps.Keys(lacking)) {
parts = append(parts, node+" lacks "+strings.Join(lacking[node], ", "))
}
return strings.Join(parts, "; ")
}
// holdBack decides, for one module of a merge, whether its new entry next waits (true: kept in the holds state, the
// modules state left at cur) or is written now (false: any hold of it dropped, the merge having moved it). It holds only
// a changed manifest of a module the modules state holds an entry of: a new module has no previous entry to keep, and is
// held on each node by the assigner (ADR 0614 §4). An error is a hold that could not be kept: the merge is left, and
// delivered again, rather than writing what a counted engine cannot read.
func (ix *Indexer) holdBack(ctx context.Context, key string, next, cur meshcatalog.ModulesByModuleValue, has bool) (bool, error) {
if ix.Holds == nil || ix.Counted == nil {
return false, nil
}
needs := meshWide(next.Needs)
var lacking map[string][]string
var unknown string
// Any change of the entry is held, not only a new manifest: a template's text that newly needs a reading changes
// the module's tree and needs while its manifest stays (ADR 0632 §2, docker's daemon file).
if len(needs) > 0 && has && cur.Manifest != "" && next.Manifest != "" && !sameButWhere(cur, next) {
lacking, unknown = ix.lacking(needs)
}
if len(lacking) == 0 && unknown == "" {
return false, ix.dropHold(ctx, key, "its merge "+next.Commit+" brought a manifest every counted node-engine reads")
}
raw, err := meshcatalogclient.EncodeModule(next)
if err != nil {
return false, err
}
h := Hold{Module: key, Needs: needs, Lacking: lacking, Unknown: unknown, Kept: cur.Manifest, Manifest: next.Manifest,
Repository: next.Repository, Commit: next.Commit, Since: ix.now().UTC(), Next: raw}
err = write(ctx, ix.Holds, key, func(value []byte, found bool) ([]byte, bool, error) {
h.Since, h.Next, h.Commit = ix.now().UTC(), raw, next.Commit
if found {
if old, err := DecodeHold(value); err == nil {
// The module is held since its first hold, whatever a later merge brings; the same entry held again keeps
// its first merge too, as a module's commit does (writeOverlay).
h.Since = old.Since
if old.Manifest == h.Manifest && sameHeld(old.Next, next) {
h.Next, h.Commit = old.Next, old.Commit
}
}
}
data, err := EncodeHold(h)
return data, false, err
})
if err != nil {
return false, fmt.Errorf("%s: its new manifest %s is held from the mesh, and the hold cannot be kept: %w", key, next.Manifest, err)
}
ix.logf("modules.%s keeps manifest %s: the new manifest %s of %s needs %s, which not every counted node-engine states (%s; ADR 0632 §2); it moves once each does",
key, cur.Manifest, next.Manifest, next.Commit, strings.Join(needs, ", "), lackingWords(lacking, unknown))
ix.holdStands(ctx, key, h)
return true, nil
}
// dropHold deletes the hold of key, if there is one, saying why.
func (ix *Indexer) dropHold(ctx context.Context, key, why string) error {
if ix.Holds == nil {
return nil
}
dropped := false
err := write(ctx, ix.Holds, key, func(_ []byte, found bool) ([]byte, bool, error) {
dropped = found
return nil, found, nil
})
if errors.Is(err, process.ErrNotYet) {
return nil // a holds state not on the bus yet holds nothing to drop
}
if err != nil {
return fmt.Errorf("holds.%s: %w", key, err)
}
if dropped {
ix.logf("holds.%s dropped: %s", key, why)
ix.holdEnds(ctx, key)
}
return nil
}
// KickHolds moves every hold whose needs every counted node-engine now states, in the background, once at a time: on a
// node's statement changed, the assignments's change and the holds state's binding.
func (ix *Indexer) KickHolds(ctx context.Context) {
if ix.Holds == nil || ix.Counted == nil {
return
}
if ix.holding.Swap(true) {
ix.holdAgain.Store(true)
return
}
go func() {
for {
ix.holdAgain.Store(false)
if err := ix.MoveHolds(ctx); err != nil {
ix.logf("moving the holds: %v", err)
}
if !ix.holdAgain.Load() {
ix.holding.Store(false)
if !ix.holdAgain.Load() || ix.holding.Swap(true) {
return
}
}
}
}()
}
// MoveHolds weighs every hold against what the counted node-engines state now: one every node reads is written, and
// one still held is kept with who lacks what now.
func (ix *Indexer) MoveHolds(ctx context.Context) error {
if ix.Holds == nil || ix.Counted == nil {
return nil
}
keys, err := ix.Holds.Keys(ctx)
if errors.Is(err, process.ErrNotYet) {
return nil // weighed once the state is bound (main.go)
}
if err != nil {
return fmt.Errorf("listing the holds: %w", err)
}
var errs []error
for _, key := range slices.Sorted(slices.Values(keys)) {
if _, _, err := ix.moveHold(ctx, key, ""); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// moveHold weighs one hold; with by, a person's word moves it whatever the engines state. It answers whether it moved,
// and what stands.
func (ix *Indexer) moveHold(ctx context.Context, key, by string) (bool, string, error) {
moved := false
for try := 0; try < writeTries; try++ {
value, rev, found, err := ix.Holds.Get(ctx, key)
if err != nil {
return moved, "", fmt.Errorf("holds.%s: %w", key, err)
}
if !found {
if moved {
return true, "moved", nil
}
return false, "no hold of " + key + " is kept", nil
}
h, err := DecodeHold(value)
if err != nil {
ix.logf("holds.%s holds what is not a hold, left: %v", key, err)
return moved, "", fmt.Errorf("holds.%s: %w", key, err)
}
next, err := meshcatalogclient.DecodeModule(h.Next)
if err != nil {
return moved, "", fmt.Errorf("holds.%s: its entry: %w", key, err)
}
lacking, unknown := ix.lacking(h.Needs)
if by == "" && (len(lacking) > 0 || unknown != "") {
if reflect.DeepEqual(lacking, h.Lacking) && unknown == h.Unknown {
ix.holdStands(ctx, key, h)
return false, lackingWords(lacking, unknown), nil
}
h.Lacking, h.Unknown = lacking, unknown
data, err := EncodeHold(h)
if err != nil {
return false, "", err
}
if err := ix.Holds.Update(ctx, key, data, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return false, "", fmt.Errorf("holds.%s: %w", key, err)
}
ix.holdStands(ctx, key, h)
return false, lackingWords(lacking, unknown), nil
}
ix.recompute.Lock()
// Under the lock a merge writes its modules by, read again: a merge since replaced or dropped the hold.
if _, now, still, err := ix.Holds.Get(ctx, key); err != nil || !still || now != rev {
ix.recompute.Unlock()
if err != nil {
return moved, "", fmt.Errorf("holds.%s: %w", key, err)
}
continue
}
curRaw, _, has, err := ix.Modules.Get(ctx, key)
if err != nil {
ix.recompute.Unlock()
return moved, "", fmt.Errorf("modules.%s: %w", key, err)
}
cur, derr := meshcatalogclient.DecodeModule(curRaw)
if !has || derr != nil || !trunk.SameRepository(cur.Repository, next.Repository) {
err := ix.Holds.Delete(ctx, key, rev)
ix.recompute.Unlock()
if errors.Is(err, ErrConflict) {
continue
}
if err == nil {
ix.holdEnds(ctx, key)
}
ix.logf("holds.%s dropped: the modules state no longer holds the module of %s", key, next.Repository)
return moved, "dropped: the modules state no longer holds the module of " + next.Repository, err
}
next.Src = int64(ix.srcOf(next.Repository, next.Commit))
w := &mergeWrite{repository: next.Repository, merge: next.Commit}
err = ix.recomputeLocked(ctx, map[string]meshcatalog.ModulesByModuleValue{key: next}, w)
if err == nil {
err = ix.Holds.Delete(ctx, key, rev)
}
ix.recompute.Unlock()
if errors.Is(err, ErrConflict) {
moved = true
continue // a merge held a newer manifest meanwhile: weighed in turn
}
if err != nil {
return moved, "", fmt.Errorf("moving the hold of %s: %w", key, err)
}
moved = true
ix.holdEnds(ctx, key)
why := "every counted node-engine states " + strings.Join(h.Needs, ", ")
if by != "" {
why = "moved by " + by + "'s word, " + stranded(lacking, unknown, h.Needs)
}
ix.logf("modules.%s moves from manifest %s to %s of %s, held since %s: %s", key, h.Kept, h.Manifest, h.Commit, h.Since.Format(time.RFC3339), why)
if err := ix.RecomputeCandidates(ctx); err != nil {
ix.logf("the candidates after the hold of %s moved: %v", key, err)
}
if ix.Verdicts != nil {
if _, err := ix.JudgeAll(ctx, w.fresh); err != nil {
ix.logf("judge: the manifests are not judged after the hold of %s moved: %v", key, err)
}
}
return true, why, nil
}
return moved, "", fmt.Errorf("holds.%s: it kept changing while it was weighed", key)
}
// sameHeld says a held entry is next but for where it came from: its first merge stands.
func sameHeld(held json.RawMessage, next meshcatalog.ModulesByModuleValue) bool {
prev, err := meshcatalogclient.DecodeModule(held)
return err == nil && sameButWhere(prev, next)
}
// holdStands keeps the finding of h standing: raised, naming who lacks what now, once h stood HoldBound; until then its
// bound is armed in the state hold-bounds, whose expiry weighs the holds again (HoldBoundEnded).
func (ix *Indexer) holdStands(ctx context.Context, key string, h Hold) {
if ends := h.Since.Add(HoldBound); ix.now().Before(ends) {
if ix.HoldBounds != nil {
if err := ix.HoldBounds.Arm(ctx, key, ends); err != nil {
ix.logf("hold-bounds.%s is not armed, so the hold standing past %s is raised at its next weighing only: %v", key, HoldBound, err)
}
}
return
}
ix.finding(ctx, findingID("hold", key), HoldStandingKind, true,
fmt.Sprintf("modules.%s keeps manifest %s since %s: its new manifest %s of %s needs %s, and %s",
key, h.Kept, h.Since.Format(time.RFC3339), h.Manifest, cmpOr(h.Commit, "its merge"), strings.Join(h.Needs, ", "), lackingWords(h.Lacking, h.Unknown)),
"A module's new manifest is held from the whole mesh",
"Every node-engine reads "+key+"'s manifest, and one counted node-engine does not yet state the reading the new one "+
"needs, so the indexer keeps the old entry and the new manifest is delivered nowhere (ADR 0632 §2). It moves by "+
"itself once each counted node's engine states it; an away node keeps it held until it is back. indexer_holds "+
"names who lacks what, asks again, or moves it by a person's word; indexer_engine_reads reads the statements.",
"The hold of "+key+" moved or was dropped.")
}
// HoldBoundEnded takes a key of the state hold-bounds that expired: the holds are weighed again, and the one it bounds,
// still standing, is raised.
func (ix *Indexer) HoldBoundEnded(ctx context.Context, key string) {
ix.logf("hold-bounds.%s ended: the holds are weighed again", key)
ix.KickHolds(ctx)
}
// holdEnds disarms the bound of key's hold and clears its finding.
func (ix *Indexer) holdEnds(ctx context.Context, key string) {
if ix.HoldBounds != nil {
if err := ix.HoldBounds.Disarm(ctx, key); err != nil {
ix.logf("hold-bounds.%s is not deleted; its end weighs the holds once more, which moves nothing: %v", key, err)
}
}
ix.finding(ctx, findingID("hold", key), HoldStandingKind, false, "", "", "", "")
}
// Strands is what moving h by a person's word strands now, as its hand act and its answer say it.
func Strands(h Hold) string { return stranded(h.Lacking, h.Unknown, h.Needs) }
// stranded says, of a hold moved by a person's word, the nodes it strands: each counted node whose engine lacks what
// the new entry needs reads it without it (an engine before form:seat-reach finds no store) until it states it.
func stranded(lacking map[string][]string, unknown string, needs []string) string {
switch {
case unknown != "":
return "while " + unknown + ": every node whose engine lacks " + strings.Join(needs, ", ") + " is stranded until it states it"
case len(lacking) == 0:
return "every counted node-engine stating " + strings.Join(needs, ", ") + ": it strands none"
}
return "and it strands " + strings.Join(slices.Sorted(maps.Keys(lacking)), ", ") + " (" + lackingWords(lacking, "") +
"): each reads the new entry without that reading until its engine states it, an away node from its return"
}
func cmpOr(a, b string) string {
if a != "" {
return a
}
return b
}
// HoldAgain answers a person's ask of one hold (the tool indexer_holds): again asks the engines of the counted nodes that
// lack what it needs once more and weighs it now; by moves it by that person's word, whatever the engines state.
func (ix *Indexer) HoldAgain(ctx context.Context, module string, release bool, by string) TakenIn {
r := TakenIn{Module: module}
key, err := meshcatalogclient.ModulesKey(module)
if err != nil {
r.Answer = err.Error()
return r
}
if ix.Holds == nil || ix.Counted == nil {
r.Answer = "the indexer keeps no holds: its holds state or the engines' statements are not bound"
return r
}
value, _, found, err := ix.Holds.Get(ctx, key)
switch {
case err != nil:
r.Answer = "the holds state cannot be read: " + err.Error()
return r
case !found:
r.Answer = "no hold of " + module + " is kept: its entry in the modules state is the newest manifest merged"
return r
}
h, err := DecodeHold(value)
if err != nil {
r.Answer = "its hold cannot be read: " + err.Error()
return r
}
r.Repository, r.Commit = h.Repository, h.Commit
if !release {
lacking, _ := ix.lacking(h.Needs)
if ix.AskEngines != nil && len(lacking) > 0 {
ix.AskEngines(slices.Sorted(maps.Keys(lacking)), "the hold of "+module+" asked again")
}
}
who := ""
if release {
who = cmpOr(by, "a person")
}
moved, words, err := ix.moveHold(ctx, key, who)
switch {
case err != nil:
r.Answer = "the hold was not weighed: " + err.Error()
case moved:
r.Stored = true
r.Answer = "moved: modules." + key + " now names manifest " + h.Manifest + " (" + words + ")"
default:
r.Held = true
r.Answer = "held at manifest " + h.Kept + ": " + words + "; the engines asked again answer in the background, and the hold moves once each states " + strings.Join(h.Needs, ", ")
}
return r
}
// ListHolds is every hold the state holds, by module, or one module's; a value that does not read is named with why.
func ListHolds(keys []string, get func(key string) ([]byte, error), module string) (map[string]any, error) {
if module != "" {
key, err := meshcatalogclient.ModulesKey(module)
if err != nil {
return nil, err
}
keys = []string{key}
}
holds, unread := map[string]Hold{}, map[string]string{}
for _, key := range slices.Sorted(slices.Values(keys)) {
raw, err := get(key)
if err != nil {
return nil, err
}
if raw == nil {
continue
}
h, err := DecodeHold(raw)
if err != nil {
unread[key] = err.Error()
continue
}
h.Next = nil // the entry whole is the modules state's form; its digest and commit say which
holds[key] = h
}
return map[string]any{"holds": holds, "unread": unread, "bound": "each hold standing " + HoldBound.String() +
" past its since is the finding " + HoldStandingKind + ", its end a key of the state " + HoldBoundsState}, nil
}
// NewHoldAgain is the takeins value indexer_holds writes to ask one module's hold again (release false) or to move it by
// a person's word (release true, which takes why: it is a hand act).
func NewHoldAgain(module, why, by string, release bool, at time.Time) (string, []byte, error) {
key, data, err := NewTakeIn(module, why, by, at)
if err != nil {
return "", nil, err
}
var a TakeInAsk
if err := json.Unmarshal(data, &a); err != nil {
return "", nil, err
}
if release && a.Why == "" {
return "", nil, errors.New("say why the hold is moved by hand (why): it is a hand act")
}
a.Hold = HoldAskAgain
if release {
a.Hold = HoldRelease
}
data, err = json.Marshal(a)
return holdPrefix + key, data, err
}
// The asks of a hold a takeins value names (TakeInAsk.Hold), and the prefix of its key.
const (
HoldAskAgain = "again"
HoldRelease = "release"
holdPrefix = "hold."
)