Files
mesh-delivery/modules/mesh-delivery-indexer/internal/index/held.go
T
jschoubben 04fe2e30fe H-A-497 indexer: a hand ask of a held branch answers at once
indexer_take_in_pending ran the whole chain of held take-ins inside the one
loop that acts on the takeins asks, minutes long, so its answer was cut and a
second ask waited behind it and answered "holds no source-moved". The ask
now starts the chain beside the loop and answers at once, "chain started at
source <n>, <m> wait"; an ask that meets a running chain answers its state.
The chain's state (branch, source being taken in, since, how many wait) is
the key chain.<branch> of the takeins state, written at each step and
deleted at the chain's end, skipped by the asks' loop and shown by
indexer_pending. A key a stop left is deleted at the indexer's start.

Builds: design 47 H2 H-A-497 (corrected), its addendum and its second addendum
2026-11-22 21:58:07 +01:00

460 lines
20 KiB
Go

package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/process"
)
// HeldState is the indexer's state held (design 47 H §744, H-A-97, H-A-118): one key per watched branch, the branch escaped as
// a key's name is, holding the branch's held source-moved events in order, oldest first, each written when it is held (its
// message acknowledged once written) and taken out at its take-in or skip; the key goes with its last. indexer_pending reads it.
const HeldState = "held"
// The held take-in's tools (§744).
const (
PendingTool = "indexer_pending"
TakeInPendingTool = "indexer_take_in_pending"
TakeInSkipTool = "indexer_take_in_skip"
)
// HeldTakeIn is one held source-moved of the state held: its branch, source revision, why it is held and since when (H-A-97),
// and the event's call, heads and start, so a take-in after a restart reads nothing of any verb (H-A-118).
type HeldTakeIn struct {
Branch string `json:"branch"`
Source int64 `json:"source"`
Why string `json:"why"`
Since time.Time `json:"since"`
Call string `json:"call"`
Heads []meshdelivery.SourceMovedEventHeadsItem `json:"heads"`
Start bool `json:"start,omitempty"`
}
// Event is the held source-moved, as the gate said it.
func (h HeldTakeIn) Event() meshdelivery.SourceMovedEvent {
return meshdelivery.SourceMovedEvent{V: keys.Version, Branch: h.Branch, Call: h.Call, Heads: h.Heads, Source: h.Source, Start: h.Start}
}
// PendingAnswer is indexer_pending's answer (H-A-102): every branch's held take-ins, in the state held's form (since in RFC 3339).
type PendingAnswer struct {
Held []HeldTakeIn `json:"held"`
// Running are the take-ins that run, each with what it waits on (design 47 H2 §803, H-A-409).
Running []RunningTakeIn `json:"running,omitempty"`
// Chains are the running chains of held take-ins, each branch's source being taken in, since when and how many wait
// (H-A-497 addendum).
Chains []HeldChain `json:"chains,omitempty"`
}
// ErrHeldUnwritten says a source-moved that could not be taken in is not written into the state held either: its message
// stays unacknowledged, so the bus gives it again.
var ErrHeldUnwritten = errors.New("the held take-in is not written into the state held")
// decodeHeld reads a key of the state held: the branch's held events in order.
func decodeHeld(v []byte) ([]HeldTakeIn, error) {
var hs []HeldTakeIn
if err := json.Unmarshal(v, &hs); err != nil {
return nil, fmt.Errorf("not a value of the state %s: %w", HeldState, err)
}
return hs, nil
}
// HeldOf is the branch's held events in order; none when it holds none.
func (ix *Indexer) HeldOf(ctx context.Context, branch string) ([]HeldTakeIn, error) {
if ix.Held == nil {
return nil, nil
}
v, _, found, err := ix.Held.Get(ctx, keys.EscapeName(branch))
if err != nil || !found {
return nil, err
}
return decodeHeld(v)
}
// hold writes e into its branch's held events, after those held before it, and says take-in.pending once per source: a source
// already held is neither written nor said again, so its since stays. ErrHeldUnwritten when it is not written.
func (ix *Indexer) hold(ctx context.Context, e meshdelivery.SourceMovedEvent, why string) error {
if ix.Held == nil {
return fmt.Errorf("%w: the indexer keeps no state %s", ErrHeldUnwritten, HeldState)
}
key, added := keys.EscapeName(e.Branch), false
err := write(ctx, ix.Held, key, func(v []byte, found bool) ([]byte, bool, error) {
var hs []HeldTakeIn
if found {
var err error
if hs, err = decodeHeld(v); err != nil {
return nil, false, err
}
}
for _, h := range hs {
if h.Source == e.Source {
added = false
return nil, false, nil
}
}
added = true
hs = append(hs, HeldTakeIn{Branch: e.Branch, Source: e.Source, Why: why, Since: ix.now().UTC(), Call: e.Call, Heads: e.Heads, Start: e.Start})
data, err := json.Marshal(hs)
return data, false, err
})
if err != nil {
ix.logf("take-in: %s.%s is not written: %v", HeldState, key, err)
return fmt.Errorf("%w: %v", ErrHeldUnwritten, err)
}
if !added {
return nil
}
ix.logf("take-in: source revision %d of %s is held: %s", e.Source, e.Branch, why)
if ix.SayTakeIn == nil {
return nil
}
p := meshcatalog.TakeInPending{Branch: e.Branch, Source: e.Source, Why: why}
if err := ix.SayTakeIn(ctx, takein.TakeInPendingEvent, PendingID(e.Branch, e.Source), p); err != nil {
ix.logf("take-in: take-in.pending of %s is not said: %v", BranchObject(e.Branch, e.Source), err)
}
return nil
}
// HoldBehind writes e behind its branch's earlier held events when the branch holds any, so the branch's source revisions are
// taken in in their order (H-A-118); it answers whether it did. ErrHeldUnwritten when it is not written.
func (ix *Indexer) HoldBehind(ctx context.Context, e meshdelivery.SourceMovedEvent) (bool, error) {
hs, err := ix.HeldOf(ctx, e.Branch)
if errors.Is(err, process.ErrNotYet) {
return false, nil // a state held not there yet holds nothing to take in first
}
if err != nil {
return false, fmt.Errorf("%w: %v", ErrHeldUnwritten, err)
}
if len(hs) == 0 {
return false, nil
}
return true, ix.hold(ctx, e, fmt.Sprintf("held behind source revision %d of %s, taken in first", hs[0].Source, e.Branch))
}
// unhold takes the branch's held source revision out of the state held, once it is taken in or skipped; the key goes with its last.
func (ix *Indexer) unhold(ctx context.Context, branch string, source int64) {
if ix.Held == nil {
return
}
key := keys.EscapeName(branch)
err := write(ctx, ix.Held, key, func(v []byte, found bool) ([]byte, bool, error) {
if !found {
return nil, false, nil
}
hs, err := decodeHeld(v)
if err != nil {
return nil, false, err
}
left := slices.DeleteFunc(slices.Clone(hs), func(h HeldTakeIn) bool { return h.Source == source })
if len(left) == len(hs) {
return nil, false, nil
}
if len(left) == 0 {
return nil, true, nil
}
data, err := json.Marshal(left)
return data, false, err
})
if err != nil {
ix.logf("take-in: source revision %d is not taken out of %s.%s: %v", source, HeldState, key, err)
}
}
// TakeHeldIn takes every branch's held source revisions in, each branch in its order, on the indexer's own room, at its
// start and by hand (H-A-114, H-A-118): a branch stops at the first that still cannot be taken in, which stays held with those
// behind it. Once a held one is taken in, the next held of its branch is taken in at once, each such start said in the journal
// (design 47 H2 H-A-497).
func (ix *Indexer) TakeHeldIn(ctx context.Context) {
all, err := ReadHeld(ctx, ix.Held)
if err != nil {
ix.logf("take-in: the state %s is not read, so no held take-in is taken in again now: %v", HeldState, err)
return
}
stopped, landed := map[string]bool{}, map[string]int64{}
behind := map[string]int{}
for _, h := range all {
behind[h.Branch]++
}
for i, h := range all {
behind[h.Branch]--
if stopped[h.Branch] {
continue
}
if prev, ok := landed[h.Branch]; ok {
ix.logf("take-in: held source %d of %s taken in next, after %d (H-A-497)", h.Source, h.Branch, prev)
}
ix.writeChain(ctx, HeldChain{Branch: h.Branch, Source: h.Source, Since: ix.now().UTC(), Waiting: behind[h.Branch]})
if _, err := ix.TakeInSource(ctx, h.Event()); err == nil {
landed[h.Branch] = h.Source
} else {
ix.logf("take-in: source revision %d of %s is still held: %v", h.Source, h.Branch, err)
stopped[h.Branch] = true
}
// The chain of a branch ends at its first held again or its last held (H-A-497 addendum).
if stopped[h.Branch] || !slices.ContainsFunc(all[i+1:], func(n HeldTakeIn) bool { return n.Branch == h.Branch }) {
ix.endChain(ctx, h.Branch)
}
}
}
// ChainPrefix is the takeins keys of the chains of held take-ins: `chain.<branch>`, the branch escaped as a key's name is,
// holding the branch's chain while it runs (design 47 H2 H-A-497 and its addendum): written at each step, deleted at its end.
const ChainPrefix = "chain."
// ChainKey is the takeins key of branch's chain.
func ChainKey(branch string) string { return ChainPrefix + keys.EscapeName(branch) }
// HeldChain is a running chain of a branch's held take-ins (H-A-497 addendum): the source being taken in, since when, and
// how many held sources of the branch wait behind it.
type HeldChain struct {
Branch string `json:"branch"`
Source int64 `json:"source"`
Since time.Time `json:"since"`
Waiting int `json:"waiting"`
}
// writeChain writes branch's chain at its step c into the state takeins; a failed write is said.
func (ix *Indexer) writeChain(ctx context.Context, c HeldChain) {
if ix.TakeIns == nil {
return
}
data, err := json.Marshal(c)
if err == nil {
err = write(ctx, ix.TakeIns, ChainKey(c.Branch), func([]byte, bool) ([]byte, bool, error) { return data, false, nil })
}
if err != nil {
ix.logf("take-in: the chain of %s at source revision %d is not written into %s: %v", c.Branch, c.Source, TakeInsState, err)
}
}
// EndChain deletes branch's chain from the state takeins once the take-in its ask started returned, so a chain whose held
// sources another act took first is never left running.
func (ix *Indexer) EndChain(ctx context.Context, branch string) { ix.endChain(ctx, branch) }
// EndChains deletes every chain the state takeins holds, at the indexer's start (H-A-497 addendum): no chain runs before the
// start's take-in, so a key left by a stop between a chain's last take-in and its end would answer "a chain runs" for good.
func (ix *Indexer) EndChains(ctx context.Context) {
chains, err := ReadChains(ctx, ix.TakeIns)
if err != nil {
ix.logf("take-in: the chains in %s are not read, so none left by a stop is deleted: %v", TakeInsState, err)
return
}
for _, c := range chains {
ix.logf("take-in: the chain of %s at source revision %d, left by a stop, is deleted at the start", c.Branch, c.Source)
ix.endChain(ctx, c.Branch)
}
}
// endChain deletes branch's chain from the state takeins.
func (ix *Indexer) endChain(ctx context.Context, branch string) {
if ix.TakeIns == nil {
return
}
if err := write(ctx, ix.TakeIns, ChainKey(branch), func([]byte, bool) ([]byte, bool, error) { return nil, true, nil }); err != nil {
ix.logf("take-in: the chain of %s is not deleted from %s: %v", branch, TakeInsState, err)
}
}
// StartChain writes branch's chain at its first held source, before the chain is taken in beside the asks (H-A-497
// addendum), so an ask after it finds it running; it answers that chain.
func (ix *Indexer) StartChain(ctx context.Context, held []HeldTakeIn) HeldChain {
c := HeldChain{Branch: held[0].Branch, Source: held[0].Source, Since: ix.now().UTC(), Waiting: len(held) - 1}
ix.writeChain(ctx, c)
return c
}
// ChainOf is branch's running chain in the state takeins, and whether one runs.
func (ix *Indexer) ChainOf(ctx context.Context, branch string) (HeldChain, bool, error) {
if ix.TakeIns == nil {
return HeldChain{}, false, nil
}
v, _, found, err := ix.TakeIns.Get(ctx, ChainKey(branch))
if err != nil || !found {
return HeldChain{}, false, err
}
var c HeldChain
if err := json.Unmarshal(v, &c); err != nil {
return HeldChain{}, false, fmt.Errorf("%s.%s: %w", TakeInsState, ChainKey(branch), err)
}
return c, true, nil
}
// ReadChains are the running chains the state takeins holds (H-A-497 addendum), each branch's once.
func ReadChains(ctx context.Context, st Store) ([]HeldChain, error) {
if st == nil {
return nil, nil
}
ks, err := st.Keys(ctx)
if err != nil {
return nil, err
}
slices.Sort(ks)
var out []HeldChain
for _, k := range ks {
if !strings.HasPrefix(k, ChainPrefix) {
continue
}
v, _, found, err := st.Get(ctx, k)
if err != nil {
return nil, err
}
var c HeldChain
if !found || json.Unmarshal(v, &c) != nil {
continue
}
out = append(out, c)
}
return out, nil
}
// SkipTakeIn ends a held source revision unwritten by hand (indexer_take_in_skip, §744): it says take-in.taken with no entries,
// skipped, by and why, and deletes the branch's held take-in; the caller acknowledges the source-moved.
func (ix *Indexer) SkipTakeIn(ctx context.Context, e meshdelivery.SourceMovedEvent, by, why string) error {
if err := ix.sayTaken(ctx, meshcatalog.TakeInTaken{Branch: e.Branch, Source: e.Source, Call: e.Call, Skipped: true, By: by, Why: why}); err != nil {
return err
}
ix.unhold(ctx, e.Branch, e.Source)
ix.logf("take-in: source revision %d of %s skipped by %s: %s", e.Source, e.Branch, by, why)
return nil
}
// ReadHeld is every branch's held take-ins, by branch, each branch's in its order.
func ReadHeld(ctx context.Context, st Store) ([]HeldTakeIn, error) {
out := []HeldTakeIn{}
if st == nil {
return out, nil
}
ks, err := st.Keys(ctx)
if err != nil {
return nil, err
}
slices.Sort(ks)
for _, k := range ks {
v, _, found, err := st.Get(ctx, k)
if err != nil {
return nil, err
}
if !found {
continue
}
hs, err := decodeHeld(v)
if err != nil {
return nil, fmt.Errorf("%s.%s: %w", HeldState, k, err)
}
out = append(out, hs...)
}
return out, nil
}
// HeldTools are the held take-in's tools (§744): indexer_pending reads the state held and the running take-ins' waiting-on in
// the state takeins (H2 §803, H-A-409); indexer_take_in_pending takes a branch's
// held source-moved again now and indexer_take_in_skip acknowledges it unwritten, each an ask in the state takeins the indexer
// acts on (H-A-97), the skip a hand act recorded through mesh-hand-acts before it is asked.
func HeldTools(held, takeIns Store, ask func(key string, value []byte) (TakeInAsk, error), now func() time.Time, record func(what, why string) error) []stdio.Tool {
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
return []stdio.Tool{
{Name: PendingTool,
Description: "Each watched branch's held take-in (design 47 H §744): the source revision of the gate's source-moved the indexer " +
"could not take in (the catalog store full, a read of the forge unanswered), why and since when, in order, each kept here once " +
"acknowledged and taken in again on the indexer's room and at its start; each running take-in that waits over a minute on another part, its waiting-on (part, verb, since); and each running chain of held take-ins, the source being taken in, since when and how many wait. indexer_take_in_pending takes it again now, indexer_take_in_skip ends it unwritten.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) {
h, err := ReadHeld(context.Background(), held)
if err != nil {
return PendingAnswer{Held: h}, err
}
r, err := ReadRunning(context.Background(), takeIns)
if err != nil {
return PendingAnswer{Held: h, Running: r}, err
}
c, err := ReadChains(context.Background(), takeIns)
return PendingAnswer{Held: h, Running: r, Chains: c}, err
}},
{Name: TakeInPendingTool,
Description: "Take a watched branch's held source-moved in again now (design 47 H §744), as the indexer's room would: " +
"the held sources are taken in in order beside the asks, and it answers at once that the chain started at a source and " +
"how many wait, or, while a chain runs, its state (design 47 H2 H-A-497). indexer_pending names the held branches and the running chains.",
Input: map[string]any{"type": "object", "required": []string{"branch"}, "properties": map[string]any{
"branch": map[string]any{"type": "string", "description": "the watched branch, as indexer_pending names it"},
"why": map[string]any{"type": "string", "description": "why it is taken again now"}}},
Run: func(args map[string]any) (any, error) {
branch := str(args, "branch")
if branch == "" {
return nil, errors.New("name the held branch (branch), as indexer_pending names it")
}
data, err := json.Marshal(TakeInAsk{V: 1, Held: branch, Why: str(args, "why"), By: stdio.CallerOf(args), At: now().UTC()})
if err != nil {
return nil, err
}
a, err := ask("held."+keys.EscapeName(branch)+".again", data)
if err != nil {
return nil, err
}
return a.Result, nil
}},
{Name: TakeInAgainTool,
Description: "Take a repository in again now at the merge commit the indexer keeps of it (design 47 H-A-208, H-A-210): its " +
"module graph is read again (each module's requirements, transitively) and the modules state recomputed as a " +
"package's publish re-pins it, so a changed take-in rule reaches a repository with no merge since; pins and " +
"fingerprints move, no catalog revision is kept and the gate is not asked. An unknown repository is refused.",
Input: map[string]any{"type": "object", "required": []string{"repository"}, "properties": map[string]any{
"repository": map[string]any{"type": "string", "description": "the repository as owner/name, such as novox/mesh-host"},
"why": map[string]any{"type": "string", "description": "why it is taken in again now"}}},
Run: func(args map[string]any) (any, error) {
repository := str(args, "repository")
if repository == "" {
return nil, errors.New("name the repository (repository) as owner/name")
}
data, err := json.Marshal(TakeInAsk{V: 1, Again: repository, Why: str(args, "why"), By: stdio.CallerOf(args), At: now().UTC()})
if err != nil {
return nil, err
}
a, err := ask("again."+keys.EscapeName(repository), data)
if err != nil {
return nil, err
}
if a.Result != nil && !a.Result.Stored {
return a.Result, fmt.Errorf("%s is not taken in again: %s", repository, a.Result.Answer)
}
return a.Result, nil
}},
{Name: TakeInSkipTool,
Description: "End a watched branch's held source-moved unwritten (design 47 H §744): it is acknowledged, take-in.taken is said " +
"with no entries and skipped, and the hand act is recorded through mesh-hand-acts before it is asked. indexer_pending " +
"names the held branch and source.",
Input: map[string]any{"type": "object", "required": []string{"branch", "source", "why"}, "properties": map[string]any{
"branch": map[string]any{"type": "string", "description": "the watched branch, as indexer_pending names it"},
"source": map[string]any{"type": "integer", "description": "the held source revision"},
"why": map[string]any{"type": "string", "description": "why it is skipped, in plain words"}}},
Run: func(args map[string]any) (any, error) {
branch, why := str(args, "branch"), str(args, "why")
source, _ := args["source"].(float64)
if branch == "" || source <= 0 || why == "" {
return nil, errors.New("name the held branch (branch) and source revision (source) and say why (why): a skip is a hand act, recorded through mesh-hand-acts")
}
data, err := json.Marshal(TakeInAsk{V: 1, Held: branch, HeldSource: int64(source), Skip: true, Why: why, By: stdio.CallerOf(args), At: now().UTC()})
if err != nil {
return nil, err
}
if err := record(fmt.Sprintf("skipped the held source revision %d of %s unwritten by hand", int64(source), branch), why); err != nil {
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was skipped: %w", err)
}
a, err := ask(fmt.Sprintf("held.%s.skip.%d", keys.EscapeName(branch), int64(source)), data)
if err != nil {
return nil, err
}
return a.Result, nil
}},
}
}