Files
mesh-delivery/modules/mesh-delivery-indexer/judge/needs.go
T

361 lines
10 KiB
Go

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, `${<name>:…}`: 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
}