Files
mesh-delivery/modules/mesh-delivery-indexer/internal/index/dryrun.go
T
jschoubben d719a69b7d I3: a dry run keeps its packages in its own scratch state
A branch's take-in, a run's candidate and a branch's re-pin compute as dry
runs whose packages went to the trunk's packages state. They now write them
to the state dry-runs under <branch>.<call>.packages.<name>, read through to
the live state, deleted when the dry run answers and every key at the
indexer's start; the manifests stay create-once by digest as every take-in's.
indexer_dry_runs reads the state; the manifest asks for it, 16 MiB, one
hour's TTL.

Builds: design 47 H2 §804, §820; H-A-413 and its addendum
2026-11-22 01:08:34 +01:00

343 lines
13 KiB
Go

package index
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"strings"
"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/nodebuildgo"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
)
type dryRun struct {
ix *Indexer
modules, graph *overlayStore
candidates, taken, predefined *overlayStore
oldSections *overlayStore
// scratch is the state dry-runs this dry run's packages are written to, under prefix (§804); nil when the indexer keeps
// none, and the packages then stay in memory.
scratch Store
prefix string
logf func(string, ...any)
}
// dry is an indexer over overlays of this one's states (overlay.go), for a run on request's candidate (runcandidates.go), a
// branch's take-in or re-pin: what it computes stays in memory but the packages it writes, kept in the state dry-runs under
// the branch and call given (scratchStore; design 47 H2 §804, H-A-413), so the trunk's packages state is left untouched; its
// manifests are written create-once by digest as every take-in's (H-A-413's addendum). The caller ends it (end) once it
// answered. It says no event, kicks nothing in the background, and knows what this one knows of the source and the
// toolchains. Every field of Indexer is named here.
func (ix *Indexer) dry(branch, call string) *dryRun {
over := func(st Store) (Store, *overlayStore) {
if st == nil {
return nil, nil
}
o := newOverlay(st)
return o, o
}
d := &dryRun{scratch: ix.DryRuns, prefix: DryRunPrefix(branch, call), logf: ix.logf}
packages := ix.Packages
if packages != nil && d.scratch != nil {
packages = &scratchStore{under: ix.Packages, scratch: d.scratch, prefix: d.prefix + PackagesState + "."}
} else if packages != nil {
packages = newOverlay(ix.Packages)
}
x := &Indexer{Module: ix.Module, Manifests: ix.Manifests, Packages: packages, DryRuns: nil, JudgeID: ix.JudgeID, Files: ix.Files, GoSum: ix.GoSum,
GoMod: ix.GoMod, Now: ix.Now, Bound: ix.Bound,
// A dry run keeps no waiting-on: the take-in it computes for says its waits through the live indexer (H-A-409).
TakeIns: nil, Builds: ix.Builds, Named: ix.Named, Trunk: ix.Trunk, BranchHead: ix.BranchHead, Read: ix.Read, Contains: ix.Contains,
SayTakeIn: nil,
// The registry milestone's fields: what a take-in would write on the bus stays out of a dry run, so the states of the
// requirements, findings, seat definitions, holds and their bounds are not overlaid, nothing is said, and no hold is
// weighed (Holds and Counted nil hold nothing); ReadFile only reads.
Requirements: nil, Findings: nil, SeatDefinitions: nil, ReadFile: ix.ReadFile, SaySeatDefinition: nil,
Heard: nil, underSeats: true, isDry: true,
// A dry run keeps no catalog graph revision (catalog_revisions.go): its revision is the take-in's to keep.
Revisions: nil, SayCatalogRevision: nil, SayFill: nil, EntryIndex: nil, NamedSets: nil, Versions: nil, SayVersionReleased: nil, SayVersionsFilled: nil, Inputs: nil, InputObjects: nil, Pins: nil, PinsPending: nil,
// A dry run writes no registration and asks no one.
Registry: nil, SeedModules: nil}
x.Logf = func(format string, args ...any) { ix.logf("take-in, computed and not written: "+format, args...) }
x.Store, d.candidates = over(ix.Store)
x.Modules, d.modules = over(ix.Modules)
x.Graph, d.graph = over(ix.Graph)
x.Taken, d.taken = over(ix.Taken)
x.Predefined, d.predefined = over(ix.Predefined)
x.OldSections, d.oldSections = over(ix.OldSections)
ix.mu.Lock()
x.source = sourceNow{rev: ix.source.rev, heads: maps.Clone(ix.source.heads)}
x.toolchains = map[string]map[string]nodebuildgo.Toolchain{}
for l, by := range ix.toolchains {
x.toolchains[l] = maps.Clone(by)
}
x.buildModules = maps.Clone(ix.buildModules) // the dry run computes with the build modules the running indexer takes
x.moving = maps.Clone(ix.moving)
x.untaken = maps.Clone(ix.untaken)
ix.mu.Unlock()
d.ix = x
return d
}
// refuseDisagreement refuses a candidate in which two pull requests give one module different manifests, as the
// candidate's own check does (mesh-sdk Candidate.check), naming both pull requests so the log says which; nothing is
// written, and the message is dropped as unreadable and said in the log (main.go handle): the next message of either pull
// request is judged again.
func (ix *Indexer) refuseDisagreement(c meshcatalog.CandidatesByGroupValue) error {
first := map[string]meshcatalog.CandidatesByGroupValuePullsItem{}
for _, p := range c.Pulls {
for module, m := range p.Fps {
before, ok := first[module]
if !ok {
first[module] = p
continue
}
if !reflect.DeepEqual(before.Fps[module], m) {
err := fmt.Errorf("%w: candidates.%s: %s#%d and %s#%d give the module %q different manifests (%s and %s), so the group is not written",
ErrUnreadable, c.Group, before.Repository, before.Number, p.Repository, p.Number, module, before.Fps[module].Manifest, m.Manifest)
return err
}
}
}
return nil
}
// DryRunsState is the indexer's state dry-runs (design 47 H2 §804, §820; H-A-413): a dry run's scratch, the overlay of the
// packages state a dry run writes, keyed <branch>.<call>.<kind>.<name> (DryRunPrefix, the kind the overlaid state's name and
// the name its key), so a dry run leaves the trunk's packages state untouched. The indexer deletes a dry run's keys when it
// answers, and every key at its start; each lives an hour at most (the state's TTL). indexer_dry_runs reads it.
const (
DryRunsState = "dry-runs"
DryRunsTool = "indexer_dry_runs"
)
// DryRunPrefix is the prefix of a dry run's keys in the state dry-runs: its branch, escaped as a key's name is, and its call.
func DryRunPrefix(branch, call string) string {
return keys.EscapeName(branch) + "." + keys.EscapeName(call) + "."
}
// scratchRevision lifts a revision of the state dry-runs above every revision of the state it overlays, as overlayStore does.
const scratchRevision = 1 << 62
// scratched is a value of the state dry-runs: the value a dry run wrote over its key, or that it deleted it.
type scratched struct {
Value []byte `json:"value,omitempty"`
Deleted bool `json:"deleted,omitempty"`
}
// scratchStore is a store whose writes go to the state dry-runs under its prefix, over the store it reads through: a key
// it wrote reads as written, a key it deleted as absent, every other as the store under it holds it. Its compare-and-set
// holds against what it reads, a key it wrote carrying the dry-runs revision lifted by scratchRevision.
type scratchStore struct {
under, scratch Store
prefix string
}
func (s *scratchStore) held(ctx context.Context, key string) (scratched, uint64, bool, error) {
raw, rev, found, err := s.scratch.Get(ctx, s.prefix+key)
if err != nil || !found {
return scratched{}, 0, false, err
}
var v scratched
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, false, fmt.Errorf("%s.%s%s: %w", DryRunsState, s.prefix, key, err)
}
return v, rev, true, nil
}
func (s *scratchStore) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
v, rev, found, err := s.held(ctx, key)
if err != nil {
return nil, 0, false, err
}
if found {
if v.Deleted {
return nil, rev + scratchRevision, false, nil
}
return v.Value, rev + scratchRevision, true, nil
}
if s.under == nil {
return nil, 0, false, nil
}
return s.under.Get(ctx, key)
}
// put checks the revision read against what the key reads as now and writes it into the state dry-runs.
func (s *scratchStore) put(ctx context.Context, key string, value []byte, revision uint64, create, del bool) error {
_, own, mine, err := s.held(ctx, key)
if err != nil {
return err
}
_, rev, found, err := s.Get(ctx, key)
if err != nil {
return err
}
if create && found || !create && (!found || rev != revision) {
return ErrConflict
}
data, err := json.Marshal(scratched{Value: value, Deleted: del})
if err != nil {
return err
}
if mine {
return s.scratch.Update(ctx, s.prefix+key, data, own)
}
return s.scratch.Create(ctx, s.prefix+key, data)
}
func (s *scratchStore) Create(ctx context.Context, key string, value []byte) error {
return s.put(ctx, key, value, 0, true, false)
}
func (s *scratchStore) Update(ctx context.Context, key string, value []byte, revision uint64) error {
return s.put(ctx, key, value, revision, false, false)
}
func (s *scratchStore) Delete(ctx context.Context, key string, revision uint64) error {
return s.put(ctx, key, nil, revision, false, true)
}
func (s *scratchStore) Keys(ctx context.Context) ([]string, error) {
var out []string
if s.under != nil {
var err error
if out, err = s.under.Keys(ctx); err != nil {
return nil, err
}
}
all, err := s.scratch.Keys(ctx)
if err != nil {
return nil, err
}
mine := map[string]bool{}
for _, k := range all {
if !strings.HasPrefix(k, s.prefix) {
continue
}
key := strings.TrimPrefix(k, s.prefix)
v, _, found, err := s.held(ctx, key)
if err != nil {
return nil, err
}
if found {
mine[key] = !v.Deleted
}
}
out = slices.DeleteFunc(out, func(k string) bool { _, ok := mine[k]; return ok })
for k, live := range mine {
if live {
out = append(out, k)
}
}
slices.Sort(out)
return out, nil
}
// end deletes the dry run's keys from the state dry-runs, once it answered (§804); a key it cannot delete is said, and goes
// with the state's TTL or at the indexer's next start.
func (d *dryRun) end(ctx context.Context) {
if d == nil || d.scratch == nil {
return
}
if err := dropPrefixed(ctx, d.scratch, d.prefix); err != nil {
d.logf("the dry run's keys %s* are not all deleted from %s: %v", d.prefix, DryRunsState, err)
}
}
// ClearDryRuns deletes every key of the state dry-runs, at the indexer's start (§804): no dry run outlives a start.
func ClearDryRuns(ctx context.Context, st Store) error { return dropPrefixed(ctx, st, "") }
func dropPrefixed(ctx context.Context, st Store, prefix string) error {
all, err := st.Keys(ctx)
if err != nil {
return err
}
var errs []error
for _, k := range all {
if !strings.HasPrefix(k, prefix) {
continue
}
_, rev, found, err := st.Get(ctx, k)
if err == nil && found {
err = st.Delete(ctx, k, rev)
}
if err != nil && !errors.Is(err, ErrConflict) {
errs = append(errs, fmt.Errorf("%s: %w", k, err))
}
}
return errors.Join(errs...)
}
// DryRunKey is one key of the state dry-runs as indexer_dry_runs answers it: the key, the value the dry run wrote (none when
// it deleted the key) and whether it deleted it.
type DryRunKey struct {
Key string `json:"key"`
Value json.RawMessage `json:"value,omitempty"`
Deleted bool `json:"deleted,omitempty"`
}
// DryRunsAnswer is indexer_dry_runs' answer: the keys in key order up to views.PageBytes, capped when more are held, and
// how many the state holds in all.
type DryRunsAnswer struct {
Keys []DryRunKey `json:"keys"`
Capped bool `json:"capped,omitempty"`
Total int `json:"total"`
}
// ReadDryRuns is what the state dry-runs holds now, at most views.PageBytes of values (§804, §811).
func ReadDryRuns(ctx context.Context, st Store) (DryRunsAnswer, error) {
out := DryRunsAnswer{Keys: []DryRunKey{}}
if st == nil {
return out, nil
}
all, err := st.Keys(ctx)
if err != nil {
return out, err
}
slices.Sort(all)
out.Total = len(all)
size := 0
for _, k := range all {
raw, _, found, err := st.Get(ctx, k)
if err != nil {
return out, err
}
if !found {
continue
}
var v scratched
if err := json.Unmarshal(raw, &v); err != nil {
return out, fmt.Errorf("%s.%s: %w", DryRunsState, k, err)
}
if size += len(k) + len(v.Value); size > views.PageBytes && len(out.Keys) > 0 {
out.Capped = true
break
}
e := DryRunKey{Key: k, Deleted: v.Deleted}
if !v.Deleted {
e.Value = v.Value
}
out.Keys = append(out.Keys, e)
}
return out, nil
}
// DryRunsTools are the dry runs' tools: indexer_dry_runs reads the state dry-runs (§804).
func DryRunsTools(st Store) []stdio.Tool {
return []stdio.Tool{{Name: DryRunsTool,
Description: "The dry runs' scratch state dry-runs (design 47 H2 §804): the packages a branch's take-in, a run's candidate " +
"or a branch's re-pin computes, kept as <branch>.<call>.packages.<name> while it runs, so the trunk's packages state " +
"is left untouched; a dry run's keys go when it answers and every key at the indexer's start. Each key with the " +
"value it wrote or deleted, up to 768 KB (capped) and the total held.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) {
return ReadDryRuns(context.Background(), st)
}}}
}