Merge pull request 'Fill a preference's ${setting:} from its manifest default (hq ADR 0262)' (#153) from feat/setting-defaults into main
This commit was merged in pull request #153.
This commit is contained in:
@@ -238,7 +238,7 @@ func (r Resolution) derivedFor(provision, as, consumer, local string, settings S
|
||||
"different things and nothing would compare them (novox/hq ADR 0202)",
|
||||
consumer, local, provision, m.Module, orNothing(sortedAnyKeys(names)))
|
||||
}
|
||||
settled, err := Settle(names, settings[m.Module])
|
||||
settled, err := Settle(names, WithDefaults(m, settings[m.Module]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s serving %s: %w", m.Module, provision, err)
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ func (b *DataBackup) UnmarshalJSON(raw []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&full); err != nil {
|
||||
return fmt.Errorf("a data item's backup is \"copy\", \"none\" or {dump, into}: %w", err)
|
||||
return fmt.Errorf("a data item's backup is \"copy\", \"none\" or {dump, into}: %w", typedUnknown(err))
|
||||
}
|
||||
*b = DataBackup{Dump: full.Dump, Into: full.Into}
|
||||
return nil
|
||||
|
||||
@@ -318,6 +318,10 @@ func (e *NotMadeError) Error() string {
|
||||
func (r Resolution) LeftOut(settings SettingsBy, adopted bool) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, m := range r.Modules {
|
||||
if why := UnknownFieldReason(m); why != "" {
|
||||
out[m.Module] = why
|
||||
continue
|
||||
}
|
||||
if err := JudgeSettings(m, settings[m.Module], adopted); err != nil {
|
||||
out[m.Module] = err.Error()
|
||||
}
|
||||
@@ -907,7 +911,7 @@ func (r Resolution) compose(with Rendering, owner map[string]string,
|
||||
// **An operator's value, from the assignment** (novox/hq ADR 0112, ADR 0155): what a
|
||||
// definition may not carry because it is true of one installation only. Filled from
|
||||
// the same layers a mergeable file takes, and refused when no layer set it.
|
||||
if err := settingInto(copied, with.Settings[m.Module], m.Module); err != nil {
|
||||
if err := settingInto(copied, WithDefaults(m, with.Settings[m.Module]), m.Module); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// **Placed before anything reads a path.** A pathless directory receives the path
|
||||
@@ -1495,7 +1499,7 @@ func (r Resolution) composed(m Manifest, to string, raw map[string]any, layers [
|
||||
// Overridden, not merged: a setting changes a key the contribution declares and adds none.
|
||||
// The provider reads the contribution as a contract, and a setting made for one of this
|
||||
// module's files is no part of it (novox/hq 04-ISSUES/173).
|
||||
values, err := overridden(raw, layers, what)
|
||||
values, err := overridden(raw, WithDefaults(m, layers), what)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
@@ -1926,7 +1930,7 @@ func (r Resolution) servedOnThisMachine(provision string, with Rendering) (map[s
|
||||
// one, so keep looking rather than concluding from the first.
|
||||
continue
|
||||
}
|
||||
settled, err := Settle(serves, with.Settings[m.Module])
|
||||
settled, err := Settle(serves, WithDefaults(m, with.Settings[m.Module]))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s serving %s: %w", m.Module, provision, err)
|
||||
}
|
||||
|
||||
@@ -153,7 +153,10 @@ func walk(node any, at string, meant map[string]bool, visit func(at, value strin
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if prose[k] || k == NamesOnPurpose || (at == "" && k == "module") {
|
||||
// Prose is a string a person reads. A key that is called `why` or `description` and holds
|
||||
// anything else — a setting of that name, whose default the mesh writes — is walked like any
|
||||
// other (novox/hq ADR 0262).
|
||||
if _, isString := v[k].(string); (prose[k] && isString) || k == NamesOnPurpose || (at == "" && k == "module") {
|
||||
continue
|
||||
}
|
||||
child := at + "." + k
|
||||
|
||||
@@ -197,7 +197,7 @@ func (i *OfferIdentity) UnmarshalJSON(raw []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&full); err != nil {
|
||||
return fmt.Errorf("an offer's identity is false or {max, in}: %w", err)
|
||||
return fmt.Errorf("an offer's identity is false or {max, in}: %w", typedUnknown(err))
|
||||
}
|
||||
*i = OfferIdentity{Max: full.Max, In: full.In}
|
||||
return nil
|
||||
@@ -316,7 +316,7 @@ func (o *Offer) UnmarshalJSON(raw []byte) error {
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&full); err != nil {
|
||||
return fmt.Errorf("a provided name is either a string or {name, scope, credential, reach, identity, "+
|
||||
"keeps-consumer-data}: %w", err)
|
||||
"keeps-consumer-data}: %w", typedUnknown(err))
|
||||
}
|
||||
o.Name, o.Scope, o.Credential, o.Reach, o.Identity = full.Name, full.Scope, full.Credential, full.Reach, full.Identity
|
||||
o.KeepsConsumerData = full.Keeps
|
||||
@@ -458,6 +458,19 @@ type Manifest struct {
|
||||
// (novox/hq ADR 0201). Not history — that is an event — and never a secret, sealed or not.
|
||||
State []StateDeclaration `json:"state,omitempty"`
|
||||
|
||||
// Settings are the defaults this module gives its settings (novox/hq ADR 0262): each key a file,
|
||||
// a contribution or a served fact asks for as `${setting:<key>}`, its default, and why that
|
||||
// default. Only a preference has one — a font size, a width, a number of workers — and a value
|
||||
// that is inherently the operator's (a domain, an identity, a secret) is declared nowhere here and
|
||||
// stays refused by name until a layer sets it. The mesh's layer, then the node's, override it.
|
||||
Settings map[string]SettingDeclaration `json:"settings,omitempty"`
|
||||
|
||||
// unknown is the first key this manifest has that this controller does not know, at any depth, when
|
||||
// it was read from the store (novox/hq ADR 0262): a manifest a newer controller registered.
|
||||
// ParseManifest refuses it; the store's catalogue still loads, and the module is left out of every
|
||||
// machine's declaration by name until the controller is updated (LeftOut).
|
||||
unknown string
|
||||
|
||||
// Data is every kind of data this module keeps — its own, by directory, and what it keeps for
|
||||
// its consumers, by provision — each with a class the mesh protects and watches it by (novox/hq
|
||||
// ADR 0233). One list: the backup holder's lines, the bindings that do not move, what an
|
||||
@@ -1178,7 +1191,13 @@ func ReceivedID(requirement string) string { return "received-" + requirement }
|
||||
type manifestFields Manifest
|
||||
|
||||
// UnmarshalJSON reads `secrets` in both of its shapes — a path, or an object of local names to
|
||||
// paths (ADR 0094) — and everything else exactly as the fields declare, unknown keys refused.
|
||||
// paths (ADR 0094) — and everything else exactly as the fields declare.
|
||||
//
|
||||
// **An unknown key is kept aside, not refused here** (novox/hq ADR 0262). Registration and the module
|
||||
// check refuse it, through ParseManifest. Reading the catalogue the store already holds does not: a
|
||||
// manifest registered under a newer controller carries a field an older one does not know, and a
|
||||
// strict read there failed the whole catalogue, and with it every plan and every send, the moment a
|
||||
// controller was rolled back. UnknownField says what was set aside.
|
||||
func (m *Manifest) UnmarshalJSON(raw []byte) error {
|
||||
var keys map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &keys); err != nil {
|
||||
@@ -1259,10 +1278,25 @@ func (m *Manifest) UnmarshalJSON(raw []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(rest))
|
||||
decoder.DisallowUnknownFields()
|
||||
var fields manifestFields
|
||||
unknown := ""
|
||||
if err := decoder.Decode(&fields); err != nil {
|
||||
return err
|
||||
if asUnknownField(err) == nil {
|
||||
return err
|
||||
}
|
||||
// Read without it where the key is at the top; where it is inside a block, the block's own
|
||||
// decoder refuses it again, and the manifest keeps its name and version alone. Either way the
|
||||
// module is left out of every declaration by name (LeftOut), so nothing runs on a part-read
|
||||
// manifest.
|
||||
unknown = err.Error()
|
||||
fields = manifestFields{}
|
||||
if json.Unmarshal(rest, &fields) != nil {
|
||||
fields = manifestFields{}
|
||||
_ = json.Unmarshal(keys["module"], &fields.Module)
|
||||
_ = json.Unmarshal(keys["version"], &fields.Version)
|
||||
}
|
||||
}
|
||||
*m = Manifest(fields)
|
||||
m.unknown = unknown
|
||||
if len(plain) > 0 {
|
||||
m.Secrets = plain
|
||||
}
|
||||
@@ -1366,6 +1400,10 @@ func SecretLocal(to, local string) string {
|
||||
return local
|
||||
}
|
||||
|
||||
// UnknownField is the first key a leniently read manifest had that this controller does not know, as
|
||||
// the JSON decoder words it, or "" when it had none (novox/hq ADR 0262).
|
||||
func (m Manifest) UnknownField() string { return m.unknown }
|
||||
|
||||
func ParseManifest(raw []byte) (Manifest, error) {
|
||||
var m Manifest
|
||||
// Strictly. **An unknown key is refused**, which is the discipline the host's declaration
|
||||
@@ -1377,7 +1415,12 @@ func ParseManifest(raw []byte) (Manifest, error) {
|
||||
// checking whether something is restricted will find that it is, and be wrong.
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&m); err != nil {
|
||||
err := decoder.Decode(&m)
|
||||
if err == nil && m.unknown != "" {
|
||||
// Kept aside by UnmarshalJSON for the stored catalogue's sake; registration refuses it.
|
||||
err = errors.New(m.unknown)
|
||||
}
|
||||
if err != nil {
|
||||
// A key that used to mean something says what it became. Refusing a renamed field with
|
||||
// "unknown field" is correct and unhelpful: whoever wrote it knew what they meant, and
|
||||
// the mesh knows what it is called now.
|
||||
@@ -1541,6 +1584,8 @@ func ParseManifest(raw []byte) (Manifest, error) {
|
||||
problems = append(problems, EventProblems(m)...)
|
||||
// And what it may call its state, and whose it may read (state.go, novox/hq ADR 0201).
|
||||
problems = append(problems, StateProblems(m)...)
|
||||
// And the defaults it gives its settings (setting_defaults.go, novox/hq ADR 0262).
|
||||
problems = append(problems, SettingProblems(m)...)
|
||||
wellFormed := true
|
||||
for _, c := range m.Claims {
|
||||
if !name.MatchString(c.Name) {
|
||||
@@ -2441,7 +2486,7 @@ func (o *OwnSecrets) UnmarshalJSON(raw []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&long); err != nil {
|
||||
return fmt.Errorf("own-secrets.%s: a path, or {\"path\", \"taken\", \"issued-by\"}: %w", name, err)
|
||||
return fmt.Errorf("own-secrets.%s: a path, or {\"path\", \"taken\", \"issued-by\"}: %w", name, typedUnknown(err))
|
||||
}
|
||||
out[name] = OwnSecret{Path: long.Path, Taken: long.Taken, IssuedBy: long.IssuedBy}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A preference has a default; the operator's own value has none (novox/hq ADR 0262, extending ADR
|
||||
// 0112 and taking the default half of ADR 0164).
|
||||
//
|
||||
// `${setting:<key>}` was refused whenever no layer set the key, and `settings set` refused a key no
|
||||
// file asked for yet. Together they meant a running module could never gain a setting: the file that
|
||||
// asks for it fails to compose until somebody sets it, and nobody can set it until the file asks.
|
||||
// A definition may now give a key a default, with why, when the value is a **preference** — a font
|
||||
// size, a width, a number of workers: something true of the software that a machine may tune. A
|
||||
// value that is inherently the operator's — a domain, a public name, an identity, a secret — gets no
|
||||
// default and stays refused by name until a layer sets it, which is what ADR 0112 and ADR 0155 were
|
||||
// written for.
|
||||
//
|
||||
// The default is the lowest layer. The mesh's layer, then the node's, override it. It fills only
|
||||
// `${setting:<key>}`: a mergeable file's content already is its defaults, and laying a default over
|
||||
// it would reach every mergeable file of the module (novox/hq issue 168).
|
||||
|
||||
// SettingDeclaration is one key's default, as the definition gives it.
|
||||
type SettingDeclaration struct {
|
||||
// Kind says what sort of value this is. `preference` is the only kind with a default; it is
|
||||
// stated rather than assumed so a reviewer sees the claim being made.
|
||||
Kind string `json:"kind"`
|
||||
// Default is the value when no layer sets the key: a string, a number or a boolean.
|
||||
Default any `json:"default"`
|
||||
// Why this default: one sentence for whoever wonders whether to change it.
|
||||
Why string `json:"why"`
|
||||
}
|
||||
|
||||
// KindPreference is the kind of a setting that may have a default.
|
||||
const KindPreference = "preference"
|
||||
|
||||
// DefaultLayer is what the layer of a module's own defaults is called where a value's source is said.
|
||||
// Only said: the layer is recognised by Layer.Default, never by this name, which a node may also have.
|
||||
const DefaultLayer = "default"
|
||||
|
||||
// meshWords are the settings keys the mesh reads itself; a module declares none of them.
|
||||
var meshWords = map[string]bool{
|
||||
PortsSetting: true, ExposeSetting: true, ReachSetting: true, EndpointsSetting: true,
|
||||
PlacesSetting: true, AccessesSetting: true, NetworksSetting: true,
|
||||
}
|
||||
|
||||
// operatorsOwn are the words that, as what a key's name is about, say its value is the operator's and
|
||||
// never a preference: a default for one would be the literal ADR 0112 removed from definitions.
|
||||
var operatorsOwn = map[string]bool{
|
||||
"domain": true, "host": true, "hostname": true, "servername": true, "fqdn": true, "zone": true,
|
||||
"realm": true, "tenant": true, "site": true, "timezone": true,
|
||||
"issuer": true, "url": true, "uri": true, "webhook": true, "origin": true, "dsn": true,
|
||||
"ip": true, "ipv4": true, "ipv6": true,
|
||||
"email": true, "mail": true, "phone": true, "address": true,
|
||||
"identity": true, "login": true, "user": true, "username": true, "account": true, "owner": true,
|
||||
"uid": true, "gid": true, "puid": true, "pgid": true,
|
||||
"password": true, "pass": true, "passwd": true, "passphrase": true, "secret": true, "token": true,
|
||||
"key": true, "apikey": true, "bearer": true, "cert": true, "credential": true,
|
||||
}
|
||||
|
||||
// operatorsCompounds are names of two words that are the operator's though neither word alone says so
|
||||
// at the end of a key: a client's identifier, and a name the world knows a site or server by.
|
||||
var operatorsCompounds = map[string]bool{
|
||||
"client-id": true, "site-name": true, "server-name": true, "public-name": true, "smtp-relay": true,
|
||||
}
|
||||
|
||||
// aboutAnAmount are first words that make a key about how many or whether, never about whom:
|
||||
// `max-tokens` is a number, `show-hostname` a switch.
|
||||
var aboutAnAmount = map[string]bool{
|
||||
"max": true, "min": true, "num": true, "count": true, "show": true, "hide": true, "enable": true,
|
||||
"disable": true, "use": true, "allow": true,
|
||||
}
|
||||
|
||||
// operatorsWord is what in a key's name says its value is the operator's, or "". A key is about its
|
||||
// last word — `url-timeout` is a timeout, `user-agent` an agent, `mail-domain` a domain — or its last two
|
||||
// as one of operatorsCompounds. A plural is read as its singular.
|
||||
func operatorsWord(key string) string {
|
||||
words := strings.FieldsFunc(key, func(r rune) bool { return r == '-' || r == '_' || r == '.' })
|
||||
if len(words) == 0 || (len(words) > 1 && aboutAnAmount[words[0]]) {
|
||||
return ""
|
||||
}
|
||||
for i, w := range words {
|
||||
if !operatorsOwn[w] && strings.HasSuffix(w, "s") && operatorsOwn[strings.TrimSuffix(w, "s")] {
|
||||
words[i] = strings.TrimSuffix(w, "s")
|
||||
}
|
||||
}
|
||||
if n := len(words); n > 1 {
|
||||
if pair := words[n-2] + "-" + words[n-1]; operatorsCompounds[pair] {
|
||||
return pair
|
||||
}
|
||||
}
|
||||
if last := words[len(words)-1]; operatorsOwn[last] {
|
||||
return last
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SettingProblems is every way a definition's setting defaults are wrong, in its own words.
|
||||
func SettingProblems(m Manifest) []string {
|
||||
if len(m.Settings) == 0 {
|
||||
return nil
|
||||
}
|
||||
used := settingKeysUsedBy(m)
|
||||
var problems []string
|
||||
for _, key := range sortedSettingKeys(m.Settings) {
|
||||
d := m.Settings[key]
|
||||
say := func(format string, args ...any) {
|
||||
problems = append(problems, fmt.Sprintf("%s's setting %q: ", m.Module, key)+fmt.Sprintf(format, args...))
|
||||
}
|
||||
if !settingRef.MatchString("${setting:" + key + "}") {
|
||||
say("not a usable key: lower-case letters, digits, dots, dashes and underscores")
|
||||
continue
|
||||
}
|
||||
if meshWords[key] {
|
||||
say("the mesh reads %q itself, and a module gives it no default", key)
|
||||
continue
|
||||
}
|
||||
if d.Kind != KindPreference {
|
||||
say("kind is %q, and only a %q has a default (novox/hq ADR 0262)", d.Kind, KindPreference)
|
||||
}
|
||||
if word := operatorsWord(key); word != "" {
|
||||
say("a key naming %q is the operator's value, and has no default — it is the "+
|
||||
"assignment's, never the definition's (novox/hq ADR 0112, ADR 0262)", word)
|
||||
}
|
||||
switch v := d.Default.(type) {
|
||||
case string:
|
||||
if strings.TrimSpace(v) == "" {
|
||||
say("an empty default is no default; give the value, or declare nothing")
|
||||
}
|
||||
case float64, bool:
|
||||
case nil:
|
||||
say("no default: a key without one is the operator's, and is not declared here")
|
||||
default:
|
||||
say("a default is a string, a number or a boolean, and this is %T", d.Default)
|
||||
}
|
||||
if strings.TrimSpace(d.Why) == "" {
|
||||
say("no why: say in one sentence why this default")
|
||||
}
|
||||
if !used[key] {
|
||||
say("nothing asks for ${setting:%s}, so the default reaches nothing", key)
|
||||
}
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
// Defaults is the layer a module's own defaults make, or nothing when it gives none.
|
||||
func Defaults(m Manifest) (Layer, bool) {
|
||||
if len(m.Settings) == 0 {
|
||||
return Layer{}, false
|
||||
}
|
||||
values := map[string]any{}
|
||||
for key, d := range m.Settings {
|
||||
if d.Default != nil {
|
||||
values[key] = d.Default
|
||||
}
|
||||
}
|
||||
return Layer{From: DefaultLayer, Values: values, Default: true}, len(values) > 0
|
||||
}
|
||||
|
||||
// WithDefaults is a module's layers with its defaults under them, for filling `${setting:<key>}`.
|
||||
func WithDefaults(m Manifest, layers []Layer) []Layer {
|
||||
d, has := Defaults(m)
|
||||
if !has {
|
||||
return layers
|
||||
}
|
||||
return append([]Layer{d}, layers...)
|
||||
}
|
||||
|
||||
// SettingSource is one key's effective value and the layer it came from.
|
||||
type SettingSource struct {
|
||||
Key string
|
||||
Value any
|
||||
// From is DefaultLayer, MeshWideLayer or the node's name.
|
||||
From string
|
||||
// FromDefault is whether the value is the module's default, whatever From reads.
|
||||
FromDefault bool
|
||||
// Default is the module's default, when it gives one.
|
||||
Default any
|
||||
HasDefault bool
|
||||
}
|
||||
|
||||
// Effective is every key a module gives a default or a layer sets, with its value and where it came
|
||||
// from: the default, then the mesh's layer, then the node's — later wins.
|
||||
func Effective(m Manifest, layers []Layer) []SettingSource {
|
||||
byKey := map[string]*SettingSource{}
|
||||
for key, d := range m.Settings {
|
||||
byKey[key] = &SettingSource{Key: key, Value: d.Default, From: DefaultLayer, FromDefault: true,
|
||||
Default: d.Default, HasDefault: true}
|
||||
}
|
||||
for _, layer := range layers {
|
||||
for key, v := range layer.Values {
|
||||
s, ok := byKey[key]
|
||||
if !ok {
|
||||
s = &SettingSource{Key: key}
|
||||
byKey[key] = s
|
||||
}
|
||||
s.Value, s.From, s.FromDefault = v, layer.From, layer.Default
|
||||
}
|
||||
}
|
||||
out := make([]SettingSource, 0, len(byKey))
|
||||
for _, s := range byKey {
|
||||
out = append(out, *s)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
|
||||
return out
|
||||
}
|
||||
|
||||
func sortedSettingKeys(in map[string]SettingDeclaration) []string {
|
||||
keys := make([]string, 0, len(in))
|
||||
for k := range in {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A preference has a default in the definition; the mesh's layer, then the node's, override it; a key
|
||||
// with a default is not stray; and a value that is the operator's still has none (novox/hq ADR 0262).
|
||||
|
||||
func notifier() Manifest {
|
||||
return Manifest{Module: "notifier",
|
||||
Settings: map[string]SettingDeclaration{
|
||||
"font-size": {Kind: KindPreference, Default: float64(10), Why: "readable at a scale of one"},
|
||||
"width": {Kind: KindPreference, Default: float64(250), Why: "fits a title of forty characters"},
|
||||
},
|
||||
Resources: []map[string]any{{"id": "configuration", "type": "file", "path": "/x/notifierrc",
|
||||
"content": "font = Inter ${setting:font-size}\nwidth = ${setting:width}\n"}},
|
||||
}
|
||||
}
|
||||
|
||||
func parsed(t *testing.T, m Manifest) error {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = ParseManifest(raw)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestAnUnsetPreferenceTakesItsDefault(t *testing.T) {
|
||||
m := notifier()
|
||||
for _, layers := range [][]Layer{nil, {{From: MeshWideLayer, Values: map[string]any{}}}} {
|
||||
file := map[string]any{}
|
||||
for k, v := range m.Resources[0] {
|
||||
file[k] = v
|
||||
}
|
||||
if err := settingInto(file, WithDefaults(m, layers), m.Module); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file["content"] != "font = Inter 10\nwidth = 250\n" {
|
||||
t.Fatalf("filled as %q", file["content"])
|
||||
}
|
||||
}
|
||||
if err := JudgeSettings(m, nil, false); err != nil {
|
||||
t.Fatalf("a module whose every key has a default does not compose with no layer: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheNodeOverTheMeshOverTheDefault(t *testing.T) {
|
||||
m := notifier()
|
||||
layers := []Layer{
|
||||
{From: MeshWideLayer, Values: map[string]any{"width": float64(300)}},
|
||||
{From: "laptop", Values: map[string]any{"font-size": float64(13), "width": float64(340)}},
|
||||
}
|
||||
file := map[string]any{"type": "file", "content": m.Resources[0]["content"]}
|
||||
if err := settingInto(file, WithDefaults(m, layers), m.Module); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file["content"] != "font = Inter 13\nwidth = 340\n" {
|
||||
t.Fatalf("filled as %q", file["content"])
|
||||
}
|
||||
file = map[string]any{"type": "file", "content": m.Resources[0]["content"]}
|
||||
if err := settingInto(file, WithDefaults(m, layers[:1]), m.Module); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file["content"] != "font = Inter 10\nwidth = 300\n" {
|
||||
t.Fatalf("the mesh's layer over the default filled as %q", file["content"])
|
||||
}
|
||||
}
|
||||
|
||||
// Composed for a machine, the way a push writes it: the default reaches the file, and the node's
|
||||
// layer overrides it.
|
||||
func TestAComposedMachineGetsTheDefaultAndTheNodesValue(t *testing.T) {
|
||||
r := anAdoptedAnchor()
|
||||
r.Modules = append(r.Modules, notifier())
|
||||
with := anchorRendering(false)
|
||||
composed, err := r.Compose(with)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if why, left := composed.LeftOut["notifier"]; left {
|
||||
t.Fatalf("the notifier was left out: %s", why)
|
||||
}
|
||||
if c := byID(composed.Resources)["notifier.configuration"]["content"]; c != "font = Inter 10\nwidth = 250\n" {
|
||||
t.Fatalf("composed with no layer as %q", c)
|
||||
}
|
||||
with.Settings["notifier"] = []Layer{{From: "anchor", Values: map[string]any{"font-size": float64(13)}}}
|
||||
if composed, err = r.Compose(with); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := byID(composed.Resources)["notifier.configuration"]["content"]; c != "font = Inter 13\nwidth = 250\n" {
|
||||
t.Fatalf("composed with the node's font size as %q", c)
|
||||
}
|
||||
}
|
||||
|
||||
// Setting a key the module gives a default is not refused as reaching nothing: it overrides the
|
||||
// default, which is how a running module gains a setting with no gap between.
|
||||
func TestAKeyWithADefaultIsNotStray(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Resources[0]["content"] = "font = Inter ${setting:font-size}\nwidth = ${setting:width}\n"
|
||||
stray := UnusedSettings(m, []Layer{{From: "laptop", Values: map[string]any{"font-size": float64(13), "colour": "red"}}})
|
||||
joined := strings.Join(stray, "; ")
|
||||
if strings.Contains(joined, `"font-size"`) || !strings.Contains(joined, `"colour"`) {
|
||||
t.Fatalf("stray: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// A default fills ${setting:…} only: it never becomes a key of a mergeable file (issue 168).
|
||||
func TestADefaultIsNotMergedIntoAJSONFile(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Resources = append(m.Resources, map[string]any{"id": "other", "type": "file", "path": "/x/other.json",
|
||||
"merge": MergeJSON, "content": `{"keep": 1}`})
|
||||
out, err := ApplySettings(m.Resources[1], WithDefaults(m, nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(out["content"].(string), "font-size") {
|
||||
t.Fatalf("a default reached a mergeable file: %s", out["content"])
|
||||
}
|
||||
}
|
||||
|
||||
// A value that is the operator's has no default: no layer setting it is refused by name, as before.
|
||||
func TestAnOperatorsValueWithoutADefaultIsStillRefused(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Resources[0]["content"] = "font = Inter ${setting:font-size}\nwidth = ${setting:width}\nfrom = ${setting:domain}\n"
|
||||
err := JudgeSettings(m, nil, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "${setting:domain}") {
|
||||
t.Fatalf("judged %v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "font-size") {
|
||||
t.Fatalf("a default was named as set today: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheParserTakesAPreferenceAndRefusesTheRest(t *testing.T) {
|
||||
if err := parsed(t, notifier()); err != nil {
|
||||
t.Fatalf("a preference with a default was refused: %v", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
key string
|
||||
d SettingDeclaration
|
||||
refuse string
|
||||
}{
|
||||
{"no kind", "font-size", SettingDeclaration{Default: float64(10), Why: "x"}, `only a "preference" has a default`},
|
||||
{"another kind", "font-size", SettingDeclaration{Kind: "operator", Default: float64(10), Why: "x"}, `only a "preference"`},
|
||||
{"no default", "font-size", SettingDeclaration{Kind: KindPreference, Why: "x"}, "no default"},
|
||||
{"an empty default", "font-size", SettingDeclaration{Kind: KindPreference, Default: " ", Why: "x"}, "an empty default"},
|
||||
{"an object", "font-size", SettingDeclaration{Kind: KindPreference, Default: map[string]any{"a": 1.0}, Why: "x"}, "a string, a number or a boolean"},
|
||||
{"no why", "font-size", SettingDeclaration{Kind: KindPreference, Default: float64(10)}, "no why"},
|
||||
{"the operator's", "mail-domain", SettingDeclaration{Kind: KindPreference, Default: "example.tld", Why: "x"}, "is the operator's value"},
|
||||
{"a secret", "api-token", SettingDeclaration{Kind: KindPreference, Default: "x", Why: "x"}, "is the operator's value"},
|
||||
{"the mesh's word", PortsSetting, SettingDeclaration{Kind: KindPreference, Default: float64(1), Why: "x"}, "the mesh reads"},
|
||||
{"read by nothing", "height", SettingDeclaration{Kind: KindPreference, Default: float64(300), Why: "x"}, "reaches nothing"},
|
||||
} {
|
||||
m := notifier()
|
||||
m.Resources[0]["content"] = m.Resources[0]["content"].(string) + "x = ${setting:" + c.key + "}\n"
|
||||
if c.name == "read by nothing" {
|
||||
m.Resources[0]["content"] = "font = Inter ${setting:font-size}\nwidth = ${setting:width}\n"
|
||||
}
|
||||
m.Settings[c.key] = c.d
|
||||
err := parsed(t, m)
|
||||
if err == nil || !strings.Contains(err.Error(), c.refuse) {
|
||||
t.Errorf("%s: parsed %v, want %q", c.name, err, c.refuse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryValueSaysWhereItCameFrom(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Resources[0]["content"] = m.Resources[0]["content"].(string) + "x = ${setting:position}\n"
|
||||
got := Effective(m, []Layer{
|
||||
{From: MeshWideLayer, Values: map[string]any{"width": float64(300), "position": "top-right"}},
|
||||
{From: "laptop", Values: map[string]any{"font-size": float64(13)}},
|
||||
})
|
||||
want := map[string]string{"font-size": "laptop", "position": MeshWideLayer, "width": MeshWideLayer}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("effective: %+v", got)
|
||||
}
|
||||
for _, s := range got {
|
||||
if s.From != want[s.Key] {
|
||||
t.Errorf("%s from %q, want %q", s.Key, s.From, want[s.Key])
|
||||
}
|
||||
}
|
||||
if got[0].Key != "font-size" || got[0].Value != float64(13) || got[0].Default != float64(10) {
|
||||
t.Fatalf("font-size: %+v", got[0])
|
||||
}
|
||||
only := Effective(m, nil)
|
||||
if only[0].From != DefaultLayer || only[0].Value != float64(10) {
|
||||
t.Fatalf("with no layer: %+v", only)
|
||||
}
|
||||
}
|
||||
|
||||
// A node may be called `default`. Its layer is a node's like any other: it overrides the module's
|
||||
// default, it merges into a mergeable file, and it is named among what is set.
|
||||
func TestANodeCalledDefaultIsANodesLayer(t *testing.T) {
|
||||
m := notifier()
|
||||
node := []Layer{{From: DefaultLayer, Values: map[string]any{"font-size": float64(13)}}}
|
||||
file := map[string]any{"type": "file", "content": m.Resources[0]["content"]}
|
||||
if err := settingInto(file, WithDefaults(m, node), m.Module); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if file["content"] != "font = Inter 13\nwidth = 250\n" {
|
||||
t.Fatalf("the node called default was dropped: %q", file["content"])
|
||||
}
|
||||
out, err := ApplySettings(map[string]any{"id": "j", "type": "file", "merge": MergeJSON, "content": `{}`}, node)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out["content"].(string), `"font-size": 13`) {
|
||||
t.Fatalf("the node called default did not merge: %s", out["content"])
|
||||
}
|
||||
if got := Effective(m, node); got[0].FromDefault || got[0].Value != float64(13) {
|
||||
t.Fatalf("the node's value read as the default: %+v", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
// The operator's own value is told by what a key's name is about: its last word, or its last two as
|
||||
// a known compound; a plural as its singular; and never a number or a switch.
|
||||
func TestAKeyIsTheOperatorsByWhatItIsAbout(t *testing.T) {
|
||||
for _, key := range []string{"max-tokens", "show-hostname", "ghost-opacity", "users-per-page", "mailbox-size",
|
||||
"font-size", "width", "keyboard-delay", "ipv6-preferred", "client-width", "user-agent", "url-timeout",
|
||||
"site-title", "cert-renewal-days", "name", "font-name"} {
|
||||
if w := operatorsWord(key); w != "" {
|
||||
t.Errorf("%s read as the operator's (%s)", key, w)
|
||||
}
|
||||
}
|
||||
for key, word := range map[string]string{"mail-domain": "domain", "api-key": "key", "admin-password": "password",
|
||||
"oauth-client-id": "client-id", "db-dsn": "dsn", "public-ip": "ip", "puid": "puid", "dns-zone": "zone",
|
||||
"webhook": "webhook", "notify_phone": "phone", "cors.origin": "origin", "smtp-pass": "pass",
|
||||
"backup-passphrase": "passphrase", "data-owner": "owner", "fqdn": "fqdn", "tenant": "tenant", "host": "host",
|
||||
"allowed-hosts": "host", "admin-emails": "email", "tokens": "token", "hostname": "hostname",
|
||||
"apikey": "apikey", "servername": "servername", "tls-cert": "cert", "site": "site", "timezone": "timezone",
|
||||
"bearer": "bearer", "bind-ipv4": "ipv4", "listen-ipv6": "ipv6", "site-name": "site-name",
|
||||
"server-name": "server-name", "public-name": "public-name", "smtp-relay": "smtp-relay"} {
|
||||
if w := operatorsWord(key); w != word {
|
||||
t.Errorf("%s: read %q, want %q", key, w, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A default is a value the mesh writes, so the installation check reads it, even under a setting
|
||||
// called `description` or `why`; a setting's own why is prose and is not read.
|
||||
func TestTheInstallationCheckReadsADefault(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Settings["relay"] = SettingDeclaration{Kind: KindPreference, Default: "relay.acme.be", Why: "as at relay.acme.be"}
|
||||
m.Settings["description"] = SettingDeclaration{Kind: KindPreference, Default: "notes.acme.be", Why: "x"}
|
||||
problems := strings.Join(InstallationProblems(m), "; ")
|
||||
for _, want := range []string{"relay.acme.be at settings.relay.default", "notes.acme.be at settings.description.default"} {
|
||||
if !strings.Contains(problems, want) {
|
||||
t.Errorf("not reported: %q in %s", want, problems)
|
||||
}
|
||||
}
|
||||
if strings.Contains(problems, "settings.relay.why") {
|
||||
t.Errorf("a why was read as a value: %s", problems)
|
||||
}
|
||||
}
|
||||
|
||||
// A default fills ${setting:…} in what a module contributes and serves, and never replaces a value a
|
||||
// contribution states itself.
|
||||
func TestADefaultFillsAContributionAndAServedFactButNotALiteral(t *testing.T) {
|
||||
m := notifier()
|
||||
m.Settings["site-title"] = SettingDeclaration{Kind: KindPreference, Default: "Notes", Why: "x"}
|
||||
contribution := map[string]any{"title": "${setting:site-title}", "width": "fixed", "port": float64(8080)}
|
||||
got, err := overridden(contribution, WithDefaults(m, nil), "a contribution")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["title"] != "Notes" || got["width"] != "fixed" {
|
||||
t.Fatalf("contribution: %v", got)
|
||||
}
|
||||
got, err = overridden(contribution, WithDefaults(m, []Layer{{From: "laptop", Values: map[string]any{"width": "wide"}}}), "a contribution")
|
||||
if err != nil || got["width"] != "wide" {
|
||||
t.Fatalf("a node's value did not override a contribution's own key: %v %v", got, err)
|
||||
}
|
||||
served, err := Settle(map[string]any{"name": "${setting:site-title}"}, WithDefaults(m, nil))
|
||||
if err != nil || served["name"] != "Notes" {
|
||||
t.Fatalf("served: %v %v", served, err)
|
||||
}
|
||||
if _, err := Settle(map[string]any{"name": "${setting:site-title}"}, nil); err == nil {
|
||||
t.Fatal("a served fact without the defaults was filled")
|
||||
}
|
||||
}
|
||||
|
||||
// A stored manifest with a key this controller does not know, at the top or inside any block, is read
|
||||
// and its module is left out of every declaration by name; the rest of the catalogue is read; the module
|
||||
// check refuses it. One case per block whose decoder wraps the decoder's words in its own.
|
||||
func TestAStoredManifestWithAnUnknownKeyIsLeftOutAndRegistrationRefusesIt(t *testing.T) {
|
||||
for where, raw := range map[string]string{
|
||||
"the top": `{"module": "later", "version": "2", "a-field-from-later": {"x": 1}}`,
|
||||
"a state": `{"module": "later", "version": "2", "state": [{"name": "s", "a-field-from-later": 1}]}`,
|
||||
"a provided name": `{"module": "later", "version": "2", "provides": [{"name": "p", "a-field-from-later": 1}]}`,
|
||||
"an offer's identity": `{"module": "later", "version": "2", "provides": [{"name": "p", "identity": {"in": "x", "a-field-from-later": 1}}]}`,
|
||||
"a backup": `{"module": "later", "version": "2", "data": {"own": [{"id": "d", "path": "${dir:d}", "class": "valuable", "backup": {"dump": "x", "into": "y", "a-field-from-later": 1}}]}}`,
|
||||
"an own secret": `{"module": "later", "version": "2", "own-secrets": {"s": {"path": "/x", "a-field-from-later": 1}}}`,
|
||||
"a seat's verb": `{"module": "later", "version": "2", "seats": [{"name": "later-seat", "serves": [{"name": "v", "a-field-from-later": 1}]}]}`,
|
||||
} {
|
||||
var m Manifest
|
||||
if err := json.Unmarshal([]byte(raw), &m); err != nil {
|
||||
t.Errorf("%s: the stored manifest was not read: %v", where, err)
|
||||
continue
|
||||
}
|
||||
if m.Module != "later" || m.Version != "2" || !strings.Contains(m.UnknownField(), `"a-field-from-later"`) {
|
||||
t.Errorf("%s: read as %q %q, unknown %q", where, m.Module, m.Version, m.UnknownField())
|
||||
continue
|
||||
}
|
||||
if where != "the top" && !strings.Contains(m.UnknownField(), ": json: unknown field") {
|
||||
t.Errorf("%s: the block's decoder did not say it: %q", where, m.UnknownField())
|
||||
}
|
||||
left := Resolution{Node: "laptop", Modules: []Manifest{m, notifier()}}.LeftOut(nil, false)
|
||||
if why := left["later"]; !strings.Contains(why, "uses a field this controller does not know") ||
|
||||
!strings.Contains(why, "a-field-from-later") {
|
||||
t.Errorf("%s: not left out by name: %v", where, left)
|
||||
}
|
||||
if _, notifierLeft := left["notifier"]; notifierLeft {
|
||||
t.Errorf("%s: another module was left out with it: %v", where, left)
|
||||
}
|
||||
if _, err := ParseManifest([]byte(raw)); err == nil || !strings.Contains(err.Error(), "a-field-from-later") {
|
||||
t.Errorf("%s: the module check took it: %v", where, err)
|
||||
}
|
||||
}
|
||||
var known Manifest
|
||||
if err := json.Unmarshal([]byte(`{"module": "now", "state": [{"name": "s"}]}`), &known); err != nil || known.UnknownField() != "" {
|
||||
t.Fatalf("a known manifest: %v %q", err, known.UnknownField())
|
||||
}
|
||||
// A malformed manifest is still refused: only an unknown key is read past.
|
||||
var bad Manifest
|
||||
if err := json.Unmarshal([]byte(`{"module": "bad", "state": [{"name": 3}]}`), &bad); err == nil {
|
||||
t.Fatal("a malformed stored manifest was read")
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,9 @@ func settingsUsed(content string) []string {
|
||||
|
||||
// settingInto fills a file's ${setting:…} placeholders from the layers over a module.
|
||||
//
|
||||
// The last layer setting a key wins, which is the node's over the mesh's — the same order settle
|
||||
// applies to a mergeable file. A value that is not a string is written the way a program would read
|
||||
// The last layer setting a key wins, which is the node's over the mesh's over the module's own
|
||||
// default (novox/hq ADR 0262) — the same order settle applies to a mergeable file. The caller lays
|
||||
// the defaults under the layers with WithDefaults. A value that is not a string is written the way a program would read
|
||||
// it (a number without a trailing .000000, a boolean as true/false).
|
||||
func settingInto(resource map[string]any, layers []Layer, module string) error {
|
||||
if fmt.Sprint(resource["type"]) != "file" {
|
||||
@@ -56,7 +57,8 @@ func settingInto(resource map[string]any, layers []Layer, module string) error {
|
||||
if !set {
|
||||
return fmt.Errorf(
|
||||
"%s has a file that says ${setting:%s}, and nothing sets %q for it — an operator's "+
|
||||
"value is the assignment's, never the definition's (novox/hq ADR 0112): "+
|
||||
"value is the assignment's, never the definition's (novox/hq ADR 0112), and only a "+
|
||||
"preference has a default in the definition (ADR 0262): "+
|
||||
"`settings set %s <file>` with {%q: …}%s",
|
||||
module, key, key, module, key, orNoSettings(layers))
|
||||
}
|
||||
@@ -80,6 +82,9 @@ func settingValue(layers []Layer, key string) (any, bool) {
|
||||
func orNoSettings(layers []Layer) string {
|
||||
var keys []string
|
||||
for _, l := range layers {
|
||||
if l.Default {
|
||||
continue
|
||||
}
|
||||
for k := range l.Values {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ type Layer struct {
|
||||
// Where these came from, for saying which layer set a value.
|
||||
From string
|
||||
Values map[string]any
|
||||
// Default marks the layer a module's own defaults make (novox/hq ADR 0262). Marked rather than
|
||||
// recognised by From, which is a node's name for a node's layer, and a node may be called anything.
|
||||
Default bool
|
||||
}
|
||||
|
||||
// ApplySettings produces a resource's final content from the module's own and the layers over it.
|
||||
@@ -114,7 +117,7 @@ func overridden(base map[string]any, layers []Layer, what string) (map[string]an
|
||||
values[key] = value
|
||||
}
|
||||
}
|
||||
kept = append(kept, Layer{From: layer.From, Values: values})
|
||||
kept = append(kept, Layer{From: layer.From, Values: values, Default: layer.Default})
|
||||
}
|
||||
merged, err := settle(base, kept, nil, what)
|
||||
if err != nil {
|
||||
@@ -151,6 +154,12 @@ func settle(base map[string]any, layers []Layer, protected map[string]bool, what
|
||||
map[string]any, error) {
|
||||
merged := deepCopy(base)
|
||||
for _, layer := range layers {
|
||||
if layer.Default {
|
||||
// A module's own defaults fill ${setting:<key>} only (novox/hq ADR 0262). A mergeable
|
||||
// file's content already is its defaults, and a contribution or served fact declares its
|
||||
// own; laid on here, a default would reach every mergeable file of its module (issue 168).
|
||||
continue
|
||||
}
|
||||
for key, value := range layer.Values {
|
||||
if key == PortsSetting {
|
||||
// Where the machine puts a port is the mesh's to apply, not a value for a file or
|
||||
@@ -224,6 +233,11 @@ func UnusedSettings(m Manifest, layers []Layer) []string {
|
||||
}
|
||||
|
||||
lands := settingKeysUsedBy(m)
|
||||
// A key the module gives a default reaches what asks for it (novox/hq ADR 0262): setting it
|
||||
// overrides the default, which is how a running module gains a setting without a gap between.
|
||||
for key := range m.Settings {
|
||||
lands[key] = true
|
||||
}
|
||||
for _, values := range m.Contributes {
|
||||
for key := range values {
|
||||
lands[key] = true
|
||||
@@ -420,7 +434,7 @@ func JudgeSettings(m Manifest, layers []Layer, adopted bool) error {
|
||||
for k, v := range settled {
|
||||
copied[k] = v
|
||||
}
|
||||
if err := settingInto(copied, layers, m.Module); err != nil {
|
||||
if err := settingInto(copied, WithDefaults(m, layers), m.Module); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ func (s *StateDeclaration) UnmarshalJSON(raw []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(trimmed))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&full); err != nil {
|
||||
return fmt.Errorf("a state is either a name or {name, history, ttl-seconds, per-machine}: %w", err)
|
||||
return fmt.Errorf("a state is either a name or {name, history, ttl-seconds, per-machine}: %w", typedUnknown(err))
|
||||
}
|
||||
*s = StateDeclaration(full)
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// A key this controller does not know, in a manifest (novox/hq ADR 0262).
|
||||
//
|
||||
// Registration refuses it, as it always has. A manifest the store already holds was registered by a newer
|
||||
// controller, and is read by this one after a rollback: refusing it there failed the whole catalogue, and
|
||||
// with it every plan and every send. Dropping the key silently would be worse — a module running without
|
||||
// something its manifest says. So the manifest is read, the module is left out of every machine's
|
||||
// declaration by name, and the controller raises a condition until it is updated.
|
||||
|
||||
// UnknownFieldError is a key a manifest has that this controller does not know, wherever it is: at the
|
||||
// top of the manifest or inside a block (a state, an offer, a data item's backup, an own secret, a verb).
|
||||
// Typed, because the blocks' decoders wrap the decoder's words in their own.
|
||||
type UnknownFieldError struct {
|
||||
Field string
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *UnknownFieldError) Error() string { return e.err.Error() }
|
||||
func (e *UnknownFieldError) Unwrap() error { return e.err }
|
||||
|
||||
// unknownFieldText is how the JSON decoder words a key its target does not have.
|
||||
var unknownFieldText = regexp.MustCompile(`^json: unknown field "([^"]*)"$`)
|
||||
|
||||
// typedUnknown is err as an UnknownFieldError when it is the decoder refusing an unknown key, else err.
|
||||
func typedUnknown(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if m := unknownFieldText.FindStringSubmatch(err.Error()); m != nil {
|
||||
return &UnknownFieldError{Field: m[1], err: err}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// asUnknownField is the unknown key err is about, at any depth, or nil.
|
||||
func asUnknownField(err error) *UnknownFieldError {
|
||||
var u *UnknownFieldError
|
||||
if errors.As(typedUnknown(err), &u) {
|
||||
return u
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnknownFieldReason is why a module whose stored manifest has a key this controller does not know is
|
||||
// left out of a machine's declaration, or "" when it has none.
|
||||
func UnknownFieldReason(m Manifest) string {
|
||||
if m.unknown == "" {
|
||||
return ""
|
||||
}
|
||||
return m.Module + " uses a field this controller does not know (" + m.unknown + "); it is left out " +
|
||||
"until the controller is updated (novox/hq ADR 0262)"
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func (v *Verb) UnmarshalJSON(raw []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(trimmed))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&p); err != nil {
|
||||
return fmt.Errorf("a served verb is a name or {name, description, input, output}: %w", err)
|
||||
return fmt.Errorf("a served verb is a name or {name, description, input, output}: %w", typedUnknown(err))
|
||||
}
|
||||
if p.Name == "" {
|
||||
return fmt.Errorf("a served verb has no name: %s", trimmed)
|
||||
@@ -249,19 +249,24 @@ var ControllerVerbs = []Verb{
|
||||
}, nil, "adopted"),
|
||||
Replaces: []string{"mesh-controller token issue", "wg set"}},
|
||||
{Name: "settings", Description: "Read or set what an assignment is configured with: a module's settings for the whole " +
|
||||
"mesh, or for one machine. Without values or clear, answers the layer as it stands — read it before setting it; " +
|
||||
"mesh, or for one machine. Without values or clear, answers the layer as it stands — read it before setting it — " +
|
||||
"then every value the module gives a default or a layer sets, with where it comes from: the module's default, " +
|
||||
"the mesh, or the machine (novox/hq ADR 0262); with list \"preferences\", or with no module, every " +
|
||||
"module's preferences and each machine's value; " +
|
||||
"with history, the layers it replaced. Setting replaces that layer whole and answers each key it adds (+), " +
|
||||
"changes (~) and removes (-); a set that would remove a key is refused unless replace says it is meant " +
|
||||
"(novox/hq ADR 0217). Takes effect at the next push. With clear, removes the layer and the module is back to " +
|
||||
"what its definition says; a cleared or replaced layer is kept in the history.",
|
||||
Input: schema(map[string]string{
|
||||
"module": "the module's name",
|
||||
"module": "the module's name; with list, only that module's",
|
||||
"values": "the settings as a JSON object, for set",
|
||||
"node": "one machine; the whole mesh when absent",
|
||||
"clear": "\"true\" to remove the layer instead of setting it; not with values",
|
||||
"replace": "\"true\": with values, the set is meant to remove the keys the layer had and it does not name",
|
||||
"history": "\"true\": without values or clear, the layers this one replaced, the latest first",
|
||||
}, []string{"module"}, "clear", "replace", "history")},
|
||||
"list": "\"preferences\": every module's preferences — key, default and why — and the value on each " +
|
||||
"machine it is assigned to with where it comes from; module and node narrow it (novox/hq ADR 0262)",
|
||||
}, nil, "clear", "replace", "history")},
|
||||
{Name: "command", Description: "Run one command line of the controller's own, as you would type it at its " +
|
||||
"shell — `node account g14 jochen`, `node show ace`, `module list` — and answer what it printed. The " +
|
||||
"generic verb beside the named ones (novox/hq ADR 0154): everything the binary can do, without a verb " +
|
||||
|
||||
Reference in New Issue
Block a user