From af5a7e58701c353d68344b70f553019b615e8806 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:18:28 +0100 Subject: [PATCH] I1 needs-in-the-judge: ManifestNeeds and ModuleNeeds move into the manifest validator, read field by field through catalogue.Manifest, a key taken only where ManifestReads names its path Builds: design 47 H2 H-A-568, H-A-622, H-A-639, H-A-640, H-A-669 --- .../internal/index/modules.go | 3 +- .../internal/index/modules_test.go | 4 +- .../internal/index/source.go | 3 +- modules/mesh-delivery-indexer/judge/needs.go | 360 ++++++++++++++++++ .../mesh-delivery-indexer/judge/needs_test.go | 74 ++++ 5 files changed, 439 insertions(+), 5 deletions(-) create mode 100644 modules/mesh-delivery-indexer/judge/needs.go create mode 100644 modules/mesh-delivery-indexer/judge/needs_test.go diff --git a/modules/mesh-delivery-indexer/internal/index/modules.go b/modules/mesh-delivery-indexer/internal/index/modules.go index a8cb0cec2..6dc86e668 100644 --- a/modules/mesh-delivery-indexer/internal/index/modules.go +++ b/modules/mesh-delivery-indexer/internal/index/modules.go @@ -10,7 +10,6 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" - "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/keys" "mesh-delivery-indexer/internal/fingerprint" @@ -102,7 +101,7 @@ func (ix *Indexer) applyMoving(ctx context.Context, f whole, drop bool, moves ma next := meshcatalog.ModulesByModuleValue{Repository: f.Repository, Commit: f.Merge, Manifest: digests[dir], Path: pathOf(dir)} // The reader capabilities a changed manifest needs are written with it, before the judge's pass names them with its // verdict, so no reader takes a new manifest as needing nothing (ADR 0614 §4). - next.Needs, _ = catalogue.ManifestNeeds([]byte(raw)) + next.Needs, _ = judge.ManifestNeeds([]byte(raw)) if whole, ok := f.Needs[dir]; ok { next.Needs = whole // its templates' text too, read by the forge bridge at the merge (ADR 0632 §2) } diff --git a/modules/mesh-delivery-indexer/internal/index/modules_test.go b/modules/mesh-delivery-indexer/internal/index/modules_test.go index e5748ce63..e44343e77 100644 --- a/modules/mesh-delivery-indexer/internal/index/modules_test.go +++ b/modules/mesh-delivery-indexer/internal/index/modules_test.go @@ -16,8 +16,8 @@ import ( "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" - "git.novox.be/novox/mesh-sdk/go/catalogue" "git.novox.be/novox/mesh-sdk/go/process" + "mesh-delivery-indexer/judge" ) const merge = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -441,7 +441,7 @@ func TestAMergeAddingAModuleDirectoryWritesItsValueWithNoBuildRecordAnywhere(t * } // ADR 0614 §4: the merge writes the reader capabilities its manifest needs, so no reader takes it as needing nothing // before the judge's pass. - if want, _ := catalogue.ManifestNeeds([]byte(avahi)); len(m.Needs) == 0 || !slices.Equal(m.Needs, want) { + if want, _ := judge.ManifestNeeds([]byte(avahi)); len(m.Needs) == 0 || !slices.Equal(m.Needs, want) { t.Errorf("module needs %v, want %v", m.Needs, want) } } diff --git a/modules/mesh-delivery-indexer/internal/index/source.go b/modules/mesh-delivery-indexer/internal/index/source.go index ea7531504..4006704d9 100644 --- a/modules/mesh-delivery-indexer/internal/index/source.go +++ b/modules/mesh-delivery-indexer/internal/index/source.go @@ -10,6 +10,7 @@ import ( "slices" "git.novox.be/novox/mesh-sdk/go/catalogue" + "mesh-delivery-indexer/judge" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" ) @@ -66,7 +67,7 @@ func (ix *Indexer) wholeAt(ctx context.Context, repository, head string) (whole, if f.Needs == nil { f.Needs = map[string][]string{} } - f.Needs[dir], _ = catalogue.ModuleNeeds([]byte(read.Manifests[dir]), texts) + f.Needs[dir], _ = judge.ModuleNeeds([]byte(read.Manifests[dir]), texts) } if l := read.Locks[dir]; len(l) > 0 { if f.Locks == nil { diff --git a/modules/mesh-delivery-indexer/judge/needs.go b/modules/mesh-delivery-indexer/judge/needs.go new file mode 100644 index 000000000..950ec5f89 --- /dev/null +++ b/modules/mesh-delivery-indexer/judge/needs.go @@ -0,0 +1,360 @@ +package judge + +import ( + "bytes" + "encoding/json" + "reflect" + "regexp" + "slices" + "sort" + "strings" + + "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// The reader capabilities a manifest needs (novox/hq ADR 0614 §4; design 47 H2, H-A-639, H-A-669): a manifest word, a +// form or a seat name of the shared contract a reader of manifests (a node-engine) must read for the manifest. +// ManifestNeeds names them for one manifest, ModuleNeeds for a module whose files take their text from templates. The +// manifest is read field by field through catalogue.Manifest, and a key is a word only where catalogue.ManifestReads() +// names its path; a unit test holds the two equal, so a difference fails. + +// requirementLong is one entry of `requires` in its long form, as catalogue reads it. +type requirementLong struct { + Name string `json:"name"` + Optional bool `json:"optional,omitempty"` + Shares []catalogue.BucketShare `json:"shares,omitempty"` +} + +// topWords are the keys catalogue.Manifest's decoder reads whole beside its fields, no words of the contract beneath. +var topWords = []string{"secrets", "contributes", catalogue.OptionalRequiresKey, catalogue.RequireSharesKey} + +// wireKeys are the keys of a block whose decoder reads its object by keys of its own. +var wireKeys = map[reflect.Type][]string{ + reflect.TypeOf(catalogue.OfferIdentity{}): {"max", "in"}, + reflect.TypeOf(catalogue.DataBackup{}): {"dump", "into"}, + reflect.TypeOf(catalogue.OwnSecret{}): {"path", "taken", "issued-by", "prompt", "owner"}, +} + +var ( + takesConfigKey = regexp.MustCompile(`"` + catalogue.TakesConfigField + `"(\s*):`) + needsSeatReach = regexp.MustCompile(`\$\{seat:[a-z0-9][a-z0-9-]*:reach\}`) +) + +const ( + configJSONToken = "${config-json}" + ifConfigWord = catalogue.ReadWord + "resources." + catalogue.IfConfigField + storeHolderSeat = "container-image-registry" +) + +// ManifestNeeds is every reader capability a manifest's own words, forms and seat names need, sorted. An error is +// only bytes that are no JSON object. +func ManifestNeeds(raw []byte) ([]string, error) { + var top map[string]any + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + if err := dec.Decode(&top); err != nil { + return nil, err + } + used := map[string]bool{} + textNeeds(raw, used) + if claimsAtMesh(top, storeHolderSeat) { + used[catalogue.ReadForm+catalogue.ReferenceFormSeatReach] = true + } + if runsAs, _ := top["runs-as"].(string); runsAs != "" { + used[nodeengine.ManifestReadWordDirectoryContentsOwner] = true + } + for _, r := range asList(top["resources"]) { + if obj, ok := r.(map[string]any); ok { + if _, has := obj[catalogue.IfConfigField]; has { + used[ifConfigWord] = true + } + } + } + if _, has := top[catalogue.ConfigField]; has || takesConfigKey.Match(raw) { + used[catalogue.ReadForm+"config"] = true + } + words := map[string]bool{} + fields := structFields(reflect.TypeOf(catalogue.Manifest{})) + for _, k := range sortedAnyKeys(top) { + v := top[k] + switch { + case k == catalogue.ConfigField: + // The config form is the settings form's words under another key. + words[catalogue.SettingsField] = true + walkValue(v, fields[catalogue.SettingsField].Type, catalogue.SettingsField, words) + case k == "requires": + words[k] = true + for _, e := range asList(v) { + obj, isObj := e.(map[string]any) + if !isObj { + continue + } + if _, bus := obj["storage"]; bus { + words[catalogue.BusStateField] = true + walkValue(obj, reflect.TypeOf(catalogue.BusStateEntry{}), catalogue.BusStateField, words) + continue + } + walkValue(obj, reflect.TypeOf(requirementLong{}), k, words) + } + case slices.Contains(topWords, k): + words[k] = true + default: + if f, known := fields[k]; known { + words[k] = true + walkValue(v, f.Type, k, words) + } + } + } + read := map[string]bool{} + for _, r := range catalogue.ManifestReads() { + read[r] = true + } + for w := range words { + if read[catalogue.ReadWord+w] { + used[catalogue.ReadWord+w] = true + } + } + for _, s := range seatNamesUsed(top) { + used[catalogue.ReadSeat+s] = true + } + return sortedSet(used), nil +} + +// ModuleNeeds is ManifestNeeds of a module whose files take their text from templates: what the manifest needs and +// what each template's text writes, sorted. A template named and not given is no need. +func ModuleNeeds(raw []byte, templates map[string]string) ([]string, error) { + needs, err := ManifestNeeds(raw) + if err != nil || len(templates) == 0 { + return needs, err + } + used := map[string]bool{} + for _, n := range needs { + used[n] = true + } + for _, text := range templates { + textNeeds([]byte(text), used) + } + return sortedSet(used), nil +} + +// readerWords is every word the validator's field-by-field reading can name, by path, sorted: the words +// catalogue.ManifestReads() must name, so a unit test holds the two equal. +func readerWords() []string { + set := map[string]bool{} + walkType(reflect.TypeOf(catalogue.Manifest{}), "", set, map[reflect.Type]bool{}) + set["requires"] = true + set[strings.TrimPrefix(ifConfigWord, catalogue.ReadWord)] = true // a resource's key, read beside the fields + walkType(reflect.TypeOf(requirementLong{}), "requires", set, map[reflect.Type]bool{}) + for _, w := range topWords { + set[w] = true + } + return sortedSet(set) +} + +// textNeeds adds the reference forms a manifest's or a template's text writes to used. +func textNeeds(text []byte, used map[string]bool) { + for _, f := range referenceFormsRead() { + if bytes.Contains(text, []byte("${"+f+":")) { + used[catalogue.ReadForm+f] = true + } + } + if bytes.Contains(text, []byte(configJSONToken)) { + used[catalogue.ReadForm+"config-json"] = true + } + if needsSeatReach.Match(text) { + used[catalogue.ReadForm+catalogue.ReferenceFormSeatReach] = true + } +} + +// referenceFormsRead are the reference forms a manifest's values may hold, `${:…}`: the forms catalogue.ManifestReads() +// names, but for the two it reads by another rule (a build's artifact reference, and a seat's reach). +func referenceFormsRead() []string { + var out []string + for _, r := range catalogue.ManifestReads() { + f, ok := strings.CutPrefix(r, catalogue.ReadForm) + if !ok || f == catalogue.ReferenceFormSeat || f == catalogue.ReferenceFormSeatReach { + continue + } + out = append(out, f) + } + return out +} + +func claimsAtMesh(top map[string]any, seat string) bool { + for _, c := range asList(top["claims"]) { + obj, _ := c.(map[string]any) + name, _ := obj["name"].(string) + scope, _ := obj["scope"].(string) + if hs, ok := catalogue.SeatNamed(name); ok && hs.Name == seat && (scope == "" || scope == catalogue.ScopeMesh) { + return true + } + } + return false +} + +// seatNamesUsed is each seat of the contract's table the manifest names: in a claim, a use, an invoke of a seat's verb, +// and a bucket's share with a seat. +func seatNamesUsed(top map[string]any) []string { + known := map[string]bool{} + for _, s := range catalogue.Seats() { + known[s.Name] = true + } + set := map[string]bool{} + add := func(name string) { + if known[name] { + set[name] = true + } + } + for _, c := range asList(top["claims"]) { + if obj, ok := c.(map[string]any); ok { + name, _ := obj["name"].(string) + add(name) + } + } + for _, u := range asList(top["uses"]) { + name, _ := u.(string) + add(name) + } + for _, i := range asList(top["invokes"]) { + text, _ := i.(string) + if seat, _, ok := catalogue.SeatInvoke(text); ok { + add(seat) + } + } + for _, r := range asList(top["requires"]) { + obj, _ := r.(map[string]any) + for _, share := range asList(obj["shares"]) { + text, _ := share.(string) + if seat, ok := strings.CutPrefix(text, "seat:"); ok { + add(seat) + } + } + } + return sortedSet(set) +} + +func walkType(t reflect.Type, path string, set map[string]bool, onPath map[reflect.Type]bool) { + t = deref(t) + if keys, custom := wireKeys[t]; custom { + for _, k := range keys { + set[joinWord(path, k)] = true + } + return + } + switch t.Kind() { + case reflect.Struct: + if onPath[t] { + return + } + onPath[t] = true + defer delete(onPath, t) + for name, f := range structFields(t) { + word := joinWord(path, name) + set[word] = true + walkType(f.Type, word, set, onPath) + } + case reflect.Slice, reflect.Array, reflect.Map: + if t.Elem().Kind() == reflect.Uint8 { + return + } + walkType(t.Elem(), path, set, onPath) + } +} + +func walkValue(v any, t reflect.Type, path string, used map[string]bool) { + t = deref(t) + if keys, custom := wireKeys[t]; custom { + obj, _ := v.(map[string]any) + for _, k := range keys { + if _, has := obj[k]; has { + used[joinWord(path, k)] = true + } + } + return + } + switch t.Kind() { + case reflect.Struct: + obj, isObj := v.(map[string]any) + if !isObj { + return + } + fields := structFields(t) + for _, k := range sortedAnyKeys(obj) { + f, known := fields[k] + if !known { + continue + } + word := joinWord(path, k) + used[word] = true + walkValue(obj[k], f.Type, word, used) + } + case reflect.Slice, reflect.Array: + if t.Elem().Kind() == reflect.Uint8 { + return + } + for _, item := range asList(v) { + walkValue(item, t.Elem(), path, used) + } + case reflect.Map: + obj, _ := v.(map[string]any) + for _, k := range sortedAnyKeys(obj) { + walkValue(obj[k], t.Elem(), path, used) + } + } +} + +func structFields(t reflect.Type) map[string]reflect.StructField { + out := map[string]reflect.StructField{} + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + name, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if name == "-" { + continue + } + if f.Anonymous && name == "" && deref(f.Type).Kind() == reflect.Struct { + for k, inner := range structFields(deref(f.Type)) { + if _, shadowed := out[k]; !shadowed { + out[k] = inner + } + } + continue + } + if !f.IsExported() { + continue + } + if name == "" { + name = f.Name + } + out[name] = f + } + return out +} + +func deref(t reflect.Type) reflect.Type { + for t.Kind() == reflect.Pointer { + t = t.Elem() + } + return t +} + +func joinWord(path, key string) string { + if path == "" { + return key + } + return path + "." + key +} + +func asList(v any) []any { + list, _ := v.([]any) + return list +} + +func sortedSet(set map[string]bool) []string { + out := make([]string, 0, len(set)) + for k := range set { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/modules/mesh-delivery-indexer/judge/needs_test.go b/modules/mesh-delivery-indexer/judge/needs_test.go new file mode 100644 index 000000000..81a7ed76c --- /dev/null +++ b/modules/mesh-delivery-indexer/judge/needs_test.go @@ -0,0 +1,74 @@ +package judge + +import ( + "slices" + "strings" + "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +func TestManifestNeeds(t *testing.T) { + for _, row := range []struct { + why, raw string + templates map[string]string + has, not []string + }{ + {"a module of its own account", `{"module":"g","version":"1","runs-as":"g"}`, nil, + []string{"directory-contents-owner", "word:runs-as"}, nil}, + {"a module with no account of its own", `{"module":"g","version":"1"}`, nil, + []string{"word:module"}, []string{"directory-contents-owner"}}, + {"a word the contract does not know", `{"module":"u","version":"1","newer-word":{"inside":1}}`, nil, + []string{"word:module"}, []string{"word:newer-word"}}, + {"a template naming a seat's reach", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","template":"files/d.json"}]}`, + map[string]string{"files/d.json": `{"x":"${seat:container-image-registry:reach}"}`}, + []string{"form:seat-reach"}, nil}, + {"a template writing the config as json", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","template":"files/c.json"}]}`, + map[string]string{"files/c.json": "${config-json}"}, []string{"form:config-json"}, []string{"form:config-lines"}}, + {"a resource with if-config", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","if-config":"x"}]}`, nil, + []string{"word:resources.if-config"}, nil}, + } { + needs, err := ModuleNeeds([]byte(row.raw), row.templates) + if err != nil { + t.Fatalf("%s: %v", row.why, err) + } + for _, n := range row.has { + if !slices.Contains(needs, n) { + t.Errorf("%s: needs %v, not %s", row.why, needs, n) + } + } + for _, n := range row.not { + if slices.Contains(needs, n) { + t.Errorf("%s: needs %v, naming %s", row.why, needs, n) + } + } + } + if _, err := ManifestNeeds([]byte("[]")); err == nil { + t.Error("bytes that are no JSON object: no error") + } +} + +// The manifest validator's reading of a manifest's keys equals ManifestReads' words (H-A-669): a word one names and the +// other does not fails here. +func TestTheValidatorReadsTheWordsManifestReadsNames(t *testing.T) { + var contract []string + for _, r := range catalogue.ManifestReads() { + if w, ok := strings.CutPrefix(r, catalogue.ReadWord); ok { + contract = append(contract, w) + } + } + if got := readerWords(); !slices.Equal(got, contract) { + t.Errorf("the validator reads %d words, ManifestReads names %d: only in the validator %v, only in ManifestReads %v", + len(got), len(contract), diff(got, contract), diff(contract, got)) + } +} + +func diff(a, b []string) []string { + var out []string + for _, x := range a { + if !slices.Contains(b, x) { + out = append(out, x) + } + } + return out +}