diff --git a/checks/environment/main.go b/checks/environment/main.go index e8cd65a69..2ffb4b89a 100644 --- a/checks/environment/main.go +++ b/checks/environment/main.go @@ -77,6 +77,7 @@ func Check(root string) (map[string]map[string][]string, error) { } set := map[string]bool{} setBy(manifest, set) + settingWords(manifest, set) reads := map[string]map[string]bool{} consts := map[string]map[string]string{} // directory -> constant -> word var goFiles []string @@ -180,6 +181,17 @@ func setBy(v any, set map[string]bool) { } } +// settingWords collects the words the node-engine composes for every setting the manifest's `config` declares, +// MESH_CONFIG_, the key upper-cased with '-' and '.' as '_', into the module's processes and its tool runner slice +// alike (design 47 H2 §781; H-A-370, H-A-400 (2)). +func settingWords(v any, set map[string]bool) { + m, _ := v.(map[string]any) + config, _ := m["config"].(map[string]any) + for key := range config { + set["MESH_CONFIG_"+strings.NewReplacer("-", "_", ".", "_").Replace(strings.ToUpper(key))] = true + } +} + // Listed is the list's ` ` lines; a line starting with # and a blank line are not entries. func Listed(path string) (map[string]bool, error) { f, err := os.Open(path) diff --git a/checks/environment/main_test.go b/checks/environment/main_test.go index f79842cd1..fd69078e7 100644 --- a/checks/environment/main_test.go +++ b/checks/environment/main_test.go @@ -32,13 +32,14 @@ func module(t *testing.T, root, name, manifest string, files map[string]string) // not; tests, node_modules and dist are not read. func TestAWordReadThatNothingSetsIsFound(t *testing.T) { root := t.TempDir() - module(t, root, "reader", `{"module":"reader","build":{"artifacts":[{"name":"tools","env":{"MESH_SET":"x"}}]},`+ + module(t, root, "reader", `{"module":"reader","config":{"ask-taken-bound":{"type":"string"}},"build":{"artifacts":[{"name":"tools","env":{"MESH_SET":"x"}}]},`+ `"resources":[{"id":"p","type":"process","environment":{"variables":{"MESH_VARIABLE":"y"}}}]}`, map[string]string{ - "cmd/a/main.go": `package main; const reach = "MESH_REACH"; var _ = os.Getenv(reach); var _ = os.Getenv("MESH_SET")`, - "cmd/a/other.go": `package main; var _, _ = os.LookupEnv("MESH_LITERAL"); var _ = os.Getenv("MESH_MODULE")`, - "cmd/a/write.go": `package main; var _ = []string{"MESH_WRITTEN_FOR_A_CHILD=1"}`, - "cmd/a/a_test.go": `package main; var _ = os.Getenv("MESH_IN_A_TEST")`, - "client.ts": `const a = process.env.MESH_TS ?? "d"; const b = env["MESH_BRACKET"]; const c = env.MESH_VARIABLE;`, + "cmd/a/main.go": `package main; const reach = "MESH_REACH"; var _ = os.Getenv(reach); var _ = os.Getenv("MESH_SET")`, + "cmd/a/other.go": `package main; var _, _ = os.LookupEnv("MESH_LITERAL"); var _ = os.Getenv("MESH_MODULE")`, + "cmd/a/write.go": `package main; var _ = []string{"MESH_WRITTEN_FOR_A_CHILD=1"}`, + "cmd/a/a_test.go": `package main; var _ = os.Getenv("MESH_IN_A_TEST")`, + // 47 H2 §781, H-A-370: a declared setting's word, which the node-engine composes; one undeclared is set by nothing. + "client.ts": `const a = process.env.MESH_TS ?? "d"; const b = env["MESH_BRACKET"]; const c = env.MESH_VARIABLE; const d = env.MESH_CONFIG_ASK_TAKEN_BOUND; const e = env.MESH_CONFIG_UNDECLARED;`, "files/env": "MESH_FROM_FILE=${config:x}\n", "index.ts": `const f = env.MESH_FROM_FILE;`, "test/x.test.ts": `env.MESH_IN_A_TEST_DIR`, @@ -50,16 +51,17 @@ func TestAWordReadThatNothingSetsIsFound(t *testing.T) { t.Fatal(err) } want := map[string]map[string][]string{"reader": { - "MESH_REACH": {"cmd/a/main.go"}, - "MESH_LITERAL": {"cmd/a/other.go"}, - "MESH_TS": {"client.ts"}, - "MESH_BRACKET": {"client.ts"}, + "MESH_REACH": {"cmd/a/main.go"}, + "MESH_LITERAL": {"cmd/a/other.go"}, + "MESH_TS": {"client.ts"}, + "MESH_BRACKET": {"client.ts"}, + "MESH_CONFIG_UNDECLARED": {"client.ts"}, }} if !reflect.DeepEqual(got, want) { t.Fatalf("found %v, want %v", got, want) } refused, stale := Judge(got, map[string]bool{"reader MESH_REACH": true, "reader MESH_GONE": true}) - if !reflect.DeepEqual(refused, []string{"reader MESH_BRACKET", "reader MESH_LITERAL", "reader MESH_TS"}) || + if !reflect.DeepEqual(refused, []string{"reader MESH_BRACKET", "reader MESH_CONFIG_UNDECLARED", "reader MESH_LITERAL", "reader MESH_TS"}) || !reflect.DeepEqual(stale, []string{"reader MESH_GONE"}) { t.Errorf("refused %v, stale %v", refused, stale) } diff --git a/checks/failurekit/failurekit.go b/checks/failurekit/failurekit.go index e46f8cad7..561138846 100644 --- a/checks/failurekit/failurekit.go +++ b/checks/failurekit/failurekit.go @@ -5,7 +5,7 @@ // exempt from that, and said so. Every build module, test step or not, must also hold a test that calls // conformance.LeftRunning with its own start sweep, so a step a previous process left running is ended at its start // (issue 1890), and one that calls conformance.Passing, so a step whose network did not answer is said as a transport fault -// (issue 1748). Its manifest asks the capability seat-settle-delay (ADR 0664 §5). +// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24). Its manifest asks the capability seat-settle-delay (ADR 0664 §5). package failurekit import ( @@ -91,6 +91,25 @@ func Judge(root string) ([]Judged, error) { refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.LeftRunning "+ "(mesh-build-go buildstep/conformance): run the kit's left-running case with the module's own start sweep (issue 1890)", seat)) } + // A-489b: every build module is asked pipeline steps, so every one runs the case that its steps can say a step's end: without a + // SayStep every step ask is refused live ("this build module says no step's end"), as mesh-build-node's was. + ends, err := runsTheKit(dir, "conformance.StepEnds(") + if err != nil { + return nil, err + } + counts, err := runsTheKit(dir, "conformance.RunsCounted(") + if err != nil { + return nil, err + } + if !counts { + // A-489c + refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.RunsCounted "+ + "(mesh-delivery-sdk steprun/conformance): run the kit's case that its puller counts the runs that started, not the bus's deliveries (A-489a)", seat)) + } + if !ends { + refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.StepEnds "+ + "(mesh-delivery-sdk steprun/conformance): run the kit's step-ends case with the module's own steps (design 47 G §24)", seat)) + } // Every build module meets the network (a fetch, a download, an install, a publish), so every one runs the passing case: its // steps say a network that did not answer as a transport fault the bus gives the ask again for (ADR 0664, issue 1748). says, err := runsTheKit(dir, "conformance.Passing(") diff --git a/checks/failurekit/failurekit_test.go b/checks/failurekit/failurekit_test.go index 42049e0ef..27dad2f4e 100644 --- a/checks/failurekit/failurekit_test.go +++ b/checks/failurekit/failurekit_test.go @@ -13,7 +13,7 @@ import ( func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { root := t.TempDir() const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n" - const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\n" + const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n" kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep for path, body := range map[string]string{ "modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`, @@ -30,6 +30,10 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { "modules/h/cmd/h/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\n", "modules/i/module.json": `{"claims":[{"name":"node-build-i"}],"capabilities":["other"],"tools":["build_i_build"]}`, // the whole kit, and no seat-settle-delay "modules/i/cmd/i/kit_test.go": imp + sweep, + "modules/j/module.json": `{"claims":[{"name":"node-build-j"}],"capabilities":["seat-settle-delay"],"tools":["build_j_build"]}`, // the rest of the kit, and no step-ends case + "modules/j/cmd/j/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n", + "modules/k/module.json": `{"claims":[{"name":"node-build-k"}],"capabilities":["seat-settle-delay"],"tools":["build_k_build"]}`, // no runs-counted case + "modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\n", "modules/e/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`, "modules/e/cmd/e/kit.go": kit, // not a test file } { @@ -45,9 +49,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { if err != nil { t.Fatal(err) } - want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused"} + want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused"} if len(got) != len(want) { - t.Fatalf("judged %+v, want a, b, c, e, f, g, h and i", got) + t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j and k", got) } for _, j := range got { is := "passes" diff --git a/modules/adwaita/module.json b/modules/adwaita/module.json index b47fbf37e..44bbe78dd 100644 --- a/modules/adwaita/module.json +++ b/modules/adwaita/module.json @@ -1,6 +1,7 @@ { "module": "adwaita", "version": "0.1", + "class": "leaf", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/artifact-store-tools/README.md b/modules/artifact-store-tools/README.md index cc662262c..586f58479 100644 --- a/modules/artifact-store-tools/README.md +++ b/modules/artifact-store-tools/README.md @@ -119,3 +119,16 @@ removed for `retention` on its seat (`release`, `remove`). It reads a reference and `//@`, as one artifact, and says artifacts-gone in the form the build named it. A call a seat refuses stops the sweep and writes the finding `sweep-refused` in the module's findings; the next sweep no seat refuses clears it (`sweepseats.go`). + +### One pending pass + +A finished build or a changed want marks the one pending pass (design 47 H, H-A-250); a pass running when one is marked +runs once more when it ends, however many events marked it. The builder's builds are a followed view: the watch's first view +at start, then its updates, kept in memory (H-A-255), each build's end taken from the builder's log's build-ended entries the +pass reads once, and only for a build the log lacks from its key's history (H-A-258); a watch asked again after an error replaces the view whole with its handover (H-A-257). A pass reads nothing +of them on the bus, judges nothing before the first view is in, and sweeps and observes S25 +from that one judgement. A list the registry +seats cannot answer ends the pass with the finding `artifact-list-unread`, written once; nothing asks the list again +until the next event, and a pass that reads it clears the finding. A pass that cannot judge the builds (the view not yet taken in, or a +done build's end unread) ends the same way with the finding `artifact-builds-unread` (H-A-260) (`holder.go`, +`sweepseats.go`). diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/door.go b/modules/artifact-store-tools/cmd/artifact-store-tools/door.go index e9292f5fe..cf807bf45 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/door.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/door.go @@ -116,12 +116,16 @@ func (runtimeBus) Publish(subject string, body any) error { return stdio.SeatPublish(subject, body, "") } -// follow watches the builder's done keys and the wants: a build's end sweeps and -// observes again; a want changed observes again. Event-driven: nothing reads them on a timer. +// follow watches the builder's done keys and the wants: the builds are a followed view, the watch's first view then its +// updates kept in memory (design 47 H, H-A-255); a build's end or a want changed marks the one pending pass (H-A-250 (1)), +// which sweeps and observes from the views. Event-driven: nothing reads them on a timer. func follow(h *Holder, v *views.Reader) { <-stdio.Served() watch := func(state string, handle func(stdio.StateChange) error) { for { + if state == BuildsRead { + h.Watching() // each handover, the first or one asked again, replaces the view whole (H-A-257) + } if err := stdio.State(state).Watch("", handle); err == nil { return } else { @@ -130,12 +134,8 @@ func follow(h *Holder, v *views.Reader) { time.Sleep(10 * time.Second) } } - observe := func() { - if err := h.Observe(context.Background()); err != nil { - h.logf("image-missing could not be observed: %v", err) - } - } watch(BuildsRead, func(c stdio.StateChange) error { + h.Heard(c) if c.Current || c.Op != stdio.OpPut { return nil } @@ -143,10 +143,12 @@ func follow(h *Holder, v *views.Reader) { State string `json:"state"` } if json.Unmarshal(c.Value, &b) == nil && b.State == "done" { - go func() { h.AfterBuild(c.Key); observe() }() + h.Wanted("after the build " + c.Key) } return nil }) + // The watch hands every current value over before it returns: the first view is in. + h.TakenIn() // The wants are the assigner's: the first view then its events (ADR 0615). What Watch hands over before it returns // is the first view, not a change. var current atomic.Bool @@ -154,7 +156,7 @@ func follow(h *Holder, v *views.Reader) { for { err := v.Watch(WantsRead, func(string, []byte, bool) { if !current.Load() { - go observe() + h.Wanted("a want changed") } }) if err == nil { @@ -164,5 +166,5 @@ func follow(h *Holder, v *views.Reader) { time.Sleep(10 * time.Second) } current.Store(false) - observe() + h.Wanted("the first view of the wants") } diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/holder.go b/modules/artifact-store-tools/cmd/artifact-store-tools/holder.go index 3490e8f4f..007d88238 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/holder.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/holder.go @@ -38,6 +38,10 @@ import ( "git.novox.be/novox/mesh-sdk/go/views" ) +// ErrBuildsUnread is a judgement refused because the builds cannot be judged: the followed view not yet taken in, or a +// done key's end unread (H-A-258, H-A-260). +var ErrBuildsUnread = errors.New("the builder's builds cannot be judged") + // What the holder reads and keeps. const ( WantsRead = assignerModule + ".wants" @@ -95,8 +99,19 @@ type Holder struct { sweep sync.Mutex // one sweep at a time mu sync.Mutex - fmu sync.Mutex // one pass of Observe at a time - ended map[string]time.Time // a done key's end, read once from its history + // pmu guards the pending pass (H-A-250 (1)): running while a pass runs, wanted when an event marked it since. + pmu sync.Mutex + running bool + wanted bool + wantedBy string + fmu sync.Mutex // one pass of Observe at a time + ended map[string]time.Time // a done key's end, read once from its history + // done is the followed view of the builder's builds (design 47 H, H-A-255): the done builds by key, taken in from the + // watch's first view and its updates (Heard); taken says the first view is in. A pass judges from it, reading nothing. + done map[string]Build + taken bool + // next is the handover a watch asked (again) is giving, which replaces done whole once it is in (H-A-257). + next map[string]Build } // Build is one done build of a module, as its key holds it, with when it ended. @@ -108,39 +123,81 @@ type Build struct { Manifest string } -// Builds is every done build the builder's keys hold, each with its end. +// Builds is every done build of the followed view, by key, read from memory, never from the bus (design 47 H, H-A-250 +// (2), H-A-255): each with the end known for it, zero where none is known yet (withEnds gives it). Before the view's first +// view is taken in there is none to judge from, and it says so, so no pass sweeps against an empty keep set. func (h *Holder) Builds() ([]Build, error) { - keys, err := h.Bus.Keys(BuildsRead) - if err != nil { - return nil, fmt.Errorf("the builder's builds: %w", err) + h.mu.Lock() + defer h.mu.Unlock() + if !h.taken { + return nil, fmt.Errorf("%w: they are not taken in yet, their first view has not come", ErrBuildsUnread) } - var out []Build - for _, k := range keys { - module, fp, err := builds.ParseBuilderBuildKey(k) - if err != nil { - continue - } - raw, found, err := h.Bus.Get(BuildsRead, k) - if err != nil { - return nil, fmt.Errorf("the builder's build %s: %w", k, err) - } - if !found { - continue - } - b, err := builds.DecodeBuilderBuild(raw) - if err != nil || b.State != builds.BuildDone { - continue - } - at, err := h.endOf(k) - if err != nil { - return nil, err - } - out = append(out, Build{Module: module, FP: fp, Key: k, At: at, Artifacts: b.Artifacts, Manifest: b.Manifest}) + out := make([]Build, 0, len(h.done)) + for _, b := range h.done { + b.At = h.ended[b.Key] + out = append(out, b) } + sort.Slice(out, func(a, b int) bool { return out[a].Key < out[b].Key }) return out, nil } -// endOf is when a done key was last written done, read once from its history: a done key is not written again. +// Heard takes one change of the builder's builds into the followed view: a done value is kept, anything else drops the +// key. Its end is not read here: withEnds takes it from the builder's log at the next pass (H-A-258); a key written done +// anew forgets the end it had. While a watch's handover is gathered (Watching), every change goes into it, current or +// not, so nothing heard before TakenIn is lost by the swap (H-A-257). +func (h *Holder) Heard(c stdio.StateChange) { + module, fp, err := builds.ParseBuilderBuildKey(c.Key) + if err != nil { + return + } + var b builds.BuilderBuild + if c.Op == stdio.OpPut { + b, err = builds.DecodeBuilderBuild(c.Value) + } + h.mu.Lock() + defer h.mu.Unlock() + if !c.Current { + delete(h.ended, c.Key) // written anew or gone: an end it had is no longer its + } + if h.next == nil && h.done == nil { + h.done = map[string]Build{} + } + into := h.done + if h.next != nil { + into = h.next + } + if c.Op != stdio.OpPut || err != nil || b.State != builds.BuildDone { + delete(into, c.Key) + return + } + into[c.Key] = Build{Module: module, FP: fp, Key: c.Key, Artifacts: b.Artifacts, Manifest: b.Manifest} +} + +// Watching says a watch of the builds is asked, first or again after an error: its handover of current values is +// gathered apart and replaces the view whole at TakenIn, so a key deleted while no watch ran leaves it (H-A-257). +func (h *Holder) Watching() { + h.mu.Lock() + h.next = map[string]Build{} + h.mu.Unlock() +} + +// TakenIn says the watch's handover is in: every current value was Heard. It replaces the view whole, and forgets the +// end of every key it no longer holds. +func (h *Holder) TakenIn() { + h.mu.Lock() + defer h.mu.Unlock() + if h.next != nil { + h.done, h.next = h.next, nil + for k := range h.ended { + if _, kept := h.done[k]; !kept { + delete(h.ended, k) + } + } + } + h.taken = true +} + +// endOf is when a done key was last written done, read from its history and kept: for a build the builder's log lacks. func (h *Holder) endOf(key string) (time.Time, error) { h.mu.Lock() at, known := h.ended[key] @@ -320,6 +377,8 @@ type judged struct { mirrors map[string]*Ref // mirrorsHeld says why no copy is eligible now, when one is not: a kept build whose bases the log does not name. mirrorsHeld string + // unread is why the registry seats' list could not be read, nil when it was (or none is read). + unread error } func (h *Holder) judge(ctx context.Context) (*judged, error) { @@ -327,6 +386,15 @@ func (h *Holder) judge(ctx context.Context) (*judged, error) { if err != nil { return nil, err } + // The builder's log, read once: what each build stood on, and each build's end (H-A-258). + against, ends, logErr := h.logged() + if logErr != nil { + h.logf("the builder's log could not be read, so every copy is kept as unrecorded and each end is read from its history: %v", logErr) + against, ends = nil, nil + } + if builds, err = h.withEnds(builds, ends); err != nil { + return nil, err + } wants, err := h.Wants() if err != nil { return nil, err @@ -335,15 +403,10 @@ func (h *Holder) judge(ctx context.Context) (*judged, error) { if h.Listed != nil { if j.view, err = h.Listed(ctx); err != nil { h.logf("the store's listing could not be read, so nothing is said gone: %v", err) - j.view = nil + j.view, j.unread = nil, err } } if j.view != nil { - against, err := h.against() - if err != nil { - h.logf("the builder's log could not be read, so every copy is kept as unrecorded: %v", err) - against = nil - } j.mirrors, j.mirrorsHeld = Mirrors(j.view, builds, keptBuilds(builds, wants), against) for r, m := range j.mirrors { if len(m.Builds) > 0 { @@ -354,13 +417,47 @@ func (h *Holder) judge(ctx context.Context) (*judged, error) { return j, nil } -// against is what each build the builder's log says ended stood on, by build key: the bases' references. -func (h *Holder) against() (map[string][]string, error) { +// withEnds gives each build its end: the one known, else the builder's log's build-ended entry, else its key's history, +// each kept once read (H-A-258). A done key whose end can be read from neither stays unread, and then nothing is judged: +// never from a view missing a build. +func (h *Holder) withEnds(built []Build, ends map[string]time.Time) ([]Build, error) { + var unread []string + var why error + for i := range built { + if !built[i].At.IsZero() { + continue + } + if at, logged := ends[built[i].Key]; logged { + h.mu.Lock() + if h.ended == nil { + h.ended = map[string]time.Time{} + } + h.ended[built[i].Key] = at + h.mu.Unlock() + built[i].At = at + continue + } + at, err := h.endOf(built[i].Key) + if err != nil { + unread, why = append(unread, built[i].Key), err + continue + } + built[i].At = at + } + if len(unread) > 0 { + return nil, fmt.Errorf("%w: the end of %d done builds could not be read (%s first), so nothing is judged: %v", ErrBuildsUnread, len(unread), unread[0], why) + } + return built, nil +} + +// logged is what each build the builder's log says ended stood on, by build key (the bases' references), and when it +// ended: one read of the log. +func (h *Holder) logged() (map[string][]string, map[string]time.Time, error) { entries, err := h.Bus.LogSince(builds.BuildLogRead, h.now().Add(-builds.BuilderLogDays*24*time.Hour)) if err != nil { - return nil, err + return nil, nil, err } - out := map[string][]string{} + out, ends := map[string][]string{}, map[string]time.Time{} for _, raw := range entries { e, err := builds.DecodeBuildLogEntry(raw.Value) if err != nil || e.Event != builds.BuildEndedEvent { @@ -371,8 +468,11 @@ func (h *Holder) against() (map[string][]string, error) { continue } out[key] = e.Against + if e.At.After(ends[key]) { + ends[key] = e.At + } } - return out, nil + return out, ends, nil } // Mirrors judges each copy in the store's mirror repositories (upstream//, /on-; ADR @@ -514,6 +614,11 @@ func (h *Holder) Sweep(ctx context.Context, s Sweeping) (*CollectAnswer, error) if err != nil { return nil, err } + return h.sweepFrom(ctx, j, s) +} + +// sweepFrom is a sweep from a judgement already read; the caller holds h.sweep. +func (h *Holder) sweepFrom(ctx context.Context, j *judged, s Sweeping) (*CollectAnswer, error) { a := &CollectAnswer{DryRun: s.DryRun, WouldLetGo: []string{}, LetGo: []string{}} var keptArchives, eligible []string for _, r := range j.sorted() { @@ -658,15 +763,73 @@ func namedBy(b Build, r string) string { return r } -// AfterBuild is the sweep at a build's end. -func (h *Holder) AfterBuild(key string) { - a, err := h.Sweep(context.Background(), Sweeping{Most: MostPerSweep, By: "after the build " + key}) +// Wanted marks the pass wanted (design 47 H, H-A-250 (1)): a finished build or a want change asks it, by naming what +// asked. With no pass running one starts; a pass running when it is marked runs once more when it ends, however many +// events marked it, never once per event. +func (h *Holder) Wanted(by string) { + if h.mark(by) { + go h.passes(by) + } +} + +// mark sets the pending mark, and says whether no pass ran, so the caller starts one. +func (h *Holder) mark(by string) bool { + h.pmu.Lock() + defer h.pmu.Unlock() + if h.running { + h.wanted, h.wantedBy = true, by + return false + } + h.running = true + return true +} + +// passes runs the pass, then once more for as long as an event marked it during the one that ran. +func (h *Holder) passes(by string) { + for { + h.Pass(context.Background(), by) + h.pmu.Lock() + if !h.wanted { + h.running = false + h.pmu.Unlock() + return + } + h.wanted, by = false, h.wantedBy + h.pmu.Unlock() + } +} + +// Pass is one pass of the seat: the keep set judged from one read of the builds, the wants and the store's list, then +// the sweep and S25's observation from that one judgement. A list the registry seats cannot answer ends the pass with +// the finding artifact-list-unread, asked again only at the next event (H-A-250 (3)); a list read again clears it. +func (h *Holder) Pass(ctx context.Context, by string) { + h.sweep.Lock() + j, err := h.judge(ctx) if err != nil { - h.logf("the sweep after %s: %v", key, err) + h.sweep.Unlock() + h.logf("the pass %s: %v", by, err) + if errors.Is(err, ErrBuildsUnread) { + h.unreadFinding(BuildsUnread, err) // H-A-260 + } return } - if len(a.LetGo) > 0 || a.Stopped != "" || a.Missing > 0 { - h.logf("the sweep after %s let go of %d (%d left, %d missing): %s", key, len(a.LetGo), a.Left, a.Missing, a.Stopped) + h.readAgain(BuildsUnread) + if j.unread != nil { + h.sweep.Unlock() + h.unreadFinding(ListUnread, j.unread) + return + } + h.readAgain(ListUnread) + a, err := h.sweepFrom(ctx, j, Sweeping{Most: MostPerSweep, By: by}) + h.sweep.Unlock() + switch { + case err != nil: + h.logf("the sweep %s: %v", by, err) + case len(a.LetGo) > 0 || a.Stopped != "" || a.Missing > 0: + h.logf("the sweep %s let go of %d (%d left, %d missing): %s", by, len(a.LetGo), a.Left, a.Missing, a.Stopped) + } + if err := h.observeFrom(ctx, j); err != nil { + h.logf("image-missing could not be observed: %v", err) } } @@ -857,10 +1020,16 @@ func inStoreAt(image, address string) string { // want's machine, written once and cleared once it no longer holds. Nothing is said without a listing. What stands is what // the held writer holds (design 47 G A-32, A-38), so a restart neither drops nor rewrites it. func (h *Holder) Observe(ctx context.Context) error { - now, err := h.observed(ctx) + j, err := h.judge(ctx) if err != nil { return err } + return h.observeFrom(ctx, j) +} + +// observeFrom is Observe from a judgement already read. +func (h *Holder) observeFrom(ctx context.Context, j *judged) error { + now := h.observed(j) if now == nil { return nil } @@ -899,13 +1068,9 @@ type Findings interface { } // observed is S25's findings now by key, nil without a listing. -func (h *Holder) observed(ctx context.Context) (map[string]meshconditions.Finding, error) { - j, err := h.judge(ctx) - if err != nil { - return nil, err - } +func (h *Holder) observed(j *judged) map[string]meshconditions.Finding { if j.view == nil { - return nil, nil + return nil } address := "" if d, err := h.Door(); err == nil { @@ -944,7 +1109,7 @@ func (h *Holder) observed(ctx context.Context) (map[string]meshconditions.Findin break } } - return now, nil + return now } // imageMissing is S25's finding, in the controller's words (cmd/mesh-controller/image_missing.go watchMissingImages); its id diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/holder_integration_test.go b/modules/artifact-store-tools/cmd/artifact-store-tools/holder_integration_test.go index 3963d3749..9c2c64958 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/holder_integration_test.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/holder_integration_test.go @@ -11,6 +11,7 @@ package main import ( "context" "encoding/json" + "fmt" "strings" "sync" "testing" @@ -200,6 +201,15 @@ func TestTheSeatSweepsAtABuildsEndOnARealBusWithNoLease(t *testing.T) { } h := &Holder{Bus: findingsAt{realBus: bus}, Findings: findingsThrough{findingsAt{realBus: bus}}, Door: mem.Door, Listed: mem.Listed, Seats: ask, Now: time.Now, Logf: t.Logf} h.Acts = meshhandactsclient.Recorder{Ask: ask} + // The followed view of the builds: the six on the bus handed over as the watch's first view does. + h.Watching() + if keys, err := bus.Keys(BuildsRead); err == nil { + for _, k := range keys { + raw, _, _ := bus.Get(BuildsRead, k) + h.Heard(stdio.StateChange{State: BuildsRead, Key: k, Op: stdio.OpPut, Value: raw, Current: true}) + } + } + h.TakenIn() // A build's end heard from the builds bucket, as follow hands it over. kv, _ := bus.kv(BuildsRead) @@ -215,7 +225,8 @@ func TestTheSeatSweepsAtABuildsEndOnARealBusWithNoLease(t *testing.T) { } select { case e := <-w.Updates(): - h.AfterBuild(e.Key()) + h.Heard(stdio.StateChange{State: BuildsRead, Key: e.Key(), Op: stdio.OpPut, Value: e.Value()}) + h.Pass(ctx, "after the build "+e.Key()) case <-ctx.Done(): t.Fatal("the build's end was not heard") } @@ -234,26 +245,82 @@ func TestTheSeatSweepsAtABuildsEndOnARealBusWithNoLease(t *testing.T) { } time.Sleep(20 * time.Millisecond) } - mu.Lock() - defer mu.Unlock() - if len(acts) != 3 || !strings.Contains(acts[0], archiveRef("letta", 2)) || !strings.Contains(acts[1], imageRef("letta", 2)) || - !strings.Contains(acts[2], mirror(1)) { - t.Fatalf("the hand acts recorded are %v; the store was asked %v", acts, door.asked) - } - if len(gone) != 1 || !strings.Contains(gone[0], `"fingerprint":"`+fp(2)+`"`) { - t.Fatalf("artifacts-gone said %v", gone) - } + func() { + mu.Lock() + defer mu.Unlock() + if len(acts) != 3 || !strings.Contains(acts[0], archiveRef("letta", 2)) || !strings.Contains(acts[1], imageRef("letta", 2)) || + !strings.Contains(acts[2], mirror(1)) { + t.Fatalf("the hand acts recorded are %v; the store was asked %v", acts, door.asked) + } + if len(gone) != 1 || !strings.Contains(gone[0], `"fingerprint":"`+fp(2)+`"`) { + t.Fatalf("artifacts-gone said %v", gone) + } - // S25 through the real findings bucket: letta's wanted image missing from the store is a finding there. - view, _ := mem.Listed(ctx) - repo, digest, _ := splitReference(imageRef("letta", 1)) - delete(view.L.Repos[repo].Revisions, digest) - if err := h.Observe(ctx); err != nil { - t.Fatal(err) - } - if keys, _ := bus.Keys("artifact-store-tools." + FindingsState); len(keys) != 1 || keys[0] != "module.letta.ace.image-missing" { - t.Fatalf("the findings are %v", keys) - } + // S25 through the real findings bucket: letta's wanted image missing from the store is a finding there. + view, _ := mem.Listed(ctx) + repo, digest, _ := splitReference(imageRef("letta", 1)) + delete(view.L.Repos[repo].Revisions, digest) + if err := h.Observe(ctx); err != nil { + t.Fatal(err) + } + if keys, _ := bus.Keys("artifact-store-tools." + FindingsState); len(keys) != 1 || keys[0] != "module.letta.ace.image-missing" { + t.Fatalf("the findings are %v", keys) + } + }() + + // Design 47 H2 §813 (7): a pass reads oci-artifact-registry's list page by page, each at most 768 KB, over 20,000 + // artifacts, so its view holds every one. + t.Run("a pass reads 20,000 artifacts page by page", func(t *testing.T) { + const many, pageBytes = 20000, 768 << 10 + repos := make([]map[string]any, many) + for i := range repos { + repos[i] = map[string]any{"name": fmt.Sprintf("m%05d/bundle", i), "manifests": []map[string]any{{ + "digest": fmt.Sprintf("sha256:%064x", i), "artifact": fmt.Sprintf("sha256:%064x", many+i), "size": 100}}} + } + pages := 0 + sub, err := nc.Subscribe("mesh.seat.oci-artifact-registry.tool.list.paged", func(m *nats.Msg) { + var in struct{ Next string } + _ = json.Unmarshal(m.Data, &in) + page, size, next := []map[string]any{}, 0, "" + for _, r := range repos { + if r["name"].(string) <= in.Next { + continue + } + raw, _ := json.Marshal(r) + if size+len(raw)+1 > pageBytes-1024 { // its comma, and room for the answer's other fields + next = page[len(page)-1]["name"].(string) + break + } + size += len(raw) + 1 + page = append(page, r) + } + pages++ + out, _ := json.Marshal(map[string]any{"repositories": page, "next": next, "capped": next != "", "total": many}) + _ = m.Respond(out) + }) + if err != nil { + t.Fatal(err) + } + defer func() { _ = sub.Unsubscribe() }() + store := &Store{Ask: func(key string, body any) (json.RawMessage, error) { + if key != "seat:oci-artifact-registry.list" { + return ask(key, body) + } + raw, _ := json.Marshal(body) + m, err := nc.Request("mesh.seat.oci-artifact-registry.tool.list.paged", raw, 5*time.Second) + if err != nil { + return nil, err + } + if len(m.Data) > pageBytes { + t.Errorf("a page of %d bytes", len(m.Data)) + } + return m.Data, nil + }} + got, err := store.ListOf("oci-artifact-registry", "") + if err != nil || len(got) != many || got[many-1].Name != "m19999/bundle" || pages < 2 { + t.Fatalf("read %d repositories in %d pages: %v", len(got), pages, err) + } + }) } // findingsAt reads and writes the holder's own findings in its bucket, artifact-store-tools_findings. diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/holder_test.go b/modules/artifact-store-tools/cmd/artifact-store-tools/holder_test.go index 72374209f..c92bb5b9a 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/holder_test.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/holder_test.go @@ -34,6 +34,17 @@ type memBus struct { history map[string][]stdio.StateRevision log []stdio.LogEntry published []string + // historyErr fails the history read of a key. + historyErr map[string]error + // calls counts each read by " ": a pass reads nothing of the builds, judged from the followed view. + calls map[string]int +} + +func (b *memBus) count(verb, state string) { + if b.calls == nil { + b.calls = map[string]int{} + } + b.calls[verb+" "+state]++ } func (b *memBus) LogSince(read string, at time.Time) ([]stdio.LogEntry, error) { @@ -49,6 +60,7 @@ func (b *memBus) LogSince(read string, at time.Time) ([]stdio.LogEntry, error) { func (b *memBus) Keys(state string) ([]string, error) { b.mu.Lock() defer b.mu.Unlock() + b.count("keys", state) var out []string for k := range b.states[state] { out = append(out, k) @@ -60,11 +72,18 @@ func (b *memBus) Keys(state string) ([]string, error) { func (b *memBus) Get(state, key string) ([]byte, bool, error) { b.mu.Lock() defer b.mu.Unlock() + b.count("get", state) v, ok := b.states[state][key] return v, ok, nil } func (b *memBus) History(state, key string) ([]stdio.StateRevision, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.count("history", state) + if err := b.historyErr[key]; err != nil { + return nil, err + } return b.history[state+" "+key], nil } @@ -229,7 +248,7 @@ func aMesh(t *testing.T) (*Holder, *memBus, *memDoor, *[]string) { want, _ := json.Marshal(meshwants.WantsByWantNodeModuleValue{V: 1, Fp: fp(1), Self: true}) _ = b.Put(WantsRead, "want.ace.letta", json.RawMessage(want)) var acts []string - h := &Holder{Bus: b, Findings: findingsThrough{b}, Door: func() (Door, error) { return door, nil }, Seats: door.seat, + h := &Holder{Logf: t.Logf, Bus: b, Findings: findingsThrough{b}, Door: func() (Door, error) { return door, nil }, Seats: door.seat, Listed: func(context.Context) (*View, error) { return &View{L: listing}, nil }, Now: func() time.Time { return day.Add(48 * time.Hour) }, Acts: meshhandactsclient.Recorder{Ask: func(key string, body any) (json.RawMessage, error) { @@ -237,9 +256,49 @@ func aMesh(t *testing.T) (*Holder, *memBus, *memDoor, *[]string) { acts = append(acts, key+" "+string(raw)) return json.RawMessage(`{}`), nil }}} + takeIn(h, b) return h, b, door, &acts } +// takeIn hands the builds over as the watch's first view does, then forgets the reads that took: a pass's are counted. +func takeIn(h *Holder, b *memBus) { + handOver(h, b) + h.TakenIn() + b.calls = nil +} + +// handOver is a watch's handover of every current value, not yet taken in. +func handOver(h *Holder, b *memBus) { + h.Watching() + keys, _ := b.Keys(BuildsRead) + for _, k := range keys { + raw, _, _ := b.Get(BuildsRead, k) + h.Heard(stdio.StateChange{State: BuildsRead, Key: k, Op: stdio.OpPut, Value: raw, Current: true}) + } +} + +// keyOf is letta's n-th build's key. +func keyOf(n int) string { k, _ := builds.BuilderBuildKey("letta", fp(n)); return k } + +// viewKeys are the keys the followed view holds. +func viewKeys(t *testing.T, h *Holder) []string { + t.Helper() + h.mu.Lock() + defer h.mu.Unlock() + var out []string + for k := range h.done { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// putBuild writes a build's key and hands it over as the watch's update does. +func putBuild(h *Holder, b *memBus, key string, raw []byte) { + _ = b.Put(BuildsRead, key, json.RawMessage(raw)) + h.Heard(stdio.StateChange{State: BuildsRead, Key: key, Op: stdio.OpPut, Value: raw}) +} + // ADR 0571 clause 2, 1126/A4/AC2: the keep set from the store's listing, the wants and the five newest builds; with no // lease key, a build's end and a confirmed collect let go of the eligible within the bound, leave an index for a // confirmed collect, record each deletion as a hand act and say artifacts-gone. @@ -312,7 +371,7 @@ func TestTheSeatKeepsTheFiveNewestAndTheWantedAndSweepsWithNoLease(t *testing.T) raw, _ := builds.EncodeBuilderBuild(builds.BuilderBuild{State: builds.BuildDone, Manifest: strings.Repeat("d", 64), Artifacts: []builds.BuiltArtifact{ {Name: "image", Kind: "image", Digest: digestOf(imageRef("letta", n)), Reference: artifactref.SeatReference(reg.Seat, "letta", "image", digestOf(imageRef("letta", n)))}, {Name: "files", Kind: "archive", Digest: digestOf(archiveRef("letta", n)), Reference: artifactref.SeatReference(ociseat.Seat, "letta", "files", digestOf(archiveRef("letta", n)))}}}) - _ = b.Put(BuildsRead, key, json.RawMessage(raw)) + putBuild(h, b, key, raw) } } if c.refuse != "" { @@ -323,7 +382,7 @@ func TestTheSeatKeepsTheFiveNewestAndTheWantedAndSweepsWithNoLease(t *testing.T) } switch c.how { case "build": - h.AfterBuild("letta.x") + h.Pass(context.Background(), "after the build letta.x") var gone []string for _, x := range door.asked { if r, ok := strings.CutPrefix(x, "let go "); ok { @@ -420,6 +479,7 @@ func TestAWantedImageTheStoreLacksIsAFindingAndImagesNamesWantsAndHaves(t *testi view.L.Repos[repo].Revisions[digest] = true // A restart: a holder made afresh holds no finding of its own, and clears what the writer holds (design 47 G A-32, A-38). h = &Holder{Bus: h.Bus, Findings: h.Findings, Door: h.Door, Listed: h.Listed, Seats: h.Seats, Now: h.Now, Acts: h.Acts, Logf: h.Logf} + takeIn(h, b) if err := h.Observe(context.Background()); err != nil { t.Fatal(err) } @@ -482,3 +542,154 @@ func (f findingsThrough) Held() []meshconditions.Finding { func (f findingsThrough) Clear(_ context.Context, scope, id, kind, _ string) error { return f.bus.Delete(FindingsState, views.FindingKey(scope, id, kind)) } + +// writesCounted counts the findings written through the test's writer. +type writesCounted struct { + findingsThrough + writes *int +} + +func (w writesCounted) Write(ctx context.Context, f meshconditions.Finding) error { + *w.writes++ + return w.findingsThrough.Write(ctx, f) +} + +// Design 47 H, H-A-250: the starts fold into one pending pass, a pass reads the builds in one page, and a list the +// registry seats cannot answer ends the pass with artifact-list-unread, written once and asked again only at an event. +func TestOnePendingPassReadsTheBuildsOnceAndEndsOnAnUnreadList(t *testing.T) { + t.Run("three events during a pass run exactly one more", func(t *testing.T) { + h, _, _, _ := aMesh(t) + listed, inner := 0, h.Listed + h.Listed = func(ctx context.Context) (*View, error) { + listed++ + if listed == 1 { + for _, by := range []string{"after the build a", "after the build b", "a want changed"} { + h.Wanted(by) // a pass runs: each only marks it + } + } + return inner(ctx) + } + if !h.mark("after the build letta.x") { + t.Fatal("no pass ran, and the mark did not start one") + } + h.passes("after the build letta.x") + if listed != 2 { + t.Fatalf("three events during a pass ran %d passes, want 2", listed) + } + if h.running || h.wanted { + t.Fatalf("after the passes running is %v and wanted %v", h.running, h.wanted) + } + }) + t.Run("a pass reads nothing of the builds and their ends come from the log", func(t *testing.T) { + h, b, door, _ := aMesh(t) + handOver(h, b) // a fresh take-in, counted: no history read for a build the log holds (H-A-258) + h.TakenIn() + h.Pass(context.Background(), "after the build letta.x") + if n := b.calls["keys "+BuildsRead] - 1 + b.calls["get "+BuildsRead] - 7 + b.calls["history "+BuildsRead]; n != 0 { + t.Fatalf("a take-in and a pass read the builds by %v", b.calls) + } + if !slices.Contains(door.asked, "let go "+imageRef("letta", 2)) { + t.Fatalf("the pass swept nothing: %v", door.asked) + } + // Only a build the log lacks is read from its history, once. + h, b, _, _ = aMesh(t) + b.log = append(b.log[:2:2], b.log[3:]...) // letta's 3rd + h.Pass(context.Background(), "a") + h.Pass(context.Background(), "b") + if b.calls["history "+BuildsRead] != 1 { + t.Fatalf("two passes read the builds' history %d times, want once for the build the log lacks", b.calls["history "+BuildsRead]) + } + }) + t.Run("no pass judges before the first view, and says so", func(t *testing.T) { + h, b, door, _ := aMesh(t) + h.taken = false + h.Pass(context.Background(), "after the build letta.x") + _, found, _ := b.Get(FindingsState, views.FindingKey("module", Module, BuildsUnread)) + if len(door.asked) != 0 || !found { + t.Fatalf("a pass before the builds were taken in asked %v; artifact-builds-unread is written: %v", door.asked, found) + } + }) + t.Run("an unread end holds every pass until it is read", func(t *testing.T) { + h, b, door, _ := aMesh(t) + writes := 0 + h.Findings = writesCounted{findingsThrough{b}, &writes} + b.log = append(b.log[:2:2], b.log[3:]...) // letta's 3rd: the log lacks it, and its history fails + b.historyErr = map[string]error{keyOf(3): errors.New("no responders")} + h.Pass(context.Background(), "a") + h.Pass(context.Background(), "b") + key := views.FindingKey("module", Module, BuildsUnread) + if _, found, _ := b.Get(FindingsState, key); !found || writes != 1 || len(door.asked) != 0 { + t.Fatalf("with an end unread the passes asked %v; the finding is written %v, %d times", door.asked, found, writes) + } + b.historyErr = nil + h.Pass(context.Background(), "c") + if _, found, _ := b.Get(FindingsState, key); found || !slices.Contains(door.asked, "let go "+imageRef("letta", 2)) { + t.Fatalf("once the end was read the pass asked %v and left the finding: %v", door.asked, found) + } + }) + t.Run("a change heard during the handover is in the view it gives", func(t *testing.T) { + h, b, _, _ := aMesh(t) + handOver(h, b) + raw, _, _ := b.Get(BuildsRead, keyOf(1)) + h.Heard(stdio.StateChange{State: BuildsRead, Key: keyOf(8), Op: stdio.OpPut, Value: raw}) // after the handover, before TakenIn + h.Heard(stdio.StateChange{State: BuildsRead, Key: keyOf(3), Op: stdio.OpDelete}) + h.TakenIn() + got := viewKeys(t, h) + if !slices.Contains(got, keyOf(8)) || slices.Contains(got, keyOf(3)) { + t.Fatalf("the view after the handover holds %v", got) + } + }) + t.Run("a key deleted or no longer done leaves the view; one written done again takes its new end", func(t *testing.T) { + h, b, _, _ := aMesh(t) + h.Pass(context.Background(), "a") // every end known + building, _ := builds.EncodeBuilderBuild(builds.BuilderBuild{State: "building"}) + h.Heard(stdio.StateChange{State: BuildsRead, Key: keyOf(3), Op: stdio.OpDelete}) + h.Heard(stdio.StateChange{State: BuildsRead, Key: keyOf(4), Op: stdio.OpPut, Value: building}) + if got := viewKeys(t, h); slices.Contains(got, keyOf(3)) || slices.Contains(got, keyOf(4)) { + t.Fatalf("the view holds %v", got) + } + later := b.log[len(b.log)-1].At.Add(time.Hour) + e := builds.BuildLogEntry{Event: builds.BuildEndedEvent, Module: "letta", FP: fp(5), Repository: "novox/x", Commit: "c", Node: "ace", At: later, Outcome: "done"} + entry, _ := builds.EncodeBuildLogEntry(e) + b.log = append(b.log, stdio.LogEntry{Sequence: 99, Key: "letta", Value: entry, At: later}) + raw, _, _ := b.Get(BuildsRead, keyOf(5)) + h.Heard(stdio.StateChange{State: BuildsRead, Key: keyOf(5), Op: stdio.OpPut, Value: raw}) + h.Pass(context.Background(), "b") + if got, _ := h.Builds(); !slices.ContainsFunc(got, func(x Build) bool { return x.Key == keyOf(5) && x.At.Equal(later) }) { + t.Fatalf("letta's 5th written done again does not end at %v: %+v", later, got) + } + }) + t.Run("a watch asked again replaces the view whole", func(t *testing.T) { + h, b, _, _ := aMesh(t) + gone, _ := builds.BuilderBuildKey("letta", fp(3)) + _ = b.Delete(BuildsRead, gone) // deleted while no watch ran: no change of it is heard + takeIn(h, b) + got, err := h.Builds() + if err != nil || len(got) != 6 || slices.ContainsFunc(got, func(x Build) bool { return x.Key == gone }) { + t.Fatalf("after the watch was asked again the view holds %d builds (%v), %s among them", len(got), err, gone) + } + }) + t.Run("a list unread ends the pass with its finding once", func(t *testing.T) { + h, b, door, _ := aMesh(t) + writes, listed, inner := 0, 0, h.Listed + h.Findings = writesCounted{findingsThrough{b}, &writes} + h.Listed = func(context.Context) (*View, error) { + listed++ + return nil, errors.New("the answer exceeds the bus's one megabyte") + } + h.Pass(context.Background(), "after the build a") + h.Pass(context.Background(), "a want changed") + key := views.FindingKey("module", Module, ListUnread) + if raw, found, _ := b.Get(FindingsState, key); !found || writes != 1 || !strings.Contains(string(raw), "one megabyte") { + t.Fatalf("the finding is %s (found %v), written %d times", raw, found, writes) + } + if listed != 2 || len(door.asked) != 0 || len(b.published) != 0 { + t.Fatalf("two passes listed %d times, asked %v and said %v", listed, door.asked, b.published) + } + h.Listed = inner + h.Pass(context.Background(), "after the build b") + if _, found, _ := b.Get(FindingsState, key); found || len(door.asked) == 0 { + t.Fatalf("a pass that read the list left the finding (%v) or swept nothing (%v)", found, door.asked) + } + }) +} diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/listed.go b/modules/artifact-store-tools/cmd/artifact-store-tools/listed.go index e83e881ea..61e7a59ac 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/listed.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/listed.go @@ -79,20 +79,46 @@ type Store struct { Ask func(key string, body any) (json.RawMessage, error) } -// ListOf asks seat's list, of one repository or, with name empty, of every one. +// ListOf asks seat's list, of one repository or, with name empty, of every one. oci-artifact-registry's list is read page by +// page from its cursor until it answers none (design 47 H2 §813 (7), §779); container-image-registry's answers whole. func (s *Store) ListOf(seat, name string) ([]reg.Repository, error) { if s == nil || s.Ask == nil { return nil, fmt.Errorf("this process reaches no registry seat") } - raw, err := s.Ask("seat:"+seat+"."+reg.VerbList, reg.ListInput{Name: name}) - if err != nil { - return nil, fmt.Errorf("%s's list: %w", seat, err) + if seat != ociseat.Seat { + raw, err := s.Ask("seat:"+seat+"."+reg.VerbList, reg.ListInput{Name: name}) + if err != nil { + return nil, fmt.Errorf("%s's list: %w", seat, err) + } + var a reg.ListAnswer + if err := json.Unmarshal(raw, &a); err != nil { + return nil, fmt.Errorf("%s's answer to list: %w", seat, err) + } + return a.Repositories, nil } - var a reg.ListAnswer - if err := json.Unmarshal(raw, &a); err != nil { - return nil, fmt.Errorf("%s's answer to list: %w", seat, err) + var out []reg.Repository + seen := map[string]bool{} + for in := (ociseat.ListInput{Name: name}); ; { + raw, err := s.Ask("seat:"+seat+"."+reg.VerbList, in) + if err != nil { + return nil, fmt.Errorf("%s's list: %w", seat, err) + } + var a struct { + Repositories []reg.Repository `json:"repositories"` + Next string `json:"next"` + } + if err := json.Unmarshal(raw, &a); err != nil { + return nil, fmt.Errorf("%s's answer to list: %w", seat, err) + } + out = append(out, a.Repositories...) + if a.Next == "" { + return out, nil + } + if seen[a.Next] { + return nil, fmt.Errorf("%s's list answered the cursor %q twice", seat, a.Next) + } + seen[a.Next], in.Next = true, a.Next } - return a.Repositories, nil } // View reads the store now, through both seats. diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/main.go b/modules/artifact-store-tools/cmd/artifact-store-tools/main.go index acb1d80d5..c4efb1cdb 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/main.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/main.go @@ -32,7 +32,7 @@ func main() { h.Acts = meshhandactsclient.Recorder{Ask: stdio.Ask} // The module's one held writer (design 47 G §689, A-16, A-29, A-32): the holder's findings and the reader's go through it. w, err := views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ - Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{ImageMissing, SweepRefused}}) + Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{ImageMissing, SweepRefused, ListUnread, BuildsUnread}}) if err != nil { logf("%v", err) os.Exit(1) diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/store_test.go b/modules/artifact-store-tools/cmd/artifact-store-tools/store_test.go index 3af7f16e7..5943e7e10 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/store_test.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/store_test.go @@ -92,7 +92,20 @@ func (f *fakeStore) ask(t *testing.T) func(string, any) (json.RawMessage, error) repos = append(repos, reg.Repository{Name: name, Manifests: ms}) } } - return json.Marshal(reg.ListAnswer{Repositories: repos}) + if seat != "oci-artifact-registry" { + return json.Marshal(reg.ListAnswer{Repositories: repos}) + } + // oci-artifact-registry pages (design 47 H2 §813 (7)): one repository a page, after the one its cursor names. + var page struct{ Next string } + _ = json.Unmarshal(raw, &page) + for len(repos) > 0 && repos[0].Name <= page.Next { + repos = repos[1:] + } + next := "" + if len(repos) > 1 { + repos, next = repos[:1], repos[0].Name + } + return json.Marshal(map[string]any{"repositories": repos, "next": next, "capped": next != ""}) } } diff --git a/modules/artifact-store-tools/cmd/artifact-store-tools/sweepseats.go b/modules/artifact-store-tools/cmd/artifact-store-tools/sweepseats.go index 538783e31..ed540cba8 100644 --- a/modules/artifact-store-tools/cmd/artifact-store-tools/sweepseats.go +++ b/modules/artifact-store-tools/cmd/artifact-store-tools/sweepseats.go @@ -27,6 +27,9 @@ import ( // SweepRefused is the sweep's finding: a seat refused a hold or a remove the sweep asked. const SweepRefused = "sweep-refused" +// ListUnread is the pass's finding: the registry seats' list could not be read, so the pass ended (design 47 H, H-A-250 (3)). +const ListUnread = "artifact-list-unread" + // canonical is a kept reference in the older form, `artifact-store://`, whichever form it came in; another is as // it was. func canonical(reference string) string { @@ -140,6 +143,53 @@ func (h *Holder) sweepClean() { } } +// BuildsUnread is the pass's finding: the builder's builds could not be judged, so the pass ended (design 47 H, H-A-260). +const BuildsUnread = "artifact-builds-unread" + +// unreadFinding writes a pass's finding of what it could not read (ListUnread, BuildsUnread) once: a pass that fails the +// same way while the writer holds it writes nothing more. Nothing asks again until the next event marks a pass. +func (h *Holder) unreadFinding(kind string, err error) { + for _, was := range h.Findings.Held() { + if was.Kind == kind { + return + } + } + at := h.now().UTC() + f := meshconditions.Finding{Scope: "module", ID: keys.EscapeName(Module), Kind: kind, + Subject: meshconditions.Subject{Scope: "module", ID: keys.EscapeName(Module)}, + Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", + Summary: "the artifact sweep stopped: the registry seats' list could not be read (the evidence names why)", + Headline: "The artifact sweep cannot read the store's list", + Explanation: "The sweep judges what to keep against the store's list, which it asks the registry seats. The list " + + "could not be read, so the sweep removed nothing and observed nothing; what it kept stays kept.", + Needs: "read the registry seat holder's journal for why its list failed; the next finished build or want change asks again.", + Evidence: []meshconditions.Evidence{{At: at, Said: err.Error()}}, + Source: "CAT-AS1", Observer: Module, At: at} + if kind == BuildsUnread { + f.Summary = "the artifact sweep stopped: the builder's builds could not be judged (the evidence names why)" + f.Headline = "The artifact sweep cannot judge the builds" + f.Explanation = "The sweep keeps each module's newest builds and every wanted one, judged from the builder's builds " + + "and when each ended. Those could not all be read, so the sweep removed nothing and observed nothing; what " + + "it kept stays kept." + f.Needs = "read this module's journal for which build's end is unread; the next finished build or want change asks again." + } + if werr := h.Findings.Write(context.Background(), f); werr != nil { + h.logf("the pass's finding %s (%v) could not be written: %v", kind, err, werr) + } +} + +// readAgain clears a pass's finding of kind, when the held writer holds it, once a pass read what it could not. +func (h *Holder) readAgain(kind string) { + for _, was := range h.Findings.Held() { + if was.Kind != kind { + continue + } + if err := h.Findings.Clear(context.Background(), was.Scope, was.ID, was.Kind, "a pass read it again"); err != nil { + h.logf("the pass's finding %s could not be cleared: %v", kind, err) + } + } +} + // keptWhy is why a kept reference is held, as the seat's hold takes it. func keptWhy(r *Ref) string { if r == nil || len(r.Why) == 0 { diff --git a/modules/artifact-store-tools/module.json b/modules/artifact-store-tools/module.json index 5ed0d1b66..26622f54e 100644 --- a/modules/artifact-store-tools/module.json +++ b/modules/artifact-store-tools/module.json @@ -1,6 +1,7 @@ { "module": "artifact-store-tools", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds": "0.1" }, @@ -111,7 +112,10 @@ { "name": "findings", "storage": "key-value", - "template": "state" + "template": "state", + "options": { + "max-mib": 8 + } }, { "name": "finding-events", @@ -124,7 +128,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/asus-zephyrus-g14/module.json b/modules/asus-zephyrus-g14/module.json index b5152b6d7..4055b81cd 100644 --- a/modules/asus-zephyrus-g14/module.json +++ b/modules/asus-zephyrus-g14/module.json @@ -1,6 +1,7 @@ { "module": "asus-zephyrus-g14", "version": "0.1", + "class": "leaf", "moved": true, "templates": "templates", "capabilities": [ diff --git a/modules/audit-logger/module.json b/modules/audit-logger/module.json index 2ed839dce..4314b5af2 100644 --- a/modules/audit-logger/module.json +++ b/modules/audit-logger/module.json @@ -1,6 +1,7 @@ { "module": "audit-logger", "version": "0.1", + "class": "leaf", "slug": "audit", "consumes": [ "**" diff --git a/modules/avahi/module.json b/modules/avahi/module.json index 01731ee6e..b73cbcca7 100644 --- a/modules/avahi/module.json +++ b/modules/avahi/module.json @@ -1,6 +1,7 @@ { "module": "avahi", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/baserow/module.json b/modules/baserow/module.json index f92a50402..ef7de33b6 100644 --- a/modules/baserow/module.json +++ b/modules/baserow/module.json @@ -1,6 +1,7 @@ { "module": "baserow", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/blueman/cmd/blueman-tools/manifest_test.go b/modules/blueman/cmd/blueman-tools/manifest_test.go index de3f7fad9..8cf1d30fb 100644 --- a/modules/blueman/cmd/blueman-tools/manifest_test.go +++ b/modules/blueman/cmd/blueman-tools/manifest_test.go @@ -1,12 +1,13 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // blueman's shape (novox/hq ADR 0208, ADR 0210): one official package, no seat, the X display on its @@ -14,40 +15,16 @@ import ( // bluetooth module's (bluez, its utilities, its daemon), and the Go bundle serving exactly the listed // blueman_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Contributions []any `json:"contributions"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestItInstallsTheAppletAndNothingElse(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestItInstallsTheAppletAndNothingElse(t *testing.T) { - m, _ := readManifest(t) if m.Module != "blueman" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) || !reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) { t.Fatalf("%+v", m) @@ -55,13 +32,22 @@ func TestItInstallsTheAppletAndNothingElse(t *testing.T) { if len(m.Resources) != 1 || m.Resources[0]["type"] != "package" || m.Resources[0]["package"] != packageFor { t.Fatalf("resources: %v", m.Resources) } - if m.Claims != nil || m.Seats != nil || m.Environment != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil { t.Fatal("it holds no seat and sets no environment") } } func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) // The package ships its XDG autostart entry, which the session's dex runs: an xinitrc slot or a // window-manager exec would start it twice. if m.Shell != nil || m.Contributions != nil { @@ -75,7 +61,16 @@ func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T) } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -96,8 +91,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/blueman-tools" || b["binary"] != "blueman-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/blueman-tools" || b.Binary != "blueman-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) diff --git a/modules/blueman/module.json b/modules/blueman/module.json index 8a79ba2d6..c896e7afb 100644 --- a/modules/blueman/module.json +++ b/modules/blueman/module.json @@ -1,6 +1,7 @@ { "module": "blueman", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/bluetooth/module.json b/modules/bluetooth/module.json index 6ee44cb77..8d908e6b5 100644 --- a/modules/bluetooth/module.json +++ b/modules/bluetooth/module.json @@ -1,6 +1,7 @@ { "module": "bluetooth", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/brother/module.json b/modules/brother/module.json index e1c1f7ae1..158ea6898 100644 --- a/modules/brother/module.json +++ b/modules/brother/module.json @@ -1,6 +1,7 @@ { "module": "brother", "version": "0.1", + "class": "core", "requires": [ { "name": "s3-bucket", diff --git a/modules/buildah/module.json b/modules/buildah/module.json index 4e97d7cdd..4f2cdad59 100644 --- a/modules/buildah/module.json +++ b/modules/buildah/module.json @@ -1,6 +1,7 @@ { "module": "buildah", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "user-namespaces" diff --git a/modules/ca-trust/module.json b/modules/ca-trust/module.json index 88602b90a..eed1faf32 100644 --- a/modules/ca-trust/module.json +++ b/modules/ca-trust/module.json @@ -1,6 +1,7 @@ { "module": "ca-trust", "version": "0.1", + "class": "core", "slug": "catrust", "capabilities": [ "service-manager" diff --git a/modules/claude-code/README.md b/modules/claude-code/README.md index 068d73518..e4ec69005 100644 --- a/modules/claude-code/README.md +++ b/modules/claude-code/README.md @@ -28,8 +28,7 @@ And, for where the agent runs as an account of its own (hq ADR 0266): rule and can read no secret the mesh placed for another account. A way found is this module's condition, and the controller's self-check says it urgently. - `/usr/local/bin/claude-agent`, root's, `0755`: starts the agent as that account — `claude` itself when run - as it, otherwise `sudo -iu claude` through the operator's own sudo, carrying the guard's - override only when it is set in the operator's shell. + as it, otherwise `sudo -iu claude` through the operator's own sudo. - `/etc/claude-code/agent-account`, root's, `0644`: the name of that account, the machine fact `agent-account`, for the shell to read — the controller fills no machine fact into shell code. - **`claude` in the operator's interactive zsh is `claude-agent`** where the machine names an agent account: @@ -48,7 +47,7 @@ whenever the node's tool runtime collects the module's tools: | `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh` (with a `timeout` of 660000 ms, mesh_wait's longest wait and a minute, so the agent's one-minute default does not cut a wait, issue 1871), and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's | | `managed-settings.json` | the keys set in this module's `managed_settings` setting — at the controller's terminal alone (hq issue 340) — under the mesh's own keys: the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, the key-helper while the node holds an API-key licence, git's credential file while the node holds the forge's read credential (below), and the two that name the `nox-mesh` marketplace and enable its plugin, and `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` (660000) in `env` beside the operator's own, the mesh's key winning | | `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions, the **"instead of" table** — then the instruction sections registered for every node and for this one | -| `marketplace/` | the `nox-mesh` plugin (hq ADR 0216): the skills, subagents, commands and output styles registered for every node and for this one, offered in a session as `nox-mesh:` — and the **guard on the agent's shell** (`guard/`), the mesh's own hook and the plugin's only one (hq issue 340). Replaced whole, staged beside and swapped in | +| `marketplace/` | the `nox-mesh` plugin (hq ADR 0216): the skills, subagents, commands and output styles registered for every node and for this one, offered in a session as `nox-mesh:` — and this module's binary (`guard/guard`, its path kept so the home-fs helper's path does not move) run by the mesh's own SessionStart and Stop hooks, the plugin's only hooks (hq issue 340, ADR 0489). No PreToolUse hook: the guard on the agent's shell is removed (the operator, 2026-11-20). Replaced whole, staged beside and swapped in | Under the operator's home: `~/.claude/.credentials.json`, only when the licence manager hands this node a subscription token; and what is registered at the **home** scope for this node — a skill, subagent, @@ -126,31 +125,15 @@ The agent kept reaching for `ssh journalctl` while the service manager answered this is not placed) — at start, every ten minutes and on `claude_code_render`, keeps it in its state (`mesh-tools.json`), and renders it into `CLAUDE.md` as one row per seat or module: `/.` and each verb with the commands it replaces. Generated, never written by hand: a verb that gains `replaces` is in - the next render. Ordered by what the guard here refused most, then the machines' seats, the modules, the + the next render. Ordered by the machines' seats, the modules, the mesh's seats; at most sixteen rows, the rest one `mesh_search` away. -- **The guard.** A PreToolUse hook on every tool, judging `Bash`, `Edit`, `Write`, `MultiEdit` and `NotebookEdit` and letting the rest through (but see the account rule below): this module's own - binary (`claude-code guard`), copied root's into the plugin with what it judges with (`guard.json`: the - machines by name, domain and address, and the replaced commands), run by its path under `/etc/claude-code` so - the session cannot change it. It refuses `ssh`, `scp`, `sftp`, `rsync`, `mosh` and `autossh` to a mesh machine - (any `*.internal` name, a machine's name or a name under its domains, one of its addresses, as `ssh -G` reads - the destination; a jump through one too), writing `/etc/hosts` or `/etc/resolv.conf`, and `HOSTALIASES` — - naming the verb that does the job on that machine when one says it replaces the command, and otherwise that a - missing tool is created in the module that owns it, never worked around. **Stated, not silent:** an ssh login - as `git` is the forge's account, which runs nothing but git, and passes; a git remote is never an ssh command - line anyway. -- **The operator's override**: `MESH_GUARD_OVERRIDE=`, exported in the operator's own shell before the - session starts. It is read from the session's environment as the kernel kept it at exec - (`/proc//environ` of the agent's process), so nothing a session does — a command's `export`, a - settings `env` key — can set it, and a command naming it is refused outright. Every override and every - refusal is a line in the module's `guard.log`; an override that cannot be recorded is not honoured. - `claude_code_guard` shows the rules, the data and the record. - -It is a guard against the habit, not a sandbox: a command written to hide what it runs can hide it, and the -record is how a habit that found a way round is seen. +The rule under the table (never `ssh` to a mesh machine, never edit `/etc/hosts` or set `HOSTALIASES` for a +mesh name) is the session's own: nothing on the agent's shell enforces it since the guard was removed (the +operator, 2026-11-20). ## Tools -`claude_code_status`, `claude_code_render`, `claude_code_guard`, `claude_code_pull` (asks the vault for this node's +`claude_code_status`, `claude_code_render`, `claude_code_pull` (asks the vault for this node's licence token now), `claude_code_grant` (for the licence manager), `claude_code_mcp_list`, `claude_code_mcp_unregister` (this node by default; `nodes: "all"` or a list for more). @@ -339,14 +322,6 @@ applied only while the agent's account holds it — and what this module placed goes: the access-token-only credentials file (one holding a refresh token is a login the person made, and stays, said), the home-scope items unless changed by hand, the key kept in the state. -**The guard there refuses every tool call of a session that does not run as the agent's account** — -shell, file edits, reads and the mesh's tools alike — and no override lifts it: the operator's account may become root, and an -agent started in it by habit must do nothing. Its record goes to the machine's journal -(`journalctl -t mesh-claude-code-guard`), which the session's account may add to and not change; -`claude_code_guard` reads it there, keeping only the lines the journal says the guard's own binary wrote. That -is not proof: the account can run the guard's binary itself and add lines in the guard's words. What it -cannot do is remove one. - **An API key is taken only from the agent's own home.** `claude_code_add_api_key` reads a file and removes it, and the runtime runs as the operator: a path anywhere would hand whoever calls it the runtime's credential or the operator's keys. So the file must lie under the home of the account the agent runs as, reached through no diff --git a/modules/claude-code/cmd/claude-code/agent_account_test.go b/modules/claude-code/cmd/claude-code/agent_account_test.go index 66b213e67..19cac6788 100644 --- a/modules/claude-code/cmd/claude-code/agent_account_test.go +++ b/modules/claude-code/cmd/claude-code/agent_account_test.go @@ -1,8 +1,7 @@ package main // Where the agent runs as an account of its own (novox/hq ADR 0266): the home touched through the helper, the -// licence that follows the account, what goes from the operator's home, and the guard that refuses a session -// running as anyone else. +// licence that follows the account, and what goes from the operator's home. import ( "bufio" @@ -11,7 +10,6 @@ import ( "errors" "io" "io/fs" - "net" "os" "path/filepath" "strings" @@ -333,82 +331,6 @@ func TestNothingGoesWhereTheAgentRunsAsTheOperator(t *testing.T) { } } -// ---- the guard -------------------------------------------------------------------------------------------- - -func TestASessionNotRunningAsTheAgentsAccountDoesNothing(t *testing.T) { - g := Guard{Data: GuardData{Node: "anchor", Agent: "agent"}} - echo := HookInput{ToolName: "Bash", ToolInput: map[string]any{"command": "echo hello"}} - v := g.JudgeAs("operator", echo) - if !v.Refuse || v.Rule != "account" || v.Overridable || !strings.Contains(v.Message, "claude-agent") { - t.Fatalf("a session as the operator is refused whatever it runs, with no override: %+v", v) - } - if v := g.JudgeAs("operator", HookInput{ToolName: "Write", ToolInput: map[string]any{"file_path": "/tmp/x"}}); !v.Refuse { - t.Fatal("a file edit too") - } - if v := g.JudgeAs("agent", echo); v.Refuse { - t.Fatalf("the agent's own account runs as before: %+v", v) - } - if v := (Guard{Data: GuardData{Node: "laptop"}}).JudgeAs("operator", echo); v.Refuse { - t.Fatal("where agents run as the operator, the operator's session runs as before") - } -} - -func TestWhereTheAgentHasItsOwnAccountTheRecordIsTheJournal(t *testing.T) { - p, _ := node(t, "anchor") - if d := GuardDataOf(p, nil); d.Agent != "" || strings.HasPrefix(d.Log, JournalRecord) { - t.Fatalf("as the operator: the module's own file; got %+v", d) - } - p.Agent, p.Operator = "agent", "operator" - d := GuardDataOf(p, nil) - if d.Agent != "agent" || d.Log != JournalRecord+GuardJournalID { - t.Fatalf("as an account of its own: the journal, and the account named; got %+v", d) - } - - socket := filepath.Join(t.TempDir(), "journal") - conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: socket, Net: "unixgram"}) - if err != nil { - t.Skipf("no unix datagram socket here: %v", err) - } - defer conn.Close() - was := journalSocket - journalSocket = socket - t.Cleanup(func() { journalSocket = was }) - if err := RecordGuard(d.Log, GuardEntry{Decision: "refused", Rule: "account", Tool: "Bash", Command: "a\nb"}); err != nil { - t.Fatal(err) - } - buf := make([]byte, 4096) - n, _, err := conn.ReadFrom(buf) - if err != nil { - t.Fatal(err) - } - lines := strings.Split(strings.TrimSuffix(string(buf[:n]), "\n"), "\n") - if len(lines) != 3 || lines[0] != "SYSLOG_IDENTIFIER="+GuardJournalID || !strings.HasPrefix(lines[2], "MESSAGE={") { - t.Fatalf("one line per field, the entry as one line of JSON: %q", lines) - } - - readWas := readJournal - t.Cleanup(func() { readJournal = readWas }) - readJournal = func(id string, last int) ([]byte, error) { - if id != GuardJournalID { - t.Fatalf("read %s", id) - } - msg, _ := json.Marshal(strings.TrimPrefix(lines[2], "MESSAGE=")) - forged, _ := json.Marshal(`{"decision":"overridden","rule":"ssh","tool":"Bash","command":"forged"}`) - return []byte(`{"MESSAGE":` + string(msg) + `,"_EXE":"` + HelperPath() + `"}` + "\n" + - `{"MESSAGE":` + string(forged) + `,"_EXE":"/usr/bin/logger"}` + "\n"), nil - } - if got := ReadGuardLog(d.Log, 10); len(got) != 1 || got[0].Rule != "account" || got[0].Command != "a\nb" { - t.Fatalf("the record reads back from the journal: %+v", got) - } - if err := RecordGuard(JournalRecord+"x", GuardEntry{}); err != nil && !strings.Contains(err.Error(), "journal") { - t.Fatal(err) - } - journalSocket = filepath.Join(t.TempDir(), "absent") - if err := RecordGuard(d.Log, GuardEntry{}); err == nil { - t.Fatal("a journal that cannot be reached is an error, so an override is not honoured unrecorded") - } -} - // ---- an API key is taken only from the agent's own home --------------------------------------------------- func TestAnAPIKeyFileOutsideTheAgentsHomeIsRefusedAndKept(t *testing.T) { @@ -439,21 +361,6 @@ func TestAnAPIKeyFileOutsideTheAgentsHomeIsRefusedAndKept(t *testing.T) { } } -func TestTheGuardIsAskedAboutEveryToolAndRefusesEachForAnotherAccount(t *testing.T) { - if GuardMatcher != "*" { - t.Fatalf("the guard is asked about every tool, got %q", GuardMatcher) - } - g := Guard{Data: GuardData{Node: "anchor", Agent: "agent"}} - for _, tool := range []string{"Read", "Grep", "WebFetch", "mcp__mesh__mesh_call", "Task"} { - if v := g.JudgeAs("operator", HookInput{ToolName: tool}); !v.Refuse { - t.Fatalf("%s as another account is refused", tool) - } - if v := g.JudgeAs("agent", HookInput{ToolName: tool}); v.Refuse { - t.Fatalf("%s as the agent's account passes", tool) - } - } -} - func TestAMoveWritesTheAccountFileBesideTheToken(t *testing.T) { p, w := node(t, "anchor") writeFile(t, p.binding(), `{"licence":"personal","kind":"subscription","generation":4}`) diff --git a/modules/claude-code/cmd/claude-code/claude_code_test.go b/modules/claude-code/cmd/claude-code/claude_code_test.go index f514945e3..7674cc348 100644 --- a/modules/claude-code/cmd/claude-code/claude_code_test.go +++ b/modules/claude-code/cmd/claude-code/claude_code_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/views" ) @@ -358,18 +359,128 @@ func TestAnAppliedBindingSaysWhyAndWho(t *testing.T) { } } -func TestTheTokenANodeIsHandedReplacesALoginsGrantAndLeavesNoRefreshToken(t *testing.T) { - p, w := node(t, "laptop") - writeFile(t, p.credentials(), `{"claudeAiOauth":{"accessToken":"at-old","refreshToken":"rt-spent","expiresAt":`+ - strings.TrimSpace(string(mustJSON(now+7_200_000)))+`}}`) - var asked []string - out, err := Pull(p, seat(t, "personal", "at-new", 1, &asked), writer(w)) - if err != nil || out["applied"] != true { - t.Fatalf("%v %v", out, err) - } - c := creds(t, p) - if c["accessToken"] != "at-new" || c["refreshToken"] != nil || HoldingsOf(p).Refresh.Present { - t.Fatalf("%v", c) +// ADR 0206, ADR 0209, design 39 §6 "the latest login wins": a login in the file that was never handed to the manager +// is newer than every lease, made while the tool runner was stopped (the start's first view) or while it runs (a +// binding or the vault's change heard before the manager asked claude_code_grant). No path writes over it; once +// claude_code_grant handed it, its successor replaces it and leaves no refresh token, and a file holding no login is +// restored as before. +func TestALoginNotHandedIsNeverWrittenOverAndItsSuccessorReplacesIt(t *testing.T) { + login := `{"claudeAiOauth":{"accessToken":"at-login","refreshToken":"rt-login","expiresAt":` + + strings.TrimSpace(string(mustJSON(now+7_200_000))) + `,"refreshTokenExpiresAt":9000},"other":1}` + lease := `{"claudeAiOauth":{"accessToken":"at-lease","expiresAt":1},"other":1}` + for _, c := range []struct { + name, file string + handed bool + offeredRTE int64 // the refresh token expiry the grant offered carries, 0 for none + offeredExp int64 // its access expiry, 0 for an hour from now + heard func(p Paths, ask Ask, w WriteManaged) (string, error) + want string // the access token the file holds after + account string // the email address the agent's account file names, "" for none + reason string // what the journal line says, "" for nothing + }{ + {"the start's first view, a login made while stopped", login, false, 0, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return FirstBinding(p, ask, w) + }, "at-login", "", ""}, + {"binding.changed heard while it runs, before the grant was asked", login, false, 0, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "", ""}, + {"the vault's change heard while it runs, before the grant was asked", login, false, 0, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnSecretChanged(p, []byte(`{"name":"licence.personal.access","generation":5}`), ask, w) + }, "at-login", "", ""}, + {"a login handed, met by its refresh: same lineage, later access expiry (H-A-139)", login, true, 9000, now + 3*7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-new", "", ""}, + {"a login handed, met by a newer lineage (H-A-138)", login, true, 200_000_000, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-new", "", ""}, + {"a login handed, met by the same lineage with an earlier access expiry (H-A-139)", login, true, 9000, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "", ""}, + {"a login handed, met by the same lineage with an equal access expiry (H-A-139)", login, true, 9000, now + 7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "", ""}, + {"a login handed, met by an older lineage (H-A-138)", login, true, -100_000_000, now + 3*7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "", ""}, + {"a login handed, met by a lease with no lineage mark (H-A-138)", login, true, 0, now + 3*7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "", ""}, + {"not handed, the same account, a lease that succeeds it: the latest login wins (H-A-140)", login, false, 9000, now + 3*7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-new", "personal", "login superseded"}, + {"not handed, the same account, a lease older than it (H-A-140)", login, false, 9000, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "personal", ""}, + {"not handed, another account, a newer lease (H-A-140)", login, false, 200_000_000, now + 3*7_200_000, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return OnBindingChanged(p, []byte(`{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}`), ask, w) + }, "at-login", "someone@example.org", ""}, + {"a file holding the lease, older than the one handed", lease, false, 0, 0, func(p Paths, ask Ask, w WriteManaged) (string, error) { + return FirstBinding(p, ask, w) + }, "at-new", "", ""}, + } { + t.Run(c.name, func(t *testing.T) { + p, w := node(t, "laptop") + writeFile(t, p.binding(), `{"licence":"personal","key":"personal","kind":"subscription","generation":2}`+"\n") + writeFile(t, p.credentials(), c.file) + if c.account != "" { + writeFile(t, p.account(), `{"oauthAccount":{"accountUuid":"u-1","emailAddress":"`+c.account+`"}}`) + } + if c.handed { + manager, _ := GenerateKeyPair() + if a, err := GrantFor(p, manager.PublicKey); err != nil || a.Sealed == nil { + t.Fatalf("the grant: %+v %v", a, err) + } + } + var asked []string + current := seat(t, "personal", "at-new", 9, &asked) + ask := func(address string, args any) (json.RawMessage, error) { + if address == SeatVerb("bindings") { + return json.RawMessage(`[{"consumer":"laptop","licence":"personal","key":"personal","kind":"subscription","generation":9}]`), nil + } + if address == VaultGet && (c.offeredRTE != 0 || c.offeredExp != 0) { + exp := c.offeredExp + if exp == 0 { + exp = now + 3_600_000 + } + g := Grant{AccessToken: "at-new", ExpiresAt: exp} + if c.offeredRTE != 0 { + g.RefreshTokenExpiresAt = &c.offeredRTE + } + gj, _ := json.Marshal(g) + box, err := Seal(string(gj), args.(map[string]any)["public_key"].(string)) + if err != nil { + t.Fatal(err) + } + return json.Marshal(map[string]any{"name": args.(map[string]any)["name"], "generation": 1, "sealed": box}) + } + return current(address, args) + } + before, _ := os.ReadFile(p.credentials()) + line, err := c.heard(p, ask, writer(w)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(line, c.reason) { + t.Fatalf("the line %s lacks %q", line, c.reason) + } + got := creds(t, p) + if got["accessToken"] != c.want { + t.Fatalf("the file holds %v, want %s", got["accessToken"], c.want) + } + after, _ := os.ReadFile(p.credentials()) + if c.want == "at-login" { + if string(after) != string(before) || !HoldingsOf(p).Refresh.Present { + t.Fatalf("a login not handed was changed: %s", after) + } + return + } + // Restored: no refresh token survives (design 14, design 36 §5), the CLI's other keys stay. + var whole map[string]any + _ = json.Unmarshal(after, &whole) + if got["refreshToken"] != nil || HoldingsOf(p).Refresh.Present || whole["other"] == nil { + t.Fatalf("restored %s", after) + } + }) } } @@ -618,7 +729,10 @@ func TestTheFirstViewOfTheBindingIsApplied(t *testing.T) { Reads []string } _ = json.Unmarshal(raw, &m) - if !slices.Contains(m.Consumes, BindingChanged) || !slices.Contains(m.Consumes, SecretChanged) || + // The manager says each change as binding.changed. (design 47 G A-134), and the bus consumer this module's + // consumes is composed into hands it only what an entry names, so an entry naming binding.changed alone hears none. + hears := slices.ContainsFunc(m.Consumes, func(c string) bool { return stdio.TopicMatches(c, BindingChanged+".g14") }) + if !hears || !slices.Contains(m.Consumes, SecretChanged) || !slices.Contains(m.Invokes, SeatVerb("bindings")) || !slices.Contains(m.Invokes, VaultGet) || len(m.Reads) != 0 { t.Fatalf("the manifest consumes %v, invokes %v, reads %v", m.Consumes, m.Invokes, m.Reads) } diff --git a/modules/claude-code/cmd/claude-code/config.go b/modules/claude-code/cmd/claude-code/config.go index 194363d5f..527bd2141 100644 --- a/modules/claude-code/cmd/claude-code/config.go +++ b/modules/claude-code/cmd/claude-code/config.go @@ -472,40 +472,27 @@ type PluginFile struct { From string `json:",omitempty"` } -// GuardDir is where the guard on the agent's shell lives in the plugin (novox/hq ADR 0245): its binary and -// what it is given. Outside hooks/, so no registered hook's name can be it. +// GuardDir is where this module's binary lives in the plugin, run by the SessionStart and Stop hooks and as the +// home-fs helper (novox/hq ADR 0266). Outside hooks/, so no registered hook's name can be it. Its path is kept so the +// helper's does not move; the guard on the agent's shell that once ran from it is removed (the operator, +// 2026-11-20). const GuardDir = "guard" -// GuardFiles are the guard as the plugin carries it: the binary to copy, what it judges with, and — the same -// binary again — the waits directory the SessionStart and Stop hooks are given (novox/hq ADR 0489, issues -// 1744, 1743). Empty WaitsDir places no such hook. -type GuardFiles struct { +// HookFiles are what the plugin carries to run its hooks: the binary to copy and the waits directory the +// SessionStart and Stop hooks are given (novox/hq ADR 0489, issues 1744, 1743). Empty WaitsDir places no hook. +type HookFiles struct { Exe string - Data GuardData WaitsDir string } -// GuardMatcher is what the guard is asked about: every tool. Its own rules judge the shell and the agent's file -// edits and let every other tool through; the rule of the account agents run as (novox/hq ADR 0266) refuses -// every tool of a session running as another, reading and the mesh's tools included, so that session can do -// nothing at all. -const GuardMatcher = "*" - -// GuardCommand is the hook's command line: by its path under the managed directory, root's — never the -// copy the agent may keep of a plugin, which the session could change. -func GuardCommand() string { - dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) - return `"` + filepath.Join(dir, "guard") + `" guard "` + filepath.Join(dir, "guard.json") + `"` -} - -// SessionStartCommand is the plugin's SessionStart hook: the guard's own binary, told the session's open +// SessionStartCommand is the plugin's SessionStart hook: this module's binary, told the session's open // waits live under waitsDir (novox/hq ADR 0489 §3, issue 1744). func SessionStartCommand(waitsDir string) string { dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) return `"` + filepath.Join(dir, "guard") + `" session-start "` + waitsDir + `"` } -// StopCommand is the plugin's Stop hook: the guard's own binary, refusing to end the turn while a wait under +// StopCommand is the plugin's Stop hook: this module's binary, refusing to end the turn while a wait under // waitsDir is open and unwatched, or past its bound and untold (novox/hq ADR 0489 §3-§6, issue 1743). func StopCommand(waitsDir string) string { dir := filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir) @@ -516,9 +503,9 @@ func StopCommand(waitsDir string) string { // over a mesh item of the same kind and name: the node's wins. func Marketplace(c Config) map[string]PluginFile { return MarketplaceWith(c, nil) } -// MarketplaceWith is the marketplace with the guard on the agent's shell, when there is one to place: its -// hook first, before any registered one. -func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { +// MarketplaceWith is the marketplace with the binary the plugin's hooks run, when there is one to place, and its +// SessionStart and Stop hooks. No PreToolUse hook: the plugin judges no tool call. +func MarketplaceWith(c Config, guard *HookFiles) map[string]PluginFile { root := "plugins/" + Plugin + "/" out := map[string]PluginFile{ ".claude-plugin/marketplace.json": {Content: jsonFile(map[string]any{ @@ -547,9 +534,6 @@ func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { hooks := map[string][]any{} if guard != nil && guard.Exe != "" { out[root+GuardDir+"/guard"] = PluginFile{From: guard.Exe, Executable: true} - out[root+GuardDir+"/guard.json"] = PluginFile{Content: jsonFile(guard.Data)} - hooks["PreToolUse"] = append(hooks["PreToolUse"], map[string]any{"matcher": GuardMatcher, - "hooks": []any{map[string]any{"type": "command", "command": GuardCommand(), "timeout": 15}}}) if guard.WaitsDir != "" { // A session's wait list (novox/hq ADR 0489): the SessionStart hook names the session's id and its open // waits (issue 1744); the Stop hook keeps the turn open while one is unwatched or untold (issue 1743). @@ -574,7 +558,7 @@ func MarketplaceWith(c Config, guard *GuardFiles) map[string]PluginFile { out[root+"output-styles/"+it.Name+".md"] = PluginFile{Content: it.Files[it.Name+".md"]} } // A hook is never rendered from a registration (novox/hq issue 340): the plugin's hooks are the mesh's own - // guard alone, and any other is the operator's, in the managed settings set at the controller's terminal. + // SessionStart and Stop hooks alone, and any other is the operator's, in the managed settings set at the controller's terminal. } if len(hooks) > 0 { out[root+"hooks/hooks.json"] = PluginFile{Content: jsonFile(map[string]any{"hooks": hooks})} diff --git a/modules/claude-code/cmd/claude-code/config_test.go b/modules/claude-code/cmd/claude-code/config_test.go index f66d79469..35a3c43ed 100644 --- a/modules/claude-code/cmd/claude-code/config_test.go +++ b/modules/claude-code/cmd/claude-code/config_test.go @@ -281,7 +281,7 @@ func TestTheManifestListsEveryToolServed(t *testing.T) { // notice goes out on the operator channel's notify (design 47 G GR8). if !slices.Equal(m.Invokes, []string{"seat:mesh-hand-acts.warranted", "seat:mesh-hand-acts.hand-act", "seat:mesh-catalog.seat-definitions", RevisionVerb, RegistrationsVerb, SourceVerb, AssignmentsTool, SeatVerb("bindings"), SeatVerb("current"), VaultGet, "seat:operator-channel.notify"}) || len(m.Reads) != 0 || - !slices.Equal(m.Consumes, []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-delivery-assigner.views.assignments", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", HoldingsAsked, BindingChanged, SecretChanged}) { + !slices.Equal(m.Consumes, []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-delivery-assigner.views.assignments", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", HoldingsAsked, BindingChanged + ".*", SecretChanged}) { t.Errorf("invokes = %v, reads = %v, consumes = %v", m.Invokes, m.Reads, m.Consumes) } if src, _ := os.ReadFile("proposals.go"); !strings.Contains(string(src), `"seat:mesh-hand-acts.warranted"`) || diff --git a/modules/claude-code/cmd/claude-code/grant.go b/modules/claude-code/cmd/claude-code/grant.go index e184da94c..7b28a383e 100644 --- a/modules/claude-code/cmd/claude-code/grant.go +++ b/modules/claude-code/cmd/claude-code/grant.go @@ -122,6 +122,36 @@ func HoldsLogin(c Credentials) bool { return rt != "" } +// LoginKept is the reason a grant is not written over a login (H-A-138). +const LoginKept = "login kept" + +// Succeeds says the offered grant replaces the login the file holds (H-A-138, H-A-139): its lineage is newer +// (its refresh token's expiry later than the login's, beyond one generation), or it is of the same lineage +// (sameGeneration) and its access token expires later than the login's, which only the manager's refresh of +// that login yields. No lineage mark, an older lineage, or the same lineage with no later access expiry is the +// older lease. +func Succeeds(login Credentials, offered Grant) bool { + if offered.RefreshTokenExpiresAt == nil { + return false + } + held := GrantOf(login) + if held == nil || held.RefreshTokenExpiresAt == nil { + return true + } + if sameGeneration(held.RefreshTokenExpiresAt, offered.RefreshTokenExpiresAt) { + return offered.ExpiresAt > held.ExpiresAt + } + return *offered.RefreshTokenExpiresAt > *held.RefreshTokenExpiresAt +} + +// LoginNotHanded says the file holds a login that was never handed to the manager: handed is the fingerprint +// of the refresh token claude_code_grant last sealed, "" when none was. Such a login is newer than anything the +// manager holds, so no grant may overwrite it before the manager adopts it (ADR 0206, ADR 0209). +func LoginNotHanded(c Credentials, handed string) bool { + rt := RefreshTokenOf(c) + return rt != "" && Fingerprint(rt) != handed +} + // RefreshTokenOf is the refresh token a login left, or "". func RefreshTokenOf(c Credentials) string { rt, _ := c.oauth()["refreshToken"].(string) diff --git a/modules/claude-code/cmd/claude-code/guard.go b/modules/claude-code/cmd/claude-code/guard.go deleted file mode 100644 index 9dd2e00bd..000000000 --- a/modules/claude-code/cmd/claude-code/guard.go +++ /dev/null @@ -1,811 +0,0 @@ -package main - -// The guard on the agent's shell (novox/hq ADR 0245): a PreToolUse hook every session on a machine of the -// mesh runs before a shell command or a file edit, delivered in the module's plugin. -// -// It refuses three work-arounds, each with the mesh tool that does the job when one says it replaces the -// command, and otherwise with the rule that a missing tool is created, never worked around: -// -// 1. **ssh to a mesh machine** — `ssh`, `scp`, `sftp`, `rsync`, `mosh` or `autossh` to a machine's name, a -// name under its domains, any `*.internal` name, or one of its addresses; a jump through one too. The -// destination is read as ssh itself reads it (`ssh -G`), so an alias in ~/.ssh/config is no way round. -// **Stated, not silent**: an ssh login as `git` is the forge's account, which runs git and nothing -// else — so `git push` over ssh, and `ssh -T git@`, reach no machine and pass. A git remote is -// never an ssh command line anyway. -// 2. **writing /etc/hosts or /etc/resolv.conf** — by redirect, tee, sed -i, an editor, cp/mv/install onto -// it, or the agent's own Edit and Write tools: a mesh name is the mesh's resolvers' (ADR 0194), and a -// machine's hosts file is its node-hostname seat's. -// 3. **HOSTALIASES**, named anywhere in a command line. -// -// And it refuses any command that names the operator's override, so the agent never sets it (guard_run.go). -// -// The matching is on the command line as a shell would split it — quotes, separators, `$(…)`, `bash -c` — -// and wrappers such as sudo, env and timeout are looked through. It is a guard against the habit of reaching -// for ssh, not a sandbox: a command built to hide what it runs can hide it, and the record of what was -// refused (the module's `guard.log`, read by `claude_code_guard`) is how a habit that found a way round is seen. - -import ( - "fmt" - "net" - "net/url" - "path" - "path/filepath" - "sort" - "strings" -) - -// GuardData is what the hook is given: this machine, the mesh's machines, what replaces what, and where -// its record is kept. Written beside the hook on every render, root's, so the session cannot change it. -type GuardData struct { - Node string `json:"node"` - Machines []Machine `json:"machines"` - Replacements []Replacement `json:"replacements"` - Log string `json:"log"` - // Agent is the account every session here must run as, where the machine names an agent account of its - // own (novox/hq ADR 0266); empty where agents run as the operator. - Agent string `json:"agent,omitempty"` -} - -// HookInput is what the agent hands a PreToolUse hook. -type HookInput struct { - ToolName string `json:"tool_name"` - ToolInput map[string]any `json:"tool_input"` - Cwd string `json:"cwd"` - SessionID string `json:"session_id"` -} - -// Verdict is the guard's answer. -type Verdict struct { - Refuse bool `json:"refuse"` - Rule string `json:"rule,omitempty"` // ssh | hosts-file | hostaliases | override-named | account - Machine string `json:"machine,omitempty"` - Message string `json:"message,omitempty"` - // Overridable is false for a refusal no override lifts: the agent naming the override itself. - Overridable bool `json:"-"` - // Calls are the tools the refusal named, by address without a machine: what the instructions' table - // puts first, the tools the agent most reached round. - Calls []string `json:"calls,omitempty"` -} - -// OverrideVar is the operator's override: set in the operator's own shell before the session starts, -// with why as its value. Read from the session's own environment as it was started, never from what a -// command or a setting put there (guard_run.go). -const OverrideVar = "MESH_GUARD_OVERRIDE" - -// ForgeUser is the forge's ssh account: it runs git, never a shell (stated in ADR 0245). -const ForgeUser = "git" - -// protectedFiles are the files a session never writes for a mesh name. -var protectedFiles = map[string]bool{"/etc/hosts": true, "/etc/resolv.conf": true} - -// SSHView is how ssh itself reads a destination with these options: the host it connects to, the user, -// and the jumps. Empty host when ssh could not say. -type SSHView func(options []string, destination string) (host, user string, jumps []string) - -// Guard judges what a session is about to do. -type Guard struct { - Data GuardData - // SSH reads a destination as ssh does (`ssh -G`); nil reads it from the command line alone. - SSH SSHView - // Resolve is a name's addresses, for a name that is none of the mesh's but may point at a machine. - Resolve func(string) []string -} - -// JudgeAs is the verdict on one tool call of a session running as an account. **On a machine whose agents run -// as an account of their own, a session running as any other does nothing** (novox/hq ADR 0266): the -// operator's account there may become root without a person, and an agent started in it by habit would carry -// that into every command. Refused whatever the command, and no override lifts it — the operator's own shell is -// how the operator acts as themselves. -func (g Guard) JudgeAs(account string, in HookInput) Verdict { - if g.Data.Agent != "" && account != g.Data.Agent { - return Verdict{Refuse: true, Rule: "account", Message: fmt.Sprintf("Refused: on %s agents run as %s, an "+ - "account that cannot become root without a person, and this session runs as %s (novox/hq ADR 0266). "+ - "No tool it calls here is let through. End it, and start the agent with `claude-agent`, which runs it as "+ - "%s; what needs the operator's own rights is the operator's to run in their own shell.", - orThisMachine(g.Data.Node), g.Data.Agent, account, g.Data.Agent)} - } - return g.Judge(in) -} - -func orThisMachine(node string) string { - if node == "" { - return "this machine" - } - return node -} - -// Judge is the verdict on one tool call. -func (g Guard) Judge(in HookInput) Verdict { - switch in.ToolName { - case "Bash": - command, _ := in.ToolInput["command"].(string) - return g.judgeLine(command, 0) - case "Edit", "Write", "MultiEdit", "NotebookEdit": - for _, key := range []string{"file_path", "notebook_path"} { - if p, _ := in.ToolInput[key].(string); p != "" && protectedFiles[filepath.Clean(p)] { - return g.hostsFile(filepath.Clean(p), in.ToolName+" "+filepath.Clean(p)) - } - } - } - return Verdict{} -} - -func (g Guard) judgeLine(line string, depth int) Verdict { - if depth > 4 { - return Verdict{} - } - if strings.Contains(line, OverrideVar) { - return Verdict{Refuse: true, Rule: "override-named", Message: fmt.Sprintf( - "Refused by the mesh's guard (novox/hq ADR 0245): this command names %s, the operator's override. "+ - "It is the operator's alone, set in their own shell before a session starts; a session never sets, "+ - "reads or passes it.", OverrideVar)} - } - if strings.Contains(line, "HOSTALIASES") { - return g.refuseLocal("hostaliases", "HOSTALIASES", "setting HOSTALIASES") - } - for _, words := range simpleCommands(line) { - if v := g.judgeCommand(words, depth); v.Refuse { - return v - } - // What a word runs in its own shell: `$(…)` and backticks inside a quoted word. - for _, w := range words { - for _, inner := range substitutions(w) { - if v := g.judgeLine(inner, depth+1); v.Refuse { - return v - } - } - } - } - return Verdict{} -} - -// wrappers run the command after them; each with the options that take a value. -var wrappers = map[string]string{ - "sudo": "ugCDhpTrt", "doas": "uC", "env": "uSC", "timeout": "sk", "nohup": "", "nice": "n", "ionice": "cnpP", - "command": "", "exec": "a", "time": "fo", "stdbuf": "ioe", "xargs": "aEdIiLlnPs", "setsid": "", "unbuffer": "", - "chronic": "", "flock": "wE", "torsocks": "", "proxychains": "f", "proxychains4": "f", "caffeinate": "", -} - -// shells run their -c argument as a command line. -var shells = map[string]bool{"sh": true, "bash": true, "zsh": true, "dash": true, "ksh": true, "fish": true, "eval": true} - -func (g Guard) judgeCommand(words []string, depth int) Verdict { - words = unwrap(words) - if len(words) == 0 { - return Verdict{} - } - name := path.Base(words[0]) - args := words[1:] - if shells[name] { - if name == "eval" { - return g.judgeLine(strings.Join(args, " "), depth+1) - } - for i, a := range args { - if strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "--") && strings.Contains(a, "c") && i+1 < len(args) { - return g.judgeLine(args[i+1], depth+1) - } - } - } - switch name { - case "ssh", "autossh", "mosh", "slogin": - return g.judgeSSH(name, args, strings.Join(words, " ")) - case "scp", "sftp", "rsync": - return g.judgeCopy(name, args, strings.Join(words, " ")) - } - if target := writesProtected(name, args); target != "" { - return g.hostsFile(target, strings.Join(words, " ")) - } - return Verdict{} -} - -// unwrap takes off what only runs the command: assignments before it, and wrappers with their options. -func unwrap(words []string) []string { - for len(words) > 0 { - w := words[0] - switch { - case w == "!" || w == "{" || w == "}" || w == "then" || w == "do" || w == "else" || w == "if" || w == "while" || - w == "until" || w == "elif": - words = words[1:] - case isAssignment(w): - words = words[1:] - default: - opts, wrapper := wrappers[path.Base(w)] - if !wrapper { - return words - } - base := path.Base(w) - words = words[1:] - for len(words) > 0 { - a := words[0] - if a == "--" { - words = words[1:] - break - } - if base == "env" && isAssignment(a) { - words = words[1:] - continue - } - if !strings.HasPrefix(a, "-") || a == "-" { - break - } - words = words[1:] - if strings.HasPrefix(a, "--") { - continue - } - if f := a[len(a)-1:]; strings.Contains(opts, f) && len(words) > 0 { - words = words[1:] - } - } - // timeout's duration, nice's adjustment as a word: a number before the command. - if (base == "timeout") && len(words) > 0 { - words = words[1:] - } - } - } - return words -} - -func isAssignment(w string) bool { - i := strings.Index(w, "=") - if i <= 0 { - return false - } - for _, r := range w[:i] { - if !(r == '_' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9') { - return false - } - } - return true -} - -// sshOptionsWithValue are ssh's single-letter options that take a value. -const sshOptionsWithValue = "BbcDEeFIiJLlmOoPpQRSWw" - -func (g Guard) judgeSSH(name string, args []string, line string) Verdict { - var options, jumps []string - user := "" - dest, rest := "", []string(nil) - for i := 0; i < len(args); i++ { - a := args[i] - if a == "--" { - if i+1 < len(args) { - dest, rest = args[i+1], args[i+2:] - } - break - } - if name == "autossh" && strings.HasPrefix(a, "-M") { - if a == "-M" { - i++ // autossh's own: the monitoring port - } - continue - } - if strings.HasPrefix(a, "-") && len(a) > 1 { - options = append(options, a) - if name == "mosh" || strings.HasPrefix(a, "--") { - continue // mosh's own options are long, each with its value after `=` - } - for j := 1; j < len(a); j++ { - if !strings.ContainsRune(sshOptionsWithValue, rune(a[j])) { - continue - } - value := a[j+1:] - if value == "" && i+1 < len(args) { - i++ - value = args[i] - options = append(options, value) - } - switch a[j] { - case 'J': - jumps = append(jumps, strings.Split(value, ",")...) - case 'l': - user = value - case 'o': - k, v, _ := strings.Cut(value, "=") - switch strings.ToLower(strings.TrimSpace(k)) { - case "proxyjump": - jumps = append(jumps, strings.Split(v, ",")...) - case "user": - user = strings.TrimSpace(v) - } - } - break - } - continue - } - dest, rest = a, args[i+1:] - break - } - if dest == "" { - return Verdict{} - } - host, destUser := hostOf(dest) - if destUser != "" { - user = destUser - } - if g.SSH != nil && name != "mosh" { - if h, u, j := g.SSH(options, dest); h != "" { - host, user = h, u - jumps = append(jumps, j...) - } - } - remote := strings.Join(rest, " ") - for _, jump := range jumps { - jh, ju := hostOf(jump) - if machine, ok := g.meshHost(jh); ok && ju != ForgeUser { - return g.refuseSSH(machine, jh, remote, line) - } - } - if user == ForgeUser { - return Verdict{} // the forge's account: git and nothing else (stated in ADR 0245) - } - if machine, ok := g.meshHost(host); ok { - return g.refuseSSH(machine, host, remote, line) - } - return Verdict{} -} - -// judgeCopy reads scp's, sftp's and rsync's remote paths, `[user@]host:path` or `scp://[user@]host/…`. -func (g Guard) judgeCopy(name string, args []string, line string) Verdict { - for i := 0; i < len(args); i++ { - a := args[i] - if strings.HasPrefix(a, "-") { - if name != "rsync" && len(a) == 2 && strings.ContainsRune("cFiJloPSXBRD", rune(a[1])) { - i++ - } - if name == "rsync" && (a == "-e" || a == "--rsh") { - i++ - } - continue - } - var host, user string - if strings.Contains(a, "://") { - host, user = hostOf(a) - } else if colon := strings.Index(a, ":"); colon > 0 && !strings.Contains(a[:colon], "/") { - host, user = hostOf(a[:colon]) - } else if name == "sftp" { - host, user = hostOf(a) - } else { - continue - } - if user == ForgeUser { - continue - } - if g.SSH != nil { - if h, u, _ := g.SSH(nil, host); h != "" { - host = h - if u == ForgeUser && user == "" { - continue - } - } - } - if machine, ok := g.meshHost(host); ok { - return g.refuseSSH(machine, host, "", line) - } - } - return Verdict{} -} - -// hostOf reads `[user@]host[:port]`, `ssh://[user@]host[:port]/…` or `[v6]`. -func hostOf(dest string) (host, user string) { - if strings.Contains(dest, "://") { - if u, err := url.Parse(dest); err == nil { - return strings.ToLower(u.Hostname()), u.User.Username() - } - } - if at := strings.LastIndex(dest, "@"); at >= 0 { - user, dest = dest[:at], dest[at+1:] - } - if strings.HasPrefix(dest, "[") { - if end := strings.Index(dest, "]"); end > 0 { - return strings.ToLower(dest[1:end]), user - } - } - if h, _, err := net.SplitHostPort(dest); err == nil && strings.Count(dest, ":") == 1 { - dest = h - } - return strings.TrimSuffix(strings.ToLower(dest), "."), user -} - -// meshHost says whether a host is one of the mesh's machines, and which when it can tell. -func (g Guard) meshHost(host string) (string, bool) { - host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".") - if host == "" { - return "", false - } - if ip := net.ParseIP(host); ip != nil { - for _, m := range g.Data.Machines { - for _, a := range m.Addresses { - if b := net.ParseIP(a); b != nil && b.Equal(ip) { - return m.Name, true - } - } - } - return "", false - } - for _, m := range g.Data.Machines { - if host == strings.ToLower(m.Name) { - return m.Name, true - } - for _, d := range m.Domains { - if host == d || strings.HasSuffix(host, "."+d) { - return m.Name, true - } - } - } - if strings.HasSuffix(host, InternalSuffix) { - return "", true - } - if g.Resolve != nil && !strings.Contains(host, "/") { - for _, a := range g.Resolve(host) { - if m, ok := g.meshHost(a); ok && net.ParseIP(a) != nil { - return m, true - } - } - } - return "", false -} - -// writesProtected is the protected file a command writes, or "". -func writesProtected(name string, args []string) string { - protected := func(a string) string { - a = strings.Trim(a, `"'`) - if strings.HasPrefix(a, "of=") { - a = a[3:] - } - if protectedFiles[filepath.Clean(a)] { - return filepath.Clean(a) - } - return "" - } - // A redirect onto it, from any command. - for i, a := range args { - if (a == ">" || a == ">>") && i+1 < len(args) { - if p := protected(args[i+1]); p != "" { - return p - } - } - } - operands := func() []string { - var out []string - for i := 0; i < len(args); i++ { - if args[i] == ">" || args[i] == ">>" || args[i] == "<" { - i++ - continue - } - out = append(out, args[i]) - } - return out - }() - switch name { - case "tee", "vi", "vim", "nvim", "nano", "emacs", "ed", "ex", "micro", "hx", "helix", "kak", "gedit", "code", - "truncate", "chattr", "chmod", "chown", "rm", "unlink", "shred", "dd", "sponge", "visudo", "vipw": - for _, a := range operands { - if p := protected(a); p != "" { - return p - } - } - case "sed", "perl", "ruby", "awk", "gawk": - inPlace := false - for _, a := range operands { - switch { - case name == "awk" || name == "gawk": - inPlace = inPlace || a == "inplace" - case strings.HasPrefix(a, "--in-place"): - inPlace = true - case strings.HasPrefix(a, "-") && !strings.HasPrefix(a, "--") && strings.Contains(a, "i"): - inPlace = true - } - } - if inPlace { - for _, a := range operands { - if p := protected(a); p != "" { - return p - } - } - } - case "cp", "mv", "install", "ln", "rsync": - var files []string - for _, a := range operands { - if !strings.HasPrefix(a, "-") { - files = append(files, a) - } - } - if len(files) > 1 { - if p := protected(files[len(files)-1]); p != "" { - return p - } - } - } - return "" -} - -// replacementsFor are the mesh's tools that replace a command, the most specific first, each address once. -func (g Guard) replacementsFor(command string) []string { - have := commandWordsOf(command) - type found struct { - address string - weight int - replace string - } - var all []found - for _, r := range g.Data.Replacements { - best := 0 - which := "" - for _, c := range r.Replaces { - want := commandWordsOf(c) - if inOrderWords(want, have) && len(want) > best { - best, which = len(want), c - } - } - if best > 0 { - all = append(all, found{r.Address, best, which}) - } - } - sort.SliceStable(all, func(i, j int) bool { return all[i].weight > all[j].weight }) - var out []string - for _, f := range all { - out = append(out, f.address+"\x00"+f.replace) - } - return out -} - -// callFor is how an address is called for a machine. -func (g Guard) callFor(address, machine string) string { - for _, r := range g.Data.Replacements { - if r.Address != address || !r.NodeScoped { - continue - } - on := machine - if !r.Seat && len(r.On) > 0 && !containsString(r.On, machine) { - on = r.On[0] - } - if on == "" { - on = "" - } - return on + "/" + address - } - return address -} - -func containsString(xs []string, s string) bool { - for _, x := range xs { - if x == s { - return true - } - } - return false -} - -// exact is the replacement that names this exact command, or "". -func (g Guard) exact(command string) string { - for _, r := range g.Data.Replacements { - for _, c := range r.Replaces { - if c == command { - return r.Address - } - } - } - return "" -} - -const missingTool = "No mesh tool says it replaces this. Do not work around it: a missing tool is created in the module " + - "that owns the thing, on the seat it occupies — say what is missing to the operator. First make sure with " + - "`mesh_search` and the command's own words." - -func (g Guard) refuseSSH(machine, host, remote, line string) Verdict { - who := machine - if who == "" { - who = host + " (a mesh name)" - } - var b strings.Builder - var named []string - fmt.Fprintf(&b, "Refused by the mesh's guard (novox/hq ADR 0245): `%s` reaches %s round the mesh's tools.\n", cut(line, 160), who) - switch { - case strings.TrimSpace(remote) == "": - target := machine - if target == "" { - target = "" - } - fmt.Fprintf(&b, "What a machine serves is `mesh_machine %s`; `mesh_search` with what you meant to run finds its tool.\n", target) - default: - calls := g.replacementsFor(remote) - if len(calls) == 0 { - b.WriteString(missingTool + "\n") - break - } - b.WriteString("Call instead, through `mesh_call`:\n") - for i, c := range calls { - if i == 3 { - break - } - address, replaces, _ := strings.Cut(c, "\x00") - named = append(named, address) - fmt.Fprintf(&b, " %s — replaces `%s`\n", g.callFor(address, machine), replaces) - } - } - return Verdict{Refuse: true, Rule: "ssh", Machine: machine, Message: strings.TrimRight(b.String(), "\n"), Overridable: true, - Calls: named} -} - -func (g Guard) refuseLocal(rule, replaced, what string) Verdict { - var b strings.Builder - fmt.Fprintf(&b, "Refused by the mesh's guard (novox/hq ADR 0245): %s is a work-around for a mesh name. "+ - "A mesh name is the mesh's resolvers' to answer, and a machine's own lines in /etc/hosts are its node-hostname seat's.\n", what) - var named []string - if address := g.exact(replaced); address != "" { - named = append(named, address) - fmt.Fprintf(&b, "Call instead, through `mesh_call`: %s — replaces `%s`", g.callFor(address, g.Data.Node), replaced) - } else { - b.WriteString(missingTool) - } - return Verdict{Refuse: true, Rule: rule, Machine: g.Data.Node, Message: b.String(), Overridable: true, Calls: named} -} - -func (g Guard) hostsFile(file, line string) Verdict { - replaced := "edit " + file - return g.refuseLocal("hosts-file", replaced, fmt.Sprintf("writing %s (`%s`)", file, cut(line, 120))) -} - -func cut(s string, n int) string { - s = strings.Join(strings.Fields(s), " ") - if r := []rune(s); len(r) > n { - return string(r[:n-1]) + "…" - } - return s -} - -// commandWordsOf are a command line's words as matched against a replaced command (the mesh MCP server's search rule): -// lower-cased, a program by path reduced to its name, sudo left out. -func commandWordsOf(line string) []string { - var out []string - for i, w := range strings.Fields(strings.ToLower(line)) { - if i == 0 || strings.HasPrefix(w, "/") { - w = path.Base(w) - } - if w == "sudo" { - continue - } - out = append(out, w) - } - return out -} - -func inOrderWords(want, have []string) bool { - i := 0 - for _, h := range have { - if i < len(want) && h == want[i] { - i++ - } - } - return len(want) > 0 && i == len(want) -} - -// ---- the shell's words ------------------------------------------------------------------------------ - -// simpleCommands splits a command line as a shell would into its simple commands' words: quotes -// removed, `;`, `&`, `|`, `&&`, `||`, newlines, parentheses and backticks between commands, `$(` opening -// one; `>` and `>>` kept as words of their own, before what they redirect to. -func simpleCommands(line string) [][]string { - var out [][]string - var words []string - var cur strings.Builder - inWord := false - flushWord := func() { - if inWord { - words = append(words, cur.String()) - cur.Reset() - inWord = false - } - } - flushCommand := func() { - flushWord() - if len(words) > 0 { - out = append(out, words) - } - words = nil - } - r := []rune(line) - for i := 0; i < len(r); i++ { - c := r[i] - switch { - case c == '\\' && i+1 < len(r): - i++ - if r[i] != '\n' { - cur.WriteRune(r[i]) - inWord = true - } - case c == '\'': - inWord = true - for i++; i < len(r) && r[i] != '\''; i++ { - cur.WriteRune(r[i]) - } - case c == '"': - inWord = true - for i++; i < len(r) && r[i] != '"'; i++ { - if r[i] == '\\' && i+1 < len(r) && strings.ContainsRune("\"\\$`", r[i+1]) { - i++ - } - cur.WriteRune(r[i]) - } - case c == '$' && i+1 < len(r) && r[i+1] == '(': - flushCommand() - i++ - case c == ';' || c == '&' || c == '|' || c == '\n' || c == '(' || c == ')' || c == '`': - flushCommand() - case c == '>' || c == '<': - // A file descriptor before it (`2>`) is not a word. - if inWord && isDigits(cur.String()) { - cur.Reset() - inWord = false - } - flushWord() - op := string(c) - if c == '>' && i+1 < len(r) && r[i+1] == '>' { - op = ">>" - i++ - } - if i+1 < len(r) && (r[i+1] == '&' || r[i+1] == '|') { - i++ - } - words = append(words, op) - case c == ' ' || c == '\t': - flushWord() - case c == '#' && !inWord: - for i < len(r) && r[i] != '\n' { - i++ - } - flushCommand() - default: - cur.WriteRune(c) - inWord = true - } - } - flushCommand() - return out -} - -func isDigits(s string) bool { - if s == "" { - return false - } - for _, r := range s { - if r < '0' || r > '9' { - return false - } - } - return true -} - -// substitutions are the command lines a quoted word runs in a shell of its own: `$(…)` and `…`. -func substitutions(word string) []string { - var out []string - for { - i := strings.Index(word, "$(") - if i < 0 { - break - } - rest := word[i+2:] - depth, end := 1, len(rest) - for j, c := range rest { - if c == '(' { - depth++ - } else if c == ')' { - depth-- - if depth == 0 { - end = j - break - } - } - } - out = append(out, rest[:end]) - if end >= len(rest) { - break - } - word = rest[end+1:] - } - parts := strings.Split(word, "`") - for i := 1; i < len(parts); i += 2 { - out = append(out, parts[i]) - } - return out -} diff --git a/modules/claude-code/cmd/claude-code/guard_run.go b/modules/claude-code/cmd/claude-code/guard_run.go deleted file mode 100644 index c135271a6..000000000 --- a/modules/claude-code/cmd/claude-code/guard_run.go +++ /dev/null @@ -1,315 +0,0 @@ -package main - -// The guard as the hook runs it (novox/hq ADR 0245): `claude-code guard `, the tool call on -// standard input, exit 2 with the reason on standard error to refuse — the agent reads it — and 0 to let it be. -// -// **The operator's override.** `MESH_GUARD_OVERRIDE=` lets one session through a refusal — never the -// refusal of a command naming the override itself — and only: -// -// - **from the session's environment as it was started**: read from /proc//environ of the agent's own -// process, which is fixed at exec. A command's `export`, an `env` key in a settings file, a variable the -// session sets for its tools — none of them reaches it. A nested session the agent starts with the -// variable is refused before it starts: the command names the override; -// - **recorded**: every override is a line in the module's guard.log — or, where the agent runs as an account -// of its own, in the machine's journal (novox/hq ADR 0266) — with why, the command and the machine; an -// override that cannot be recorded is not honoured. Refusals are recorded the same way. -// -// A guard that fails — a fault in this code — exits 1, which the agent shows and does not block on: a guard -// that refused every command would stop the session the operator needs to repair it. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net" - "os" - "os/exec" - "os/user" - "path/filepath" - "strconv" - "strings" - "time" -) - -// procRoot and parentPID are where the session's process is found; a test points them at its own. -var ( - procRoot = "/proc" - parentPID = os.Getppid -) - -// GuardLogMax is the size the guard's record grows to before it is kept once as guard.log.1. -const GuardLogMax = 1 << 20 - -// GuardEntry is one line of the guard's record. -type GuardEntry struct { - At string `json:"at"` - Node string `json:"node,omitempty"` - Decision string `json:"decision"` // refused | overridden - Rule string `json:"rule"` - Machine string `json:"machine,omitempty"` - Tool string `json:"tool"` - Command string `json:"command"` - Why string `json:"why,omitempty"` - // Tools are the tools the refusal named instead. - Tools []string `json:"tools,omitempty"` - Session string `json:"session,omitempty"` -} - -// JournalRecord is the guard's record where the agent runs as an account of its own (novox/hq ADR 0266): the -// session's account cannot enter the module's state, and must not be able to rewrite what it was refused, so -// each line goes to the machine's journal, which the account may add to and not change. The record's -// location is then this prefix and the journal's identifier. -const JournalRecord = "journal:" - -// GuardJournalID is the identifier the guard's lines carry in the journal. -const GuardJournalID = "mesh-claude-code-guard" - -// journalSocket is where the journal takes a line; a test points it at its own. -var journalSocket = "/run/systemd/journal/socket" - -// RecordGuard appends one line to the record. -func RecordGuard(path string, e GuardEntry) error { - if path == "" { - return fmt.Errorf("no record is kept here") - } - if id, ok := strings.CutPrefix(path, JournalRecord); ok { - return recordInJournal(id, e) - } - if info, err := os.Stat(path); err == nil && info.Size() > GuardLogMax { - _ = os.Rename(path, path+".1") - } - f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) - if err != nil { - return err - } - raw, _ := json.Marshal(e) - if _, err := f.Write(append(raw, '\n')); err != nil { - f.Close() - return err - } - return f.Close() -} - -// recordInJournal says one line to the journal by its native protocol: the entry as JSON in MESSAGE, one line, -// so nothing in a command can add a field of its own. -func recordInJournal(id string, e GuardEntry) error { - raw, err := json.Marshal(e) - if err != nil { - return err - } - conn, err := net.Dial("unixgram", journalSocket) - if err != nil { - return fmt.Errorf("the journal cannot be reached: %w", err) - } - defer conn.Close() - _, err = conn.Write([]byte("SYSLOG_IDENTIFIER=" + id + "\nPRIORITY=5\nMESSAGE=" + string(raw) + "\n")) - return err -} - -// readJournal is the journal's last lines of the guard's record, read as root through the runtime account's -// sudo where this process is not root: what other accounts said is not the runtime account's to read. As JSON, -// with the field the journal itself sets for the program that wrote the line (_EXE), which no writer chooses — -// and matched on it in the query itself, so lines another program wrote under the guard's identifier cannot -// push the guard's own past the last ones read. -var readJournal = func(id string, last int) ([]byte, error) { - args := []string{"journalctl", "-q", "--no-pager", "-o", "json", "--output-fields=MESSAGE,_EXE", "-t", id, - "_EXE=" + HelperPath(), "-n", strconv.Itoa(last)} - if os.Geteuid() != 0 { - args = append([]string{"sudo", "-n"}, args...) - } - cmd := exec.Command(args[0], args[1:]...) - cmd.Env = append(os.Environ(), "LC_ALL=C", "LANG=C") - return cmd.Output() -} - -// guardsOwnLines keeps, of the journal's JSON lines, the messages the guard's own binary wrote (novox/hq ADR -// 0266). The agent's account may add to the journal under any identifier — `logger -t` — and the journal -// says which program wrote each line; a line another program wrote under the guard's identifier is not the -// guard's record. The agent can still run the guard's binary itself, so the record is the guard's words, not -// proof that each refusal happened in a session: what it cannot do is remove one. -func guardsOwnLines(raw []byte, exe string) []byte { - var out []byte - for _, line := range bytes.Split(raw, []byte("\n")) { - var f struct { - Message any `json:"MESSAGE"` - Exe string `json:"_EXE"` - } - if json.Unmarshal(line, &f) != nil || f.Exe != exe { - continue - } - if m, ok := f.Message.(string); ok { - out = append(append(out, m...), '\n') - } - } - return out -} - -// ReadGuardLog is the record's last lines, newest last. -func ReadGuardLog(path string, last int) []GuardEntry { - read := os.ReadFile - if id, ok := strings.CutPrefix(path, JournalRecord); ok { - read = func(string) ([]byte, error) { - raw, err := readJournal(id, last) - return guardsOwnLines(raw, HelperPath()), err - } - } - raw, err := read(path) - if err != nil { - return []GuardEntry{} - } - lines := strings.Split(strings.TrimSpace(string(raw)), "\n") - if len(lines) > last { - lines = lines[len(lines)-last:] - } - out := []GuardEntry{} - for _, l := range lines { - var e GuardEntry - if json.Unmarshal([]byte(l), &e) == nil { - out = append(out, e) - } - } - return out -} - -// sshDashG reads a destination as ssh does: `ssh -G` prints the configuration it would use and connects -// to nothing, so an alias, a HostName and a ProxyJump in ~/.ssh/config are what is judged. -func sshDashG(options []string, destination string) (host, user string, jumps []string) { - if _, err := exec.LookPath("ssh"); err != nil { - return "", "", nil - } - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - args := append([]string{"-G"}, options...) - args = append(args, "--", destination) - out, err := exec.CommandContext(ctx, "ssh", args...).Output() - if err != nil { - return "", "", nil - } - for _, line := range strings.Split(string(out), "\n") { - k, v, ok := strings.Cut(strings.TrimSpace(line), " ") - if !ok { - continue - } - switch k { - case "hostname": - host = strings.ToLower(v) - case "user": - user = v - case "proxyjump": - if v != "none" { - jumps = append(jumps, strings.Split(v, ",")...) - } - } - } - return host, user, jumps -} - -func quickLookup(name string) []string { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - addrs, _ := net.DefaultResolver.LookupHost(ctx, name) - return addrs -} - -// sessionEnvironment is the environment the agent's own process was started with: the nearest ancestor -// that is the agent, read from what the kernel kept at its exec. -func sessionEnvironment(proc string, pid int) map[string]string { - for i := 0; i < 32 && pid > 1; i++ { - cmdline, _ := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "cmdline")) - if isAgent(cmdline) { - raw, err := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "environ")) - if err != nil { - return nil - } - env := map[string]string{} - for _, kv := range bytes.Split(raw, []byte{0}) { - if k, v, ok := strings.Cut(string(kv), "="); ok { - env[k] = v - } - } - return env - } - stat, err := os.ReadFile(filepath.Join(proc, strconv.Itoa(pid), "stat")) - if err != nil { - return nil - } - // The parent is the fourth field, after the command's name in parentheses (which may hold spaces). - closing := bytes.LastIndexByte(stat, ')') - fields := strings.Fields(string(stat[closing+1:])) - if len(fields) < 2 { - return nil - } - pid, _ = strconv.Atoi(fields[1]) - } - return nil -} - -// isAgent says whether a process's command line is the agent's: its native binary, or its package run by node. -func isAgent(cmdline []byte) bool { - args := strings.Split(strings.TrimRight(string(cmdline), "\x00"), "\x00") - if len(args) == 0 || args[0] == "" { - return false - } - if filepath.Base(args[0]) == "claude" { - return true - } - if b := filepath.Base(args[0]); (b == "node" || b == "bun") && len(args) > 1 { - return filepath.Base(args[1]) == "claude" || strings.Contains(args[1], "@anthropic-ai/claude-code") - } - return false -} - -// currentAccount is the account the session runs as; a test sets its own. -var currentAccount = func() string { - if u, err := user.Current(); err == nil { - return u.Username - } - return "uid " + strconv.Itoa(os.Getuid()) -} - -// runGuard is the hook: the tool call in, the verdict out as the exit code. -func runGuard(dataPath string, stdin io.Reader, stderr io.Writer) (code int) { - defer func() { - if r := recover(); r != nil { - fmt.Fprintf(stderr, "the mesh's guard failed and judged nothing: %v\n", r) - code = 1 - } - }() - var in HookInput - if err := json.NewDecoder(stdin).Decode(&in); err != nil { - fmt.Fprintf(stderr, "the mesh's guard could not read the tool call: %v\n", err) - return 1 - } - var data GuardData - if raw, err := os.ReadFile(dataPath); err == nil { - _ = json.Unmarshal(raw, &data) - } - g := Guard{Data: data, SSH: sshDashG, Resolve: quickLookup} - v := g.JudgeAs(currentAccount(), in) - if !v.Refuse { - return 0 - } - command, _ := in.ToolInput["command"].(string) - if command == "" { - command, _ = in.ToolInput["file_path"].(string) - } - entry := GuardEntry{At: time.Now().UTC().Format(time.RFC3339), Node: data.Node, Decision: "refused", Rule: v.Rule, - Machine: v.Machine, Tool: in.ToolName, Command: cut(command, 400), Session: in.SessionID, Tools: v.Calls} - if v.Overridable { - if why := strings.TrimSpace(sessionEnvironment(procRoot, parentPID())[OverrideVar]); why != "" { - entry.Decision, entry.Why = "overridden", cut(why, 200) - if err := RecordGuard(data.Log, entry); err == nil { - return 0 - } else { - v.Message += fmt.Sprintf("\nThe operator's override is set, and could not be recorded (%v): an override "+ - "that is not recorded is not honoured.", err) - entry.Decision, entry.Why = "refused", "" - } - } - } - _ = RecordGuard(data.Log, entry) - fmt.Fprintln(stderr, v.Message) - return 2 -} diff --git a/modules/claude-code/cmd/claude-code/guard_test.go b/modules/claude-code/cmd/claude-code/guard_test.go deleted file mode 100644 index aedd86b78..000000000 --- a/modules/claude-code/cmd/claude-code/guard_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "os" - "path/filepath" - "strconv" - "strings" - "testing" - - "git.novox.be/novox/mesh-sdk/go/seatdef" -) - -// meshForTheGuard is a mesh of two machines and the verbs that replace what an agent runs over ssh, as the -// seats' contract and the modules' manifests say them. -func meshForTheGuard() GuardData { - defined := []seatdef.Definition{ - {Seat: "mesh-module-assigner", Scope: "mesh", Verbs: []seatdef.Verb{ - {Name: "assignments", Description: "Read assignments: one node's key.", Replaces: []string{"hostnamectl", "uptime"}}}}, - {Seat: "node-service-manager", Scope: "node", Verbs: []seatdef.Verb{ - {Name: "status", Description: "One unit as the service manager sees it now: its states.", Replaces: []string{"systemctl status", "systemctl is-active"}}, - {Name: "restart", Description: "Restart one unit.", Replaces: []string{"systemctl restart"}}, - {Name: "journal", Description: "The last lines of one unit's journal.", Replaces: []string{"journalctl"}}}}, - {Seat: "node-hostname", Scope: "node", Verbs: []seatdef.Verb{ - {Name: "add", Description: "Add one address and its names to the operator's lines of /etc/hosts.", Replaces: []string{"edit /etc/hosts", "HOSTALIASES"}}}}, - } - modules := []ModuleTools{{Module: "docker", On: []string{"anchor"}, Replaces: map[string][]string{"docker_logs": {"docker logs"}, "docker_list": {"docker ps"}}}, - {Module: "systemd", On: []string{"anchor", "laptop"}}} - return GuardData{Node: "laptop", Replacements: ReplacementsOf(defined, modules), Machines: []Machine{ - {Name: "anchor", Domains: []string{"anchor" + InternalSuffix, "anchor.example"}, Addresses: []string{"192.0.2.10", "10.10.0.1"}}, - {Name: "laptop", Domains: []string{"laptop" + InternalSuffix}, Addresses: []string{"10.10.0.4"}}, - }} -} - -// noSSH reads a destination from the command line alone; aliases reads one alias as ssh's configuration would. -func aliases(options []string, destination string) (string, string, []string) { - host, user := hostOf(destination) - switch host { - case "a": - return "anchor.example", "operator", nil - case "via-anchor": - return "203.0.113.5", "operator", []string{"anchor"} - case "forge": - return "git.anchor" + InternalSuffix, "git", nil - } - if user == "" { - user = "operator" - } - for i, o := range options { - if o == "-l" && i+1 < len(options) { - user = options[i+1] - } - } - return host, user, nil -} - -func guard() Guard { - return Guard{Data: meshForTheGuard(), SSH: aliases, Resolve: func(name string) []string { - if name == "nas.lan" { - return []string{"192.0.2.10"} - } - return nil - }} -} - -func bash(command string) HookInput { - return HookInput{ToolName: "Bash", ToolInput: map[string]any{"command": command}} -} - -// **ssh to a mesh machine is refused**, by every name and address it has and however the shell spells it, -// and the refusal names the verb that does the job on that machine (novox/hq ADR 0245). -func TestSSHToAMeshMachineIsRefusedNamingTheTool(t *testing.T) { - g := guard() - for command, want := range map[string]string{ - "ssh anchor journalctl -u mesh-config -n 50": "anchor/node-service-manager.journal", - "ssh anchor 'sudo journalctl -fu sshd'": "anchor/node-service-manager.journal", - "ssh -p 22 root@anchor.example systemctl status nats": "anchor/node-service-manager.status", - "ssh anchor.internal systemctl restart nats": "anchor/node-service-manager.restart", - "ssh -o StrictHostKeyChecking=no 10.10.0.1 docker ps -a": "anchor/docker.docker_list", - "ssh anchor docker logs --tail 100 nats": "anchor/docker.docker_logs", - "ssh laptop docker logs x": "anchor/docker.docker_logs", - "ssh a uptime": "mesh-module-assigner.assignments", - "cd /tmp && ssh anchor journalctl": "anchor/node-service-manager.journal", - "sudo -u root ssh anchor journalctl": "anchor/node-service-manager.journal", - "timeout 10 ssh anchor journalctl": "anchor/node-service-manager.journal", - "env LANG=C ssh anchor journalctl": "anchor/node-service-manager.journal", - "bash -c 'ssh anchor journalctl -u x'": "anchor/node-service-manager.journal", - `echo "$(ssh anchor journalctl -n 5)" | tail`: "anchor/node-service-manager.journal", - "for n in anchor laptop; do ssh $n uptime; done; ssh anchor uptime": "mesh-module-assigner.assignments", - "ssh -J anchor 203.0.113.9 journalctl": "anchor/node-service-manager.journal", - "ssh via-anchor journalctl": "anchor/node-service-manager.journal", - "ssh nas.lan journalctl": "anchor/node-service-manager.journal", - "ssh ssh://anchor:2222 journalctl": "anchor/node-service-manager.journal", - } { - v := g.Judge(bash(command)) - if !v.Refuse || v.Rule != "ssh" { - t.Errorf("%q was not refused: %+v", command, v) - continue - } - if !strings.Contains(v.Message, want) { - t.Errorf("%q: the refusal does not name %s:\n%s", command, want, v.Message) - } - } -} - -// What no tool replaces is refused all the same, saying a tool is created, never worked around; a shell -// on a machine is pointed at what the machine serves; copying a file off one is refused too. -func TestSSHWithNoToolForItSaysCreateOne(t *testing.T) { - g := guard() - for command, want := range map[string]string{ - "ssh anchor cat /var/lib/thing/state.json": "a missing tool is created in the module", - "ssh anchor": "mesh_machine anchor", - "ssh build.internal ls": "a missing tool is created", - "scp anchor:/etc/nats/nats.conf /tmp/": "mesh_machine anchor", - "rsync -av root@10.10.0.4:/srv/ ./srv/": "mesh_machine laptop", - "sftp anchor.example": "mesh_machine anchor", - "mosh anchor": "mesh_machine anchor", - "autossh -M 0 -N -L 5432:localhost:5432 anchor": "mesh_machine anchor", - } { - v := g.Judge(bash(command)) - if !v.Refuse { - t.Errorf("%q was not refused", command) - continue - } - if !strings.Contains(v.Message, want) { - t.Errorf("%q: want %q in:\n%s", command, want, v.Message) - } - } -} - -// **What is not a work-around passes**: git over ssh to the forge above all, and ssh beyond the mesh, and -// every command that merely mentions ssh or a machine. -func TestWhatIsNotAWorkAroundPasses(t *testing.T) { - g := guard() - for _, command := range []string{ - "git push -u origin feat/x", - "git clone ssh://git@git.anchor.internal:222/novox/hq.git", - "git fetch ssh://git@git.anchor.internal:222/novox/hq.git main", - `GIT_SSH_COMMAND="ssh -i ~/.ssh/forge -o IdentitiesOnly=yes" git push origin HEAD`, - "git -c core.sshCommand='ssh -p 222' pull", - "ssh -T git@git.anchor.internal -p 222", - "ssh forge", - "scp git@git.anchor.internal:novox/hq.git .", - "ssh github.com", - "ssh -T git@github.com", - "ssh user@203.0.113.7 uptime", - "ssh -V", - "ssh-keygen -t ed25519 -f ~/.ssh/x", - "ssh-add -l", - "man ssh", - "grep -r 'ssh anchor' docs/", - `git commit -m "Stop running ssh anchor journalctl"`, - "echo anchor && journalctl --user -n 5", - "cat /etc/hosts", - "getent hosts anchor.internal", - "cp /etc/hosts /tmp/hosts.copy", - "sed -n 1,5p /etc/hosts", - "curl -s http://anchor.internal:8080/health", - "go test ./...", - } { - if v := g.Judge(bash(command)); v.Refuse { - t.Errorf("%q was refused:\n%s", command, v.Message) - } - } - if v := g.Judge(HookInput{ToolName: "Read", ToolInput: map[string]any{"file_path": "/etc/hosts"}}); v.Refuse { - t.Errorf("reading /etc/hosts was refused") - } - if v := g.Judge(HookInput{ToolName: "Write", ToolInput: map[string]any{"file_path": "/tmp/hosts"}}); v.Refuse { - t.Errorf("writing a file named hosts elsewhere was refused") - } -} - -// **The local work-arounds for a mesh name are refused** with the machine's own hosts verb: writing -// /etc/hosts by any means, the agent's own Edit and Write included, and HOSTALIASES. -func TestTheLocalWorkAroundsForAMeshNameAreRefused(t *testing.T) { - g := guard() - for _, command := range []string{ - "echo '10.10.0.1 anchor' | sudo tee -a /etc/hosts", - "sudo sh -c 'echo 10.10.0.1 anchor >> /etc/hosts'", - "echo x >>/etc/hosts", - "sudo sed -i 's/old/new/' /etc/hosts", - "sudo sed -Ei.bak 's/a/b/' /etc/hosts", - "sudo vim /etc/hosts", - "sudo cp /tmp/hosts /etc/hosts", - "sudo install -m 644 hosts /etc/hosts", - "HOSTALIASES=~/.hosts curl http://anchor/", - "export HOSTALIASES=/tmp/aliases", - } { - v := g.Judge(bash(command)) - if !v.Refuse { - t.Errorf("%q was not refused", command) - continue - } - if !strings.Contains(v.Message, "laptop/node-hostname.add") { - t.Errorf("%q: the refusal does not name this machine's hosts verb:\n%s", command, v.Message) - } - } - for _, tool := range []string{"Edit", "Write", "MultiEdit"} { - v := g.Judge(HookInput{ToolName: tool, ToolInput: map[string]any{"file_path": "/etc/../etc/hosts"}}) - if !v.Refuse || !strings.Contains(v.Message, "node-hostname.add") { - t.Errorf("%s of /etc/hosts was not refused with the verb: %+v", tool, v) - } - } - // The resolver file has no verb that replaces writing it: the refusal says to create one. - v := g.Judge(bash("echo nameserver 192.0.2.53 | sudo tee /etc/resolv.conf")) - if !v.Refuse || !strings.Contains(v.Message, "a missing tool is created") { - t.Errorf("writing the resolver file: %+v", v) - } -} - -// The agent never names the operator's override, and no override lifts that refusal. -func TestACommandNamingTheOverrideIsRefused(t *testing.T) { - g := guard() - for _, command := range []string{ - "export " + OverrideVar + "=because", - OverrideVar + "=x claude -p 'ssh anchor uptime'", - "env " + OverrideVar + "=1 bash", - } { - v := g.Judge(bash(command)) - if !v.Refuse || v.Rule != "override-named" || v.Overridable { - t.Errorf("%q: %+v", command, v) - } - } -} - -// Without the mesh's answer — a controller not asked yet — the mesh's own names are still refused. -func TestWithoutTheMeshsAnswerItsNamesAreStillRefused(t *testing.T) { - g := Guard{} - if v := g.Judge(bash("ssh anchor.internal journalctl")); !v.Refuse || !strings.Contains(v.Message, "a missing tool is created") { - t.Errorf("an internal name without data: %+v", v) - } - if v := g.Judge(bash("echo x | sudo tee -a /etc/hosts")); !v.Refuse { - t.Errorf("the hosts file without data: %+v", v) - } -} - -// fakeProc lays out a process tree: the agent started with env, a shell under it, the hook under that. -func fakeProc(t *testing.T, agentEnv []string) (root string, hookParent int) { - t.Helper() - root = t.TempDir() - write := func(pid, ppid int, cmdline []string, env []string) { - dir := filepath.Join(root, strconv.Itoa(pid)) - _ = os.MkdirAll(dir, 0o755) - _ = os.WriteFile(filepath.Join(dir, "cmdline"), []byte(strings.Join(cmdline, "\x00")+"\x00"), 0o644) - _ = os.WriteFile(filepath.Join(dir, "environ"), []byte(strings.Join(env, "\x00")), 0o644) - _ = os.WriteFile(filepath.Join(dir, "stat"), []byte(strconv.Itoa(pid)+" (some (odd) name) S "+strconv.Itoa(ppid)+" 1 1"), 0o644) - } - write(100, 1, []string{"/opt/claude-code/bin/claude", "--resume"}, agentEnv) - write(200, 100, []string{"/bin/sh", "-c", "hook"}, []string{OverrideVar + "=set-by-the-session"}) - return root, 200 -} - -// **The override is the operator's, from the session as it was started, and recorded** — and a value a -// command or a setting put in the session's later environment is not it. -func TestTheOverrideIsTheOperatorsAndRecorded(t *testing.T) { - data := meshForTheGuard() - data.Log = filepath.Join(t.TempDir(), "guard.log") - path := filepath.Join(t.TempDir(), "guard.json") - raw, _ := json.Marshal(data) - _ = os.WriteFile(path, raw, 0o644) - was, wasPID := procRoot, parentPID - t.Cleanup(func() { procRoot, parentPID = was, wasPID }) - run := func(command string) (int, string) { - var stderr bytes.Buffer - in, _ := json.Marshal(bash(command)) - return runGuard(path, bytes.NewReader(in), &stderr), stderr.String() - } - - // Not set where the session started: the later shell's value is not the operator's. - root, hook := fakeProc(t, []string{"HOME=/home/operator"}) - procRoot, parentPID = root, func() int { return hook } - if code, says := run("ssh anchor journalctl"); code != 2 || !strings.Contains(says, "anchor/node-service-manager.journal") { - t.Fatalf("refused with %d: %s", code, says) - } - // Set by the operator before the session: let through, with why on record. - root, hook = fakeProc(t, []string{"HOME=/home/operator", OverrideVar + "=reading the broker's log by hand while the systemd module is down"}) - procRoot, parentPID = root, func() int { return hook } - if code, says := run("ssh anchor journalctl -u nats"); code != 0 { - t.Fatalf("the operator's override was not honoured: %d %s", code, says) - } - // Never for a command naming the override itself. - if code, _ := run("export " + OverrideVar + "=x"); code != 2 { - t.Fatalf("a command naming the override passed under it: %d", code) - } - record := ReadGuardLog(data.Log, 10) - if len(record) != 3 || record[0].Decision != "refused" || record[1].Decision != "overridden" || - !strings.Contains(record[1].Why, "systemd module is down") || record[1].Machine != "anchor" || record[2].Rule != "override-named" { - t.Fatalf("the record: %+v", record) - } - // An override that cannot be recorded is not honoured. - data.Log = filepath.Join(t.TempDir(), "no", "such", "dir", "guard.log") - raw, _ = json.Marshal(data) - _ = os.WriteFile(path, raw, 0o644) - if code, says := run("ssh anchor journalctl"); code != 2 || !strings.Contains(says, "could not be recorded") { - t.Fatalf("an override not recorded was honoured: %d %s", code, says) - } -} - -// What passes is not recorded, and a guard that cannot read the call says so and blocks nothing. -func TestTheHookExitsAsTheAgentReadsIt(t *testing.T) { - path := filepath.Join(t.TempDir(), "guard.json") - _ = os.WriteFile(path, []byte(`{}`), 0o644) - var stderr bytes.Buffer - in, _ := json.Marshal(bash("git push")) - if code := runGuard(path, bytes.NewReader(in), &stderr); code != 0 || stderr.Len() != 0 { - t.Errorf("git push: %d %q", code, stderr.String()) - } - if code := runGuard(path, strings.NewReader("not json"), &stderr); code != 1 { - t.Errorf("an unreadable call: %d", code) - } -} - -func TestTheAgentsProcessIsKnown(t *testing.T) { - for cmdline, want := range map[string]bool{ - "/opt/claude-code/bin/claude\x00--resume\x00": true, - "claude\x00": true, - "node\x00/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js\x00": true, - "/usr/bin/node\x00/home/x/.local/bin/claude\x00": true, - "/bin/zsh\x00": false, - "node\x00server.js\x00": false, - "/usr/bin/claude-code-tools\x00": false, - } { - if isAgent([]byte(cmdline)) != want { - t.Errorf("%q: want %v", cmdline, want) - } - } -} diff --git a/modules/claude-code/cmd/claude-code/homefs.go b/modules/claude-code/cmd/claude-code/homefs.go index 3bde64e76..7d6ddec59 100644 --- a/modules/claude-code/cmd/claude-code/homefs.go +++ b/modules/claude-code/cmd/claude-code/homefs.go @@ -63,7 +63,7 @@ func FilesFor(p Paths) *Files { return &Files{Home: filepath.Clean(p.Home), Account: p.Agent, Helper: &Helper{Account: p.Agent, Exe: HelperPath()}} } -// HelperPath is the helper's binary: the guard's copy of this module's binary in the plugin, root's and +// HelperPath is the helper's binary: the plugin's copy of this module's binary in the plugin, root's and // readable by every account, so the agent's account runs exactly what the mesh placed. func HelperPath() string { return filepath.Join(ManagedDir, MarketplaceDir, "plugins", Plugin, GuardDir, "guard") diff --git a/modules/claude-code/cmd/claude-code/insteadof.go b/modules/claude-code/cmd/claude-code/insteadof.go index 98491b0b7..98b9de7f4 100644 --- a/modules/claude-code/cmd/claude-code/insteadof.go +++ b/modules/claude-code/cmd/claude-code/insteadof.go @@ -4,12 +4,10 @@ package main // address, not this shell command — generated on every render from what each seat verb and module tool // says it replaces, so it cannot drift from the tools the mesh has. // -// Short: a row per seat or module, its top what this machine's agent reached round most — the tools the -// guard named most often in its record. +// Short: a row per seat or module, the machines' seats first. import ( "fmt" - "sort" "strings" ) @@ -31,17 +29,15 @@ func code(s string) string { return "`" + strings.ReplaceAll(s, "`", "'") + "`" // insteadGroup is one row: a seat or a module, and its verbs that replace a command. type insteadGroup struct { - prefix string // `/node-service-manager.` or `mesh-controller.` - verbs []Replacement - refused int + prefix string // `/node-service-manager.` or `mesh-controller.` + verbs []Replacement } // InsteadOf is the section, or "" when the mesh said nothing replaces anything — an older controller, // or one not yet asked. // // One row per seat or module, every verb of it that replaces a command in the row, so a verb is never cut -// for being late in its seat's list; the rows the guard here named most come first, then the machines' -// seats, the modules' tools and the mesh's own seats in the records' order. +// for being late in its seat's list; the machines' seats first, the modules' tools and the mesh's own seats in the records' order. func InsteadOf(m *MeshTools) string { if m == nil || len(m.Replacements) == 0 { return "" @@ -64,13 +60,8 @@ func InsteadOf(m *MeshTools) string { groups = append(groups, g) } g.verbs = append(g.verbs, r) - g.refused += m.Refused[r.Address] } } - sort.SliceStable(groups, func(i, j int) bool { return groups[i].refused > groups[j].refused }) - for _, g := range groups { - sort.SliceStable(g.verbs, func(i, j int) bool { return m.Refused[g.verbs[i].Address] > m.Refused[g.verbs[j].Address] }) - } more := 0 if len(groups) > InsteadOfRows { more = len(groups) - InsteadOfRows @@ -97,7 +88,7 @@ func InsteadOf(m *MeshTools) string { fmt.Fprintf(&b, "\n%d more seats and modules: `mesh_search` with the command finds the tool for it.\n", more) } b.WriteString("\n- **Never `ssh` to a mesh machine**, and never edit `/etc/hosts` or set `HOSTALIASES` for a mesh\n" + - " name: the guard on this session's shell refuses it and names the tool. Where no tool covers what you\n" + + " name: call the tool the table names instead. Where no tool covers what you\n" + " need, none is worked around: say so, and the tool is created in the module that owns it, on its seat.\n") return b.String() } diff --git a/modules/claude-code/cmd/claude-code/insteadof_test.go b/modules/claude-code/cmd/claude-code/insteadof_test.go index a403dddf0..2396f230e 100644 --- a/modules/claude-code/cmd/claude-code/insteadof_test.go +++ b/modules/claude-code/cmd/claude-code/insteadof_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "os" + "path/filepath" "reflect" "slices" "strings" @@ -98,16 +99,10 @@ func aCatalog() fakeCatalog { return f } -func resolving(name string) []string { - return map[string][]string{"anchor": {"10.10.0.1"}, "anchor.internal": {"10.10.0.1"}, "anchor.example": {"192.0.2.10"}, - "laptop": {"127.0.0.1", "10.10.0.4"}}[name] -} - // Issue 1126 B13: what the mesh says of its tools and machines is read from the bus whole, never asked of the -// controller: the seats' verbs, the placed modules' own tools, every machine with its domains and addresses — a -// loopback address never one of them. +// controller: the seats' verbs and the placed modules' own tools. func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { - m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if err != nil { t.Fatal(err) } @@ -118,12 +113,21 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { if got := strings.Join(addresses, ","); got != "mesh-module-assigner.assignments,node-service-manager.status,node-service-manager.journal,docker.docker_logs" { t.Errorf("replacements: %s", got) } - t.Run("the again tool answers the operator and the healers only", func(t *testing.T) { - // An operator's session through the mesh MCP server is proved as its machine's tool runner (issue 627, issue 1966). - for caller, refused := range map[string]bool{"person.jochen": false, "shanks.node-tools": false, "shanks.mesh-healers": false, - "shanks.mesh-config": true} { - if err := seatlist.Refusal("claude_code_seat_list_again", seatListAgainCallers, caller); (err != nil) != refused { - t.Errorf("%s: refused=%v, err %v", caller, refused, err) + t.Run("the again tool answers every caller", func(t *testing.T) { + // H-A-66 (design 47 H §752): no holder keeps a callers list; the seat list's tools answer every caller. + files, _ := filepath.Glob("*.go") + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + raw, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, gone := range []string{"AnyPerson", "seatListAgainCallers", "seatlist.Refusal"} { + if strings.Contains(string(raw), gone) { + t.Errorf("%s still names %s", f, gone) + } } } }) @@ -144,7 +148,7 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { case <-time.After(10 * time.Second): t.Fatalf("the seat list was not read: %+v", seatList.Status()) } - got, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), definedSeats(), resolving) + got, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), definedSeats()) var addrs []string for _, r := range got.Replacements { addrs = append(addrs, r.Address) @@ -154,10 +158,6 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { t.Fatalf("replacements from the bus: %v, %v", addrs, err) } }) - if len(m.Machines) != 2 || strings.Join(m.Machines[0].Domains, ",") != "anchor.internal,anchor.example" || - strings.Join(m.Machines[0].Addresses, ",") != "10.10.0.1,192.0.2.10" || strings.Join(m.Machines[1].Addresses, ",") != "10.10.0.4" { - t.Errorf("machines: %+v", m.Machines) - } if m.Replacements[3].Does != "logs" || !m.Replacements[2].NodeScoped || m.Replacements[0].NodeScoped { t.Errorf("the rows: %+v", m.Replacements) } @@ -166,7 +166,7 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) { // **The table is generated, not written** (novox/hq ADR 0245): what the records say a verb replaces is a row, // the machines' seats first, and nothing is rendered where the records say nothing. func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { - m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) table := InsteadOf(&m) for _, want := range []string{ "| `/node-service-manager.` | `status` — `systemctl status`, `systemctl is-active` · `journal` — `journalctl` |", @@ -182,14 +182,11 @@ func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { strings.Index(table, "docker.") > strings.Index(table, "`mesh-module-assigner.`") { t.Errorf("not the machines' seats, then modules, then the mesh's:\n%s", table) } - // What the guard here named most comes first: its row, and in its row its verb. - m.Refused = map[string]int{"node-service-manager.journal": 3, "mesh-module-assigner.assignments": 1} - ranked := InsteadOf(&m) - if !strings.Contains(ranked, "| `/node-service-manager.` | `journal` — `journalctl` · `status`") || - strings.Index(ranked, "`mesh-module-assigner.`") > strings.Index(ranked, "`/docker.`") { - t.Errorf("not ranked by the guard's record:\n%s", ranked) + // No guard on the session's shell: the rule is the session's own, and the text claims no guard (the operator, + // 2026-11-20). + if strings.Contains(table, "guard") || !strings.Contains(table, "call the tool the table names instead") { + t.Errorf("the rule names a guard, or not the tool to call:\n%s", table) } - m.Refused = nil if InsteadOf(nil) != "" || InsteadOf(&MeshTools{}) != "" { t.Error("a table from nothing") } @@ -216,21 +213,17 @@ func TestTheInsteadOfTableIsGeneratedFromTheRecords(t *testing.T) { // Asked again with the same answer, nothing is written and nothing renders. func TestTheMeshsToolsAreKeptOnlyWhenTheyChange(t *testing.T) { p := Paths{State: t.TempDir()} - m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, _ := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if !KeepMeshTools(p, m) { t.Fatal("the first answer was not kept") } if KeepMeshTools(p, m) { t.Fatal("the same answer was kept again") } - m.Machines = m.Machines[:1] - if !KeepMeshTools(p, m) || len(ReadMeshTools(p).Machines) != 1 { + m.Replacements = m.Replacements[:1] + if !KeepMeshTools(p, m) || len(ReadMeshTools(p).Replacements) != 1 { t.Fatal("a changed answer was not kept") } - d := GuardDataOf(Paths{State: p.State, Node: "laptop"}, ReadMeshTools(p)) - if d.Node != "laptop" || len(d.Replacements) != 4 || !strings.HasSuffix(d.Log, "guard.log") { - t.Errorf("the guard's data: %+v", d) - } } // Where a module runs is read from the seat mesh-module-assigner's assignments (issue 1126 B13), never the controller's answer. @@ -267,20 +260,20 @@ func TestTheMeshIsReadFromTheOwnersFirstViews(t *testing.T) { t.Fatal(err) } } - want, err := ReadMeshToolsFrom(bus, aCatalog(), someSeats(), resolving) + want, err := ReadMeshToolsFrom(bus, aCatalog(), someSeats()) if err != nil { t.Fatal(err) } - got, err := ReadMeshToolsFrom(viewStates{r}, aCatalog(), someSeats(), resolving) + got, err := ReadMeshToolsFrom(viewStates{r}, aCatalog(), someSeats()) if err != nil || !reflect.DeepEqual(got, want) || len(got.Replacements) == 0 { t.Fatalf("from the views: %+v, %v\nfrom the state: %+v", got, err, want) } // A reader not yet answered says so, and reads nothing. // A catalog half with no first view says so, and reads no module as absent. - if _, err := ReadMeshToolsFrom(bus, fakeCatalog{notYet: errors.New("the catalog half has no first view of main yet")}, someSeats(), resolving); err == nil || !strings.Contains(err.Error(), "no first view") { + if _, err := ReadMeshToolsFrom(bus, fakeCatalog{notYet: errors.New("the catalog half has no first view of main yet")}, someSeats()); err == nil || !strings.Contains(err.Error(), "no first view") { t.Fatalf("an unanswered catalog half: %v", err) } - if _, err := ReadMeshToolsFrom(viewStates{newMeshViews()}, aCatalog(), someSeats(), resolving); err == nil || !strings.Contains(err.Error(), "no first view") { + if _, err := ReadMeshToolsFrom(viewStates{newMeshViews()}, aCatalog(), someSeats()); err == nil || !strings.Contains(err.Error(), "no first view") { t.Fatalf("an unanswered first view: %v", err) } } @@ -288,7 +281,7 @@ func TestTheMeshIsReadFromTheOwnersFirstViews(t *testing.T) { // Issue 1126 B13 AC1 (ADR 0590): over the seats the mesh defines, the rendered instructions, their table among them, // name no address of the controller, which is not placed: each job is named by the seat that owns it now. func TestTheRenderedInstructionsNameNoControllerAddress(t *testing.T) { - m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats(), resolving) + m, err := ReadMeshToolsFrom(aMesh(t), aCatalog(), someSeats()) if err != nil { t.Fatal(err) } diff --git a/modules/claude-code/cmd/claude-code/main.go b/modules/claude-code/cmd/claude-code/main.go index 407b94b61..ab5c5a101 100644 --- a/modules/claude-code/cmd/claude-code/main.go +++ b/modules/claude-code/cmd/claude-code/main.go @@ -339,10 +339,10 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c Description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, what it reports holding, the managed files, the MCP servers registered here. Fingerprints only, never a token.", Run: func(map[string]any) (any, error) { return status(p), nil }}, {Name: "claude_code_render", - Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces and which machines the mesh has (the instructions' table and the shell's guard).", + Description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here — after reading the bus again for what each tool replaces (the instructions' table).", Run: func(map[string]any) (any, error) { answer := map[string]any{} - if m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats(), lookup); err != nil { + if m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats()); err != nil { answer["asked"] = "the bus could not be read in full (" + err.Error() + "); what was kept is rendered" } else { KeepMeshTools(p, m) @@ -351,16 +351,6 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c answer["rendered"] = out return answer, err }}, - {Name: "claude_code_guard", - Description: "The guard on the agent's shell on this machine (novox/hq ADR 0245): what it refuses — ssh to a mesh machine, writing /etc/hosts or /etc/resolv.conf, HOSTALIASES — the machines and the replaced commands it judges with, the \"instead of\" table rendered into the agent's instructions, and its record of what it refused and what the operator's override let through, newest last.", - Input: map[string]any{"last": map[string]any{"type": "integer", "description": "how many lines of the record (default 50)"}}, - Run: func(a map[string]any) (any, error) { - last := 50 - if n, ok := a["last"].(float64); ok && n > 0 { - last = int(n) - } - return GuardStatus(p, last), nil - }}, {Name: "claude_code_pull", Description: "Ask the licence manager which licence this node holds and the vault for its access token now, and apply it, rather than waiting for its binding or the token to change.", Run: func(map[string]any) (any, error) { return Pull(p, ask, writeManaged) }}, @@ -452,10 +442,6 @@ func persist(what string, attempt func() error, done func(refusals int)) { } func main() { - // The guard on the agent's shell (novox/hq ADR 0245): this binary, run by the agent's hook. - if len(os.Args) == 3 && os.Args[1] == "guard" { - os.Exit(runGuard(os.Args[2], os.Stdin, os.Stderr)) - } // The plugin's SessionStart hook (novox/hq ADR 0489 §1, issue 1744): names the session's id and its open waits. if len(os.Args) == 3 && os.Args[1] == "session-start" { os.Exit(runSessionStart(os.Args[2], os.Stdin, os.Stdout)) @@ -734,17 +720,12 @@ func refusals(n int) string { return fmt.Sprintf(" (after %d refusal(s))", n) } -// seatListAgainCallers may read the seat list again: every operator's session and the healers (ADR 0636 §7). A call through -// the mesh MCP server is proved only as its machine's tool runner (.node-tools, issue 627), so node-tools stands for -// an operator's session until a session is proved (issue 1966). -var seatListAgainCallers = []string{stdio.AnyPerson, "node-tools", "mesh-healers"} - -// seatListTools are the seat list reader's two tools: what the list holds and what it waits for, and a read now. The -// reader starts once the runtime serves, after the tools are listed, so each tool finds it when it is called. +// seatListTools are the seat list reader's two tools: what the list holds and what it waits for, and a read now, each +// answering every caller (design 47 H §752, H-A-66). The reader starts once the runtime serves, after the tools are +// listed, so each tool finds it when it is called. func seatListTools() []stdio.Tool { names := []string{"claude_code_seat_list", "claude_code_seat_list_again"} - callers := seatListAgainCallers - shape := seatlist.Tools(&seatlist.Reader{}, names[0], names[1], callers) + shape := seatlist.Tools(&seatlist.Reader{}, names[0], names[1]) for i := range shape { run := i shape[i].Run = func(args map[string]any) (any, error) { @@ -754,7 +735,7 @@ func seatListTools() []stdio.Tool { if r == nil { return nil, errors.New("the seat list reader has not started yet: the runtime has not served this module") } - return seatlist.Tools(r, names[0], names[1], callers)[run].Run(args) + return seatlist.Tools(r, names[0], names[1])[run].Run(args) } } return shape diff --git a/modules/claude-code/cmd/claude-code/mesh.go b/modules/claude-code/cmd/claude-code/mesh.go index e8cd63359..1fac6c010 100644 --- a/modules/claude-code/cmd/claude-code/mesh.go +++ b/modules/claude-code/cmd/claude-code/mesh.go @@ -1,22 +1,19 @@ package main -// What the mesh says about its own tools and machines, as the agent's instructions and the guard on its -// shell need it (novox/hq ADR 0245): every seat verb and module tool that says what shell command it -// replaces, and the mesh's machines by every name and address a session could reach one by. +// What the mesh says about its own tools, as the agent's instructions need it (novox/hq ADR 0245): every seat verb +// and module tool that says what shell command it replaces. // -// Read from the bus at start and every few minutes (issue 1126 B13; the controller that answered this before is +// Read from the bus at start and whenever a followed state changes (issue 1126 B13; the controller that answered this before is // not placed, novox/hq ADR 0590): the seats' verbs from the seats' contract (mesh-contracts), the modules' -// own tools from the manifests the indexer keeps (`mesh-delivery-indexer.modules` and `.manifests`), and the -// machines and where each module runs from the seat mesh-module-assigner's `assignments`. Kept in the module's state so +// own tools from the manifests the indexer keeps (`mesh-delivery-indexer.modules` and `.manifests`), and where +// each module runs from the seat mesh-module-assigner's `assignments`. Kept in the module's state so // a render never waits for the bus, and rendered whenever it changes. Nothing here is written by hand: a verb -// that gains a `replaces` is in the next render's table and the guard's next refusal. +// that gains a `replaces` is in the next render's table. import ( - "context" "encoding/json" "errors" "fmt" - "net" "os" "path/filepath" "sort" @@ -45,39 +42,13 @@ type Replacement struct { On []string `json:"on,omitempty"` } -// Machine is one of the mesh's machines and the names and addresses it is reached by. -type Machine struct { - Name string `json:"name"` - Domains []string `json:"domains,omitempty"` - Addresses []string `json:"addresses,omitempty"` -} - // MeshTools is what the bus said, as kept in the module's state. type MeshTools struct { Replacements []Replacement `json:"replacements"` - Machines []Machine `json:"machines"` // Asked is when the bus was last read whole. Asked string `json:"asked,omitempty"` - // Refused is how often the guard here named each tool instead of a work-around, from its record: the - // table's order. Never kept — read from the record at each render. - Refused map[string]int `json:"-"` } -// RefusedCounts are how often the guard's record named each tool, over its last lines. -func RefusedCounts(log string) map[string]int { - out := map[string]int{} - for _, e := range ReadGuardLog(log, 2000) { - for _, t := range e.Tools { - out[t]++ - } - } - return out -} - -// InternalSuffix is the mesh's own names' domain: every machine and service is `.internal` -// (novox/hq ADR 0194), and a session reaches none of them by ssh. -const InternalSuffix = ".internal" - func (p Paths) meshTools() string { return filepath.Join(p.State, "mesh-tools.json") } // ReadMeshTools is what was kept, or nil. @@ -234,17 +205,8 @@ func ReplacementsOf(defined []seatdef.Definition, modules []ModuleTools) []Repla return out } -// lookup resolves one name, briefly: a name that does not resolve here is no address. -func lookup(name string) []string { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - addrs, _ := net.DefaultResolver.LookupHost(ctx, name) - return addrs -} - -// ReadMeshToolsFrom reads the bus now: the seats' verbs, the placed modules' own tools, and every node assignments names -// with its domains and addresses. A part that cannot be read is left out and said in the error; what was read is kept. -func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition, resolve func(string) []string) (MeshTools, error) { +// ReadMeshToolsFrom reads the bus now: the seats' verbs and the placed modules' own tools. A part that cannot be read is left out and said in the error; what was read is kept. +func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition) (MeshTools, error) { var m MeshTools placed, err := assignments(st) if err != nil { @@ -253,24 +215,6 @@ func ReadMeshToolsFrom(st States, cat CatalogHalf, defined []seatdef.Definition, } modules, merr := modulesTools(cat, runsOn(placed)) m.Replacements = ReplacementsOf(defined, modules) - for node, p := range placed { - machine := Machine{Name: node, Domains: []string{node + InternalSuffix}} - if d := strings.ToLower(strings.TrimSpace(p.Decided.PublicDomain)); d != "" { - machine.Domains = append(machine.Domains, d) - } - seen := map[string]bool{} - for _, name := range append([]string{node}, machine.Domains...) { - for _, a := range resolve(name) { - if !seen[a] && !net.ParseIP(a).IsLoopback() { - seen[a] = true - machine.Addresses = append(machine.Addresses, a) - } - } - } - sort.Strings(machine.Addresses) - m.Machines = append(m.Machines, machine) - } - sort.Slice(m.Machines, func(i, j int) bool { return m.Machines[i].Name < m.Machines[j].Name }) return m, merr } @@ -295,22 +239,9 @@ func KeepMeshTools(p Paths, m MeshTools) bool { return os.Rename(tmp, p.meshTools()) == nil } -// GuardDataOf is what the guard judges with on this machine. -func GuardDataOf(p Paths, m *MeshTools) GuardData { - d := GuardData{Node: p.Node, Log: filepath.Join(p.State, "guard.log"), Machines: []Machine{}, Replacements: []Replacement{}} - if p.Confined() { - // The session's account cannot write the module's state, and must not rewrite its own record (ADR 0266). - d.Agent, d.Log = p.Agent, JournalRecord+GuardJournalID - } - if m != nil { - d.Machines, d.Replacements = m.Machines, m.Replacements - } - return d -} - -// guardFiles is the guard to place: this module's own executable and what it judges with. None where the +// hookFiles is what the plugin's hooks run: this module's own executable and the waits directory. None where the // executable cannot be named — then no hook is written, rather than one that cannot run. -func guardFiles(p Paths, m *MeshTools) *GuardFiles { +func hookFiles(p Paths) *HookFiles { exe, err := os.Executable() if err != nil { return nil @@ -318,18 +249,13 @@ func guardFiles(p Paths, m *MeshTools) *GuardFiles { if resolved, err := filepath.EvalSymlinks(exe); err == nil { exe = resolved } - return &GuardFiles{Exe: exe, Data: GuardDataOf(p, m), WaitsDir: WaitsDirPath(p)} + return &HookFiles{Exe: exe, WaitsDir: WaitsDirPath(p)} } -// MeshToolsEvery is how often the machines' addresses are resolved again; the tools and the assignments are read again -// when their followed states change (a views event), not on this timer. -const MeshToolsEvery = 10 * time.Minute - // MeshToolsFirst is how long the first read waits for the first views to be answered. const MeshToolsFirst = 2 * time.Minute -// refreshMeshTools reads the pictures once the first views are answered, and again whenever one changes (and the -// machines' addresses every few minutes), and renders when what it said changed. +// refreshMeshTools reads the pictures once the first views are answered, and again whenever one changes, and renders when what it said changed. func refreshMeshTools(p Paths) { select { case <-meshViews.Ready(): @@ -338,60 +264,26 @@ func refreshMeshTools(p Paths) { } startSeatList(seatlist.StdioBus()) for { - m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats(), lookup) + m, err := ReadMeshToolsFrom(viewStates{meshViews}, meshCatalog, definedSeats()) if err != nil { - say("reading what each tool replaces and which machines the mesh has: %v", err) + say("reading what each tool replaces: %v", err) } if (err == nil || len(m.Replacements) > 0) && KeepMeshTools(p, m) { if _, err := RenderNow(p, writeManaged); err != nil { say("rendering what the bus said of the tools: %v", err) } else { - say("the mesh's tools changed: %d replace a command, %d machines; rendered", len(m.Replacements), len(m.Machines)) + say("the mesh's tools changed: %d replace a command; rendered", len(m.Replacements)) } } + <-meshChanged + time.Sleep(2 * time.Second) // a burst of events is one read select { case <-meshChanged: - time.Sleep(2 * time.Second) // a burst of events is one read - select { - case <-meshChanged: - default: - } - case <-time.After(MeshToolsEvery): + default: } } } -// GuardStatus is what claude_code_guard answers. -func GuardStatus(p Paths, last int) map[string]any { - m := ReadMeshTools(p) - d := GuardDataOf(p, m) - asked := "never: the bus has not been read whole yet" - if m != nil { - asked = m.Asked - } - return map[string]any{ - "refuses": []string{ - "ssh, scp, sftp, rsync, mosh or autossh to a mesh machine: its name, a name under its domains, any *" + InternalSuffix + - " name or one of its addresses, read as ssh reads it (ssh -G); a jump through one too. An ssh login as `" + - ForgeUser + "` is the forge's account and passes", - "writing /etc/hosts or /etc/resolv.conf, by the shell or the agent's Edit and Write", - "HOSTALIASES, named anywhere in a command", - "any command naming " + OverrideVar, - "where the machine names an agent account of its own (novox/hq ADR 0266): every command and file edit of a " + - "session that does not run as it, whatever it is, and no override lifts it", - }, - "agent_account": map[bool]string{true: p.Agent, false: "none of its own: agents run as the operator's account"}[p.Confined()], - "override": OverrideVar + "=, set in the operator's own shell before the session starts; read from the session's " + - "environment as it was started, recorded with why, and not honoured when it cannot be recorded", - "hook": GuardCommand(), - "asked": asked, - "machines": d.Machines, - "replacements": d.Replacements, - "instead_of": InsteadOf(m), - "record": ReadGuardLog(d.Log, last), - } -} - // seatList is the seat list this module holds: the definitions of the seats, read from the seat mesh-catalog and // followed on its events (novox/hq ADR 0635 §1, ADR 0636), the foundation's bootstrapped ones until it answers. var seatList *seatlist.Reader diff --git a/modules/claude-code/cmd/claude-code/node.go b/modules/claude-code/cmd/claude-code/node.go index 011ebb8c8..02f26f440 100644 --- a/modules/claude-code/cmd/claude-code/node.go +++ b/modules/claude-code/cmd/claude-code/node.go @@ -24,6 +24,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "os" "path/filepath" "regexp" @@ -84,8 +85,8 @@ func PathsFrom(env func(string) string) (Paths, bool) { Agent: env("MESH_AGENT_ACCOUNT"), Operator: env("MESH_OPERATOR_ACCOUNT"), AgentHome: env("MESH_AGENT_HOME"), OperatorHome: env("MESH_OPERATOR_HOME")} if (p.Home == "") != (p.Agent == "") { - // Half of the agent's account is not "the operator's": taken so, the agent's account rule of the guard - // would be off and its home never written, and nothing would say so. Not launched, said (main). + // Half of the agent's account is not "the operator's": taken so, the agent's + // home would never be written, and nothing would say so. Not launched, said (main). return p, false } if p.Home == "" { @@ -143,6 +144,7 @@ func HomeScopeRefused(p Paths, target string) string { func (p Paths) credentials() string { return filepath.Join(p.Home, ".claude", ".credentials.json") } func (p Paths) account() string { return filepath.Join(p.Home, ".claude.json") } func (p Paths) binding() string { return filepath.Join(p.State, "licence.json") } +func (p Paths) handed() string { return filepath.Join(p.State, "login-handed") } func (p Paths) apiKey() string { return filepath.Join(p.keyDir(), "api-key") } func (p Paths) helper() string { return filepath.Join(p.keyDir(), "api-key-helper") } @@ -256,11 +258,8 @@ func RenderNow(p Paths, write WriteManaged) ([]string, error) { config.Approved = ApprovedHere(approved, p.Node) } mesh := ReadMeshTools(p) - if mesh != nil { - mesh.Refused = RefusedCounts(GuardDataOf(p, mesh).Log) - } files := RenderWithMesh(facts, settings, binding, p.helperCommand(), Registered(p), config, mesh) - tree, _ := json.Marshal(MarketplaceWith(config, guardFiles(p, mesh))) + tree, _ := json.Marshal(MarketplaceWith(config, hookFiles(p))) files[MarketplaceDir+"/"] = string(tree) names := make([]string, 0, len(files)) for n := range files { @@ -418,9 +417,26 @@ func GrantFor(p Paths, managerPublicKey string) (GrantAnswer, error) { if err != nil { return GrantAnswer{}, err } + // Which login was handed: only its successor may replace it (ADR 0206, ADR 0209). The fingerprint, never + // the token. + if err := fsys.MkdirAll(p.State, 0o700); err != nil { + return GrantAnswer{}, err + } + if err := fsys.WriteFile(p.handed(), []byte(Fingerprint(rt)+"\n"), 0o600); err != nil { + return GrantAnswer{}, err + } return GrantAnswer{Sealed: &box, Identity: ReadIdentity(p.account()), Fingerprint: Fingerprint(rt)}, nil } +// readHanded is the fingerprint of the login last handed to the manager, or "". +func readHanded(p Paths) string { + raw, err := fsys.ReadFile(p.handed()) + if err != nil { + return "" + } + return strings.TrimSpace(string(raw)) +} + // Pull asks the seat which licence this node holds, then the vault for that licence's access secret, sealed to this // module's key, and applies it (§19). func Pull(p Paths, ask Ask, write WriteManaged) (map[string]any, error) { @@ -609,9 +625,37 @@ func Apply(p Paths, c Current, sealed SealedBox, write WriteManaged) (map[string return nil, err } local := ReadCredentials(p.credentials()) - // A login waiting here was handed to the manager first (ADR 0206): what comes back is its successor, - // and the refresh token in the file is the one the manager just spent. + // A login made here that the manager has not adopted yet stays whole: the grant handed is the old + // lineage's, and writing it would spend the person's login unseen (ADR 0206, ADR 0209). The manager + // asks claude_code_grant for it on this node's report; its successor then comes as a newer generation. + // This return skips the binding's generation below on purpose: later binding events pull again until + // the manager adopts the login. + // The latest login wins (design 39 §6): a lease of the same account that succeeds the login (H-A-139) — + // the manager adopted a later login to that account from another node — replaces it, said as "login + // superseded"; a login to another account than the lease's licence is always kept (H-A-140, hq + // design/47-H1-answers-59 b75d1386). + superseded := false + if LoginNotHanded(local, readHanded(p)) { + id := ReadIdentity(p.account()) + if id == nil || id.EmailAddress == "" || id.EmailAddress != c.Licence || !Succeeds(local, g) { + log.Printf("login kept: the login in the credentials file was not handed to the manager yet (licence %s)", c.Licence) + return map[string]any{"applied": false, "licence": c.Licence, "reason": LoginKept}, nil + } + superseded = true + log.Printf("login superseded: a later login to the account of licence %s was adopted by the manager (generation %d)", c.Licence, c.Generation) + } + // A login handed to the manager is replaced only by a grant of a newer lineage (its refresh token's + // expiry later than the login's, or the same lineage with a later access expiry, as the manager's refresh yields it): a lease older than the login is never + // written, so the manager's failed refresh is a finding on the manager, never a lost login here + // (H-A-138, hq design/47-H1-answers-59 175ed320; H-A-139, e359911e). + if HoldsLogin(local) && !Succeeds(local, g) { + log.Printf("login kept: the grant offered for licence %s does not succeed the login in the credentials file", c.Licence) + return map[string]any{"applied": false, "licence": c.Licence, "reason": LoginKept}, nil + } d := DecideApply(GrantOf(local), g, switched || HoldsLogin(local)) + if d.Apply && superseded { + out["reason"] = "login superseded" + } if d.Apply { next := WithGrant(local, g) if switched { diff --git a/modules/claude-code/cmd/claude-code/session_start_test.go b/modules/claude-code/cmd/claude-code/session_start_test.go index a10827095..4edcead14 100644 --- a/modules/claude-code/cmd/claude-code/session_start_test.go +++ b/modules/claude-code/cmd/claude-code/session_start_test.go @@ -114,7 +114,7 @@ func TestSessionStartRejectsAnUnsafeSessionID(t *testing.T) { } // 1744/AC4 is checked together with 1743/AC7 in terminal_only_test.go's -// TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook. +// TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook. // ADR 0490 §2: every session start lists every name on this node with an open wait, from the node-wide // index, with the exact adopt call to make if it is yours — read directly, never by calling back into this diff --git a/modules/claude-code/cmd/claude-code/stop_test.go b/modules/claude-code/cmd/claude-code/stop_test.go index 11ead0cf0..ef97930c0 100644 --- a/modules/claude-code/cmd/claude-code/stop_test.go +++ b/modules/claude-code/cmd/claude-code/stop_test.go @@ -320,9 +320,9 @@ func TestWaitBlocksStopAdvisesMeshWaitOnItsEventOtherwiseAWatcher(t *testing.T) } } -// 1743/AC7's rendering half (hooks.json holds the guard's PreToolUse entry and the Stop entry) is checked +// 1743/AC7's rendering half (hooks.json holds the Stop entry) is checked // together with 1744/AC4 in terminal_only_test.go's -// TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook. claude_code_hook_register still +// TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook. claude_code_hook_register still // refuses a Stop hook (or any other) at every scope. func TestHookRegisterStillRefusesEveryHook(t *testing.T) { p, _ := node(t, "laptop") diff --git a/modules/claude-code/cmd/claude-code/terminal_only_test.go b/modules/claude-code/cmd/claude-code/terminal_only_test.go index 5c41587b6..b4618c5ce 100644 --- a/modules/claude-code/cmd/claude-code/terminal_only_test.go +++ b/modules/claude-code/cmd/claude-code/terminal_only_test.go @@ -261,12 +261,13 @@ func TestTheOperatorsManagedSettingsAreWhatSessionsObey(t *testing.T) { } } -// The plugin's only hooks are the guard, the session-start hook and the Stop hook (novox/hq ADR 0245, ADR -// 0489) — never a hook a registration named, whatever the configuration given holds (novox/hq issue 340). -func TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook(t *testing.T) { +// The plugin's only hooks are the session-start hook and the Stop hook (novox/hq ADR 0489) — no guard on the +// shell (the operator, 2026-11-20), and never a hook a registration named, whatever the configuration given holds +// (novox/hq issue 340). +func TestThePluginsOnlyHooksAreTheSessionStartHookAndTheStopHook(t *testing.T) { c := Config{Mesh: []Item{{Kind: KindHook, Name: "planted", Scope: ScopeMesh, Event: "PreToolUse", Matcher: "Bash", Command: "${HOOK_DIR}/x.sh", Files: map[string]string{"x.sh": "#!/bin/sh\n"}}}} - plugin := MarketplaceWith(c, &GuardFiles{Exe: "/bin/true", WaitsDir: "/home/agent/.claude/nox-mesh/waits"}) + plugin := MarketplaceWith(c, &HookFiles{Exe: "/bin/true", WaitsDir: "/home/agent/.claude/nox-mesh/waits"}) root := "plugins/" + Plugin + "/" var hooks struct { Hooks map[string][]struct { @@ -279,9 +280,14 @@ func TestThePluginsOnlyHooksAreTheGuardTheSessionStartHookAndTheStopHook(t *test if err := json.Unmarshal([]byte(plugin[root+"hooks/hooks.json"].Content), &hooks); err != nil { t.Fatal(err) } - if len(hooks.Hooks) != 3 || len(hooks.Hooks["PreToolUse"]) != 1 || hooks.Hooks["PreToolUse"][0].Matcher != GuardMatcher || - hooks.Hooks["PreToolUse"][0].Hooks[0].Command != GuardCommand() { - t.Fatalf("the guard's hook: %s", plugin[root+"hooks/hooks.json"].Content) + if len(hooks.Hooks) != 2 || hooks.Hooks["PreToolUse"] != nil { + t.Fatalf("a hook beside the session-start and Stop hooks: %s", plugin[root+"hooks/hooks.json"].Content) + } + if plugin[root+GuardDir+"/guard"].From != "/bin/true" { + t.Fatalf("the binary the hooks run is not placed: %+v", plugin[root+GuardDir+"/guard"]) + } + if _, ok := plugin[root+GuardDir+"/guard.json"]; ok { + t.Fatal("the guard's data is placed") } if len(hooks.Hooks["SessionStart"]) != 1 || hooks.Hooks["SessionStart"][0].Matcher != "startup|resume|clear|compact" || hooks.Hooks["SessionStart"][0].Hooks[0].Command != SessionStartCommand("/home/agent/.claude/nox-mesh/waits") { diff --git a/modules/claude-code/cmd/claude-code/waits.go b/modules/claude-code/cmd/claude-code/waits.go index 3929fc2ae..f3699dec4 100644 --- a/modules/claude-code/cmd/claude-code/waits.go +++ b/modules/claude-code/cmd/claude-code/waits.go @@ -20,7 +20,7 @@ package main // Every file lives under the agent's home (the manifest's `agent-home` resource), which this process — // launched as the operator's account (novox/hq ADR 0193) — cannot itself write when the node names an agent // account of its own (novox/hq ADR 0266): every write below goes through `fsys` (homefs.go), which already -// carries such a write through the sudo helper the guard's binary also serves, exactly as grant.go's +// carries such a write through the sudo helper this module's binary serves, exactly as grant.go's // WriteCredentials does for the agent's own credentials file. Where the node has no agent account of its // own, fsys is the plain filesystem and the write reaches the operator's own home directly. diff --git a/modules/claude-code/files/claude-agent b/modules/claude-code/files/claude-agent index e3d330f2b..0281cdb39 100755 --- a/modules/claude-code/files/claude-agent +++ b/modules/claude-code/files/claude-agent @@ -5,9 +5,5 @@ agent='${machine:agent-account}' if [ "$(id -un)" = "$agent" ]; then exec claude "$@" fi -# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority. The -# operator's override of the guard travels only when it is set in this shell, as it would reach claude. -if [ -n "$MESH_GUARD_OVERRIDE" ]; then - exec sudo -iu "$agent" env MESH_GUARD_OVERRIDE="$MESH_GUARD_OVERRIDE" claude "$@" -fi +# Another account, the operator's, becomes the agent's through its own sudo: the person is the authority. exec sudo -iu "$agent" claude "$@" diff --git a/modules/claude-code/module.json b/modules/claude-code/module.json index 882b366ab..fd0a9fc56 100644 --- a/modules/claude-code/module.json +++ b/modules/claude-code/module.json @@ -1,6 +1,7 @@ { "module": "claude-code", "version": "0.1", + "class": "leaf", "moved": true, "slug": "agent", "capabilities": [ @@ -23,7 +24,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } }, { @@ -63,7 +64,7 @@ "mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", "claude-licence-manager.holdings.asked", - "claude-licence-manager.binding.changed", + "claude-licence-manager.binding.changed.*", "mesh-vault.secret-changed" ], "state": [ @@ -82,7 +83,6 @@ "tools": [ "claude_code_status", "claude_code_render", - "claude_code_guard", "claude_code_pull", "claude_code_grant", "claude_code_add_api_key", diff --git a/modules/claude-licence-manager/module.json b/modules/claude-licence-manager/module.json index 62145c08b..5b6c70668 100644 --- a/modules/claude-licence-manager/module.json +++ b/modules/claude-licence-manager/module.json @@ -1,6 +1,7 @@ { "module": "claude-licence-manager", "version": "0.1", + "class": "core", "slug": "licmgr", "runs-as": "claude-licence-manager", "requires": [ diff --git a/modules/clipmenu/cmd/clipmenu-tools/manifest_helpers_test.go b/modules/clipmenu/cmd/clipmenu-tools/manifest_helpers_test.go index 28adb6607..740a42250 100644 --- a/modules/clipmenu/cmd/clipmenu-tools/manifest_helpers_test.go +++ b/modules/clipmenu/cmd/clipmenu-tools/manifest_helpers_test.go @@ -1,66 +1,19 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Items []item `json:"items"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - // Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here. - Contributions []any `json:"contributions"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest. -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} - // shell is the code the module adds to a shell's or the session's start, read from the templates of its items of // the collections shell::, in the order they are declared. -func (m manifest) shell(t *testing.T) []shellCode { +func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode { t.Helper() - var out []shellCode + var out []catalogue.ShellCode for _, it := range m.Items { parts := strings.Split(it.Collection, ":") if len(parts) != 3 || parts[0] != "shell" { @@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode { if err != nil { t.Fatal(err) } - out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)}) + out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)}) } return out } // environmentOf is the variables the module sets, read from the templates of its items of the environment. -func (m manifest) environmentOf(t *testing.T) *environment { +func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment { t.Helper() - var env *environment + var env *catalogue.Environment for _, it := range m.Items { if it.Collection != "environment" || it.Attributes["kind"] != "variable" { continue @@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment { t.Fatal(err) } if env == nil { - env = &environment{Variables: map[string]string{}} + env = &catalogue.Environment{Variables: map[string]string{}} } env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n") } return env } -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - m.Environment = m.environmentOf(t) - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } @@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config" // i3Lines is what the module contributes to the window manager: the text of its item of the collection // contribution:node-display-session:config (design 57 L3, issue 848). -func (m manifest) i3Lines() string { +func i3Lines(m catalogue.Manifest) string { var out string for _, it := range m.Items { if it.Collection == displaySession { @@ -287,7 +224,7 @@ func (m manifest) i3Lines() string { // i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no // old-form contribution to node-display-session is left. -func (m manifest) i3LinesAreSource(t *testing.T, source string) { +func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) { t.Helper() if len(m.Contributions) != 0 { t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession) @@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) { if len(templates) != 1 || templates[0] != source { t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source) } - if m.i3Lines() == "" { + if i3Lines(m) == "" { t.Fatalf("the template %s holds no line", source) } } diff --git a/modules/clipmenu/cmd/clipmenu-tools/manifest_test.go b/modules/clipmenu/cmd/clipmenu-tools/manifest_test.go index b00b6cde1..217066972 100644 --- a/modules/clipmenu/cmd/clipmenu-tools/manifest_test.go +++ b/modules/clipmenu/cmd/clipmenu-tools/manifest_test.go @@ -6,12 +6,15 @@ import ( "net" "os" "os/exec" + "path/filepath" "reflect" "strings" "sync" "syscall" "testing" "time" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // clipmenu's shape (novox/hq ADR 0208, research 026/04): it claims node-clipboard serving history @@ -19,28 +22,44 @@ import ( // from the session's start, and binds its menu as an i3 drop-in through the launcher's dmenu command. func TestItClaimsTheClipboardSeatServingHistoryAndCopy(t *testing.T) { - m := readManifest(t) - if m.Module != "clipmenu" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "clipmenu" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) { t.Fatalf("claims: %+v", m.Claims) } if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("requires: %v", m.Requires) } - present, absent := m.packages() + present, absent := packages(m) if !reflect.DeepEqual(present, []string{"clipmenu"}) || !reflect.DeepEqual(absent, []string{"rofi-greenclip"}) { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) { - m := readManifest(t) - if len(m.shell(t)) != 0 { - t.Fatalf("a second start from the session: %+v", m.shell(t)) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - svc := m.resource(t, "daemon") + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if len(shell(t, m)) != 0 { + t.Fatalf("a second start from the session: %+v", shell(t, m)) + } + svc := resource(t, m, "daemon") want := map[string]any{"id": "daemon", "type": "service", "unit": "clipmenud.service", "scope": "user", "user": "${machine:account}", "state": "running", "boot": "enabled", "reload-on": nil} for k, v := range want { @@ -53,15 +72,15 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) { if h, _ := svc["health"].(map[string]any); h["kind"] != "unit" { t.Fatalf("daemon health = %v, want kind unit", svc["health"]) } - dropin := m.resource(t, "daemon-dropin") - content := m.text(t, "daemon-dropin") + dropin := resource(t, m, "daemon-dropin") + content := templateText(t, m, "daemon-dropin") if dropin["path"] != "${machine:account-home}/.config/systemd/user/clipmenud.service.d/mesh.conf" || dropin["owner"] != "${machine:account}" || !strings.Contains(content, "ExecStart=/usr/local/lib/mesh-clipmenu/clipmenud-session") || strings.Contains(content, "greenclip") { t.Fatalf("drop-in: %v", dropin) } - launcher := m.text(t, "launcher") + launcher := templateText(t, m, "launcher") if !strings.Contains(launcher, "DISPLAY") || !strings.Contains(launcher, "/tmp/.X11-unix") || !strings.Contains(launcher, `PATH="/usr/local/lib/mesh-clipmenu:$PATH"`) || !strings.Contains(launcher, "exec clipmenud") { t.Fatalf("launcher: %q", launcher) @@ -74,7 +93,7 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) { if !strings.Contains(content, "StartLimitIntervalSec=0") || !strings.Contains(content, "RestartSec=2s") { t.Fatalf("drop-in lacks the safety net: %q", content) } - for k, v := range m.environmentOf(t).Variables { + for k, v := range environmentOf(t, m).Variables { if !strings.Contains(content, "Environment="+k+"="+v) { t.Fatalf("the unit lacks %s=%s", k, v) } @@ -82,34 +101,67 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) { } func TestItsSettingsAreEnvironmentAndItsMenuIsTheLaunchersDmenu(t *testing.T) { - m := readManifest(t) - if !reflect.DeepEqual(m.Environment.Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) { - t.Fatalf("%v", m.Environment.Variables) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if _, set := m.Environment.Variables["CM_LAUNCHER"]; set { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if !reflect.DeepEqual(environmentOf(t, m).Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) { + t.Fatalf("%v", environmentOf(t, m).Variables) + } + if _, set := environmentOf(t, m).Variables["CM_LAUNCHER"]; set { t.Fatal("the launcher is clipmenu's default, dmenu: the seat's command") } - m.i3LinesAreSource(t, "files/i3/50-clipmenu.conf") - if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") { + i3LinesAreSource(t, m, "files/i3/50-clipmenu.conf") + if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") { t.Fatalf("%s", c) } } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } // Run for real: DISPLAY from the manager is used at once; several sockets and no DISPLAY wait. func TestTheLauncherUsesTheManagersDisplayAndWaitsOtherwise(t *testing.T) { - m := readManifest(t) - script := m.text(t, "launcher") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + script := templateText(t, m, "launcher") dir := t.TempDir() file := dir + "/launcher" // clipmenud and the socket directory are faked: the script's own paths are rewritten. @@ -162,8 +214,16 @@ func TestTheLauncherWaitsQuietlyWhileAnotherClipmenudHoldsTheLock(t *testing.T) if _, err := exec.LookPath("flock"); err != nil { t.Skip("flock is missing here") } - m := readManifest(t) - script := m.text(t, "launcher") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + script := templateText(t, m, "launcher") dir := t.TempDir() body := strings.Replace(script, "exec clipmenud", `echo "started"`, 1) file := dir + "/launcher" diff --git a/modules/clipmenu/module.json b/modules/clipmenu/module.json index 1c59e061b..168f925de 100644 --- a/modules/clipmenu/module.json +++ b/modules/clipmenu/module.json @@ -1,6 +1,7 @@ { "module": "clipmenu", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/confluence/module.json b/modules/confluence/module.json index 3580e2d1f..26dbb3333 100644 --- a/modules/confluence/module.json +++ b/modules/confluence/module.json @@ -1,6 +1,7 @@ { "module": "confluence", "version": "0.1", + "class": "leaf", "slug": "confl", "own-secrets": { "token": "${dir:state}/token" diff --git a/modules/cups/module.json b/modules/cups/module.json index a11903c28..2156e3bbc 100644 --- a/modules/cups/module.json +++ b/modules/cups/module.json @@ -1,6 +1,7 @@ { "module": "cups", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/dbus/module.json b/modules/dbus/module.json index e71f5100a..9bdd57ba8 100644 --- a/modules/dbus/module.json +++ b/modules/dbus/module.json @@ -1,6 +1,7 @@ { "module": "dbus", "version": "0.1", + "class": "core", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/desk-channel/module.json b/modules/desk-channel/module.json index 562945690..bf8b4487a 100644 --- a/modules/desk-channel/module.json +++ b/modules/desk-channel/module.json @@ -1,6 +1,7 @@ { "module": "desk-channel", "version": "0.1", + "class": "core", "slug": "desk", "runs-as": "desk-channel", "claims": [ diff --git a/modules/dev-tools/module.json b/modules/dev-tools/module.json index 0505c8666..754963765 100644 --- a/modules/dev-tools/module.json +++ b/modules/dev-tools/module.json @@ -1,6 +1,7 @@ { "module": "dev-tools", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/disk-load/module.json b/modules/disk-load/module.json index 3d33aecb9..f19a46849 100644 --- a/modules/disk-load/module.json +++ b/modules/disk-load/module.json @@ -1,6 +1,7 @@ { "module": "disk-load", "version": "0.1", + "class": "leaf", "tools": [ "disk_load", "disk_top", @@ -24,6 +25,15 @@ "loads": [ "disk-load" ] + }, + { + "name": "diskreadings", + "kind": "package", + "language": "go", + "paths": [ + "diskreadings" + ], + "series": "0.1" } ] }, diff --git a/modules/distribution/cmd/distribution-tools/bounded.go b/modules/distribution/cmd/distribution-tools/bounded.go index 7bf77f0dd..c7211e4e7 100644 --- a/modules/distribution/cmd/distribution-tools/bounded.go +++ b/modules/distribution/cmd/distribution-tools/bounded.go @@ -46,8 +46,13 @@ func stepErr(bound time.Duration, what string, f func() error) error { return err } -// boundedObjects is the incoming object store with each operation bounded and logged. -type boundedObjects struct{ parts.Objects } +// boundedObjects is the incoming object store with each operation bounded and logged. Purge is the store's purge of a +// deleted object's chunks (busstate.Objects.Purge): every delete of a chunk is followed by it, so what a delete left +// behind is dropped and the store's kept descriptions equal its live objects (design 47 H2 §813 (8); H-A-227, H-A-366). +type boundedObjects struct { + parts.Objects + Purge func(name string) error +} func (b boundedObjects) Used() (uint64, error) { return step(stepBound, "the incoming object store's fill (objects)", b.Objects.Used) @@ -59,7 +64,15 @@ func (b boundedObjects) Get(name string) ([]byte, error) { return step(stepBound, "the get of a chunk from the incoming object store (objects)", func() ([]byte, error) { return b.Objects.Get(name) }) } func (b boundedObjects) Delete(name string) error { - return stepErr(stepBound, "the delete of a chunk in the incoming object store (objects)", func() error { return b.Objects.Delete(name) }) + err := stepErr(stepBound, "the delete of a chunk in the incoming object store (objects)", func() error { return b.Objects.Delete(name) }) + if b.Purge == nil { + return err + } + perr := stepErr(stepBound, "the purge of a deleted chunk's leftovers in the incoming object store (objects)", func() error { return b.Purge(name) }) + if err != nil { + return err + } + return perr } // boundedTransfers is the transfers state with its reads and writes bounded and logged. diff --git a/modules/distribution/cmd/distribution-tools/bounded_test.go b/modules/distribution/cmd/distribution-tools/bounded_test.go index 64cec0079..04b1c0331 100644 --- a/modules/distribution/cmd/distribution-tools/bounded_test.go +++ b/modules/distribution/cmd/distribution-tools/bounded_test.go @@ -8,8 +8,16 @@ import ( "time" ) +// The incoming store's steps (design 47 H2 §819: one test function for the bounded steps). +func TestTheBoundedSteps(t *testing.T) { + t.Run("a hung step answers with its name", hungStepAnswersWithItsName) + t.Run("a given-up step says when its call ended", givenUpStepSaysWhenItsCallEnded) + t.Run("a deleted chunk is purged", deletedChunkIsPurged) + t.Run("a finding is said off the path", findingIsSaidOffThePath) +} + // A bus operation that never answers becomes an error naming its step, within the bound. -func TestAHungStepAnswersWithItsName(t *testing.T) { +func hungStepAnswersWithItsName(t *testing.T) { block := make(chan struct{}) defer close(block) _, err := step(10*time.Millisecond, "the write of the idle key", func() (int, error) { <-block; return 0, nil }) @@ -22,7 +30,7 @@ func TestAHungStepAnswersWithItsName(t *testing.T) { } // A step given up on is said given up by name, and the log says later when the call behind it ended and how (A-443a). -func TestAGivenUpStepSaysWhenItsCallEnded(t *testing.T) { +func givenUpStepSaysWhenItsCallEnded(t *testing.T) { var mu sync.Mutex var lines []string ended := make(chan struct{}) @@ -52,7 +60,7 @@ func TestAGivenUpStepSaysWhenItsCallEnded(t *testing.T) { } // The finding is said off the caller's path: a writer that never answers does not hold the call that says it. -func TestAFindingIsSaidOffThePath(t *testing.T) { +func findingIsSaidOffThePath(t *testing.T) { block := make(chan struct{}) defer close(block) say := boundedFinding(func(string, string, string, bool) { <-block }) @@ -68,3 +76,31 @@ func TestAFindingIsSaidOffThePath(t *testing.T) { t.Fatal("the call was held by the finding") } } + +// fakeObjects is an object store that counts deletes. +type fakeObjects struct{ deleted []string } + +func (f *fakeObjects) Put(string, []byte) error { return nil } +func (f *fakeObjects) Get(string) ([]byte, error) { return nil, nil } +func (f *fakeObjects) Delete(name string) error { f.deleted = append(f.deleted, name); return nil } +func (f *fakeObjects) Used() (uint64, error) { return 0, nil } + +// Every delete of a chunk purges what it left behind, so the store's kept descriptions equal its live objects (design 47 +// H2 §813 (8)); a purge's failure is said, never swallowed. +func deletedChunkIsPurged(t *testing.T) { + f := &fakeObjects{} + var purged []string + b := boundedObjects{f, func(name string) error { purged = append(purged, name); return nil }} + for i := range 1000 { + if err := b.Delete(fmt.Sprintf("chunk.%d", i)); err != nil { + t.Fatal(err) + } + } + if len(f.deleted) != 1000 || len(purged) != 1000 || purged[999] != "chunk.999" { + t.Fatalf("deleted %d, purged %d", len(f.deleted), len(purged)) + } + b.Purge = func(string) error { return fmt.Errorf("no responders") } + if err := b.Delete("chunk.x"); err == nil || !strings.Contains(err.Error(), "no responders") { + t.Fatalf("a failed purge answered %v", err) + } +} diff --git a/modules/distribution/cmd/distribution-tools/contract.go b/modules/distribution/cmd/distribution-tools/contract.go index 4fe26822a..6e4e08f1b 100644 --- a/modules/distribution/cmd/distribution-tools/contract.go +++ b/modules/distribution/cmd/distribution-tools/contract.go @@ -40,11 +40,15 @@ func partAnswer(in reg.PublishPartInput, a holder.PublishAnswer) reg.PublishPart return reg.PublishPartAnswer{Transfer: in.Transfer, Part: in.Part, Received: in.Sequence + 1, Complete: a.Ended} } -// versionsAnswer is `versions`: each version with the digest the store holds under it. +// versionsAnswer is `versions`: each version with the digest its reference names (holder.Verbs.VersionDigest). func versionsAnswer(v *holder.Verbs, kind string, a holder.VersionsAnswer) reg.VersionsAnswer { out := reg.VersionsAnswer{Name: a.Name, Versions: []reg.Artifact{}} for _, ver := range a.Versions { - d, _ := v.Catalog.Digest(a.Name, ver) + d, err := v.VersionDigest(a.Seat, a.Name, ver) + if err != nil { + // The contract's answer has no field for why; the version is answered with no digest and the reason said here. + logf("versions: %s %s on %s answers no digest: %v", a.Name, ver, a.Seat, err) + } out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind}) } return out diff --git a/modules/distribution/cmd/distribution-tools/contract_test.go b/modules/distribution/cmd/distribution-tools/contract_test.go index 1ed66b9f2..436ff9566 100644 --- a/modules/distribution/cmd/distribution-tools/contract_test.go +++ b/modules/distribution/cmd/distribution-tools/contract_test.go @@ -12,6 +12,12 @@ import ( "distribution/internal/holder" ) +// twoDigests is a store whose every version's manifest digest and blob differ. +type twoDigests struct{ holder.Catalog } + +func (twoDigests) Digest(string, string) (string, error) { return "sha256:manifest", nil } +func (twoDigests) Blob(string, string) (string, error) { return "sha256:blob", nil } + func jsonFields(v any) map[string]bool { out := map[string]bool{} t := reflect.TypeOf(v) @@ -28,9 +34,9 @@ func jsonFields(v any) map[string]bool { func TestTheVerbsSpeakTheSeatsContract(t *testing.T) { inputs := map[string]any{reg.VerbPublish: reg.PublishInput{}, reg.VerbPublishPart: reg.PublishPartInput{}, reg.VerbVersions: reg.VersionsInput{}, reg.VerbRemove: reg.RemoveInput{}, reg.VerbHold: reg.HoldInput{}, - reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbTags: reg.TagsInput{}} + reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbNameOf: reg.NameOfInput{}, reg.VerbTags: reg.TagsInput{}} seen := 0 - for _, tool := range tools(&holder.Verbs{}, kept[holder.Window]{}) { + for _, tool := range tools(&holder.Verbs{}, kept[holder.Window]{}, nil) { seat, verb, ok := strings.Cut(tool.Name, ".") in, isVerb := inputs[verb] if !ok || !isVerb || (seat != holder.ImageSeat && seat != holder.ArtifactSeat) { @@ -45,8 +51,8 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) { } } } - if seen != 14 { - t.Errorf("%d seat verbs served, want 14 (8 on the image seat, 6 on the artifact seat)", seen) + if seen != 15 { + t.Errorf("%d seat verbs served, want 15 (9 on the image seat, 6 on the artifact seat)", seen) } for event, want := range map[string]any{holder.EventPublished: ®.Outcome{}, holder.EventKept: ®.KeptEvent{}, holder.EventHeld: ®.Hold{}, holder.EventReleased: ®.Hold{}} { b, _ := json.Marshal(eventBody(event, holder.Event{Name: "m/a", Kind: holder.KindArchive, Digest: "sha256:aa", Holder: holder.Self, By: "x.artifact-store-tools"})) @@ -59,6 +65,14 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) { if a := publishAnswer(holder.PublishAnswer{Transfer: "t", Missing: []string{"sha256:bb"}}); !reflect.DeepEqual(a.Lacks, []string{"sha256:bb"}) || a.Held { t.Errorf("publish answers %+v", a) } + // versions answers the digest a reference names (design 47 G A-430a): the blob on the artifact seat, the manifest on the image seat. + cat := twoDigests{} + for _, c := range []struct{ seat, want string }{{holder.ArtifactSeat, "sha256:blob"}, {holder.ImageSeat, "sha256:manifest"}} { + got := versionsAnswer(&holder.Verbs{Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}) + if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" { + t.Errorf("versions on %s answers %+v, want digest %s", c.seat, got.Versions, c.want) + } + } if r, err := partOf(reg.PublishPartInput{Transfer: "t", Part: "sha256:bb", Data: "aGk=", Last: true}); err != nil || string(r.Data) != "hi" || r.Digest != "sha256:bb" { t.Errorf("publish-part read %+v, %v", r, err) } diff --git a/modules/distribution/cmd/distribution-tools/main.go b/modules/distribution/cmd/distribution-tools/main.go index ae4a503b4..a28d28791 100644 --- a/modules/distribution/cmd/distribution-tools/main.go +++ b/modules/distribution/cmd/distribution-tools/main.go @@ -22,9 +22,10 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" meshconditions "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" reg "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry" + oci "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts" stdio "git.novox.be/novox/mesh-sdk/go" - "git.novox.be/novox/mesh-sdk/go/seatlist" + "git.novox.be/novox/mesh-sdk/go/busstate" "git.novox.be/novox/mesh-sdk/go/views" "distribution/internal/holder" @@ -243,7 +244,7 @@ func arg[T any](args map[string]any) (T, error) { func str(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) } // tools are distribution's tools over v. -func tools(v *holder.Verbs, windows kept[holder.Window]) []stdio.Tool { +func tools(v *holder.Verbs, windows kept[holder.Window], taken *asks) []stdio.Tool { obj := func(props map[string]any, req ...string) map[string]any { return map[string]any{"type": "object", "required": req, "properties": props} } @@ -261,7 +262,9 @@ func tools(v *holder.Verbs, windows kept[holder.Window]) []stdio.Tool { caller := stdio.CallerOf(args) start := time.Now() logf("%s.publish received from %s: %s %s (%s, %d parts)", seat, caller, in.Name, in.Version, in.Kind, len(in.Parts)) - a, err := v.Publish(seat, caller, publishOf(in)) + r := publishOf(in) + a, err := taken.once(seat, stdio.AskIDOf(args), func() (holder.PublishAnswer, error) { return v.Publish(seat, caller, r) }, + func() (holder.PublishAnswer, error) { return v.Repeat(seat, caller, r) }) if err == nil { // The window's learning asks the delivery view (up to 60 s, past the runner's 30 s call bound), // so it never holds the answer. @@ -311,15 +314,7 @@ func tools(v *holder.Verbs, windows kept[holder.Window]) []stdio.Tool { } return reg.RemoveAnswer{Removed: got.Removed, Kept: got.Kept, Reason: got.Reason, Tags: got.Tags, Artifact: ®.Artifact{Name: in.Name, Version: in.Version, Tag: in.Tag, Digest: in.Digest}}, nil }}, - stdio.Tool{Name: seat + "." + holder.VerbList, Description: "What the store holds of one repository, or of every repository the seat holds: each manifest's digest, whether it is an index and the manifests it names, the tags naming it, its size and whether it is held (ADR 0632 §3). Read from the store's own files; changes nothing.", - Input: obj(map[string]any{"name": s("/; every repository when not given")}), - Run: func(args map[string]any) (any, error) { - repos, err := v.List(context.Background(), seat, stdio.CallerOf(args), str(args, "name")) - if err != nil { - return nil, err - } - return reg.ListAnswer{Repositories: repos}, nil - }}, + listTool(v, seat), stdio.Tool{Name: seat + "." + holder.VerbHold, Description: "Keep one untagged bundle, archive or copied base from retention (the artifact sweep alone); says held.", Input: obj(map[string]any{"name": s("name"), "digest": s("sha256:…"), "reason": s("which of the sweep's rules keeps it")}, "name", "digest", "reason"), Run: func(args map[string]any) (any, error) { @@ -369,6 +364,19 @@ func tools(v *holder.Verbs, windows kept[holder.Window]) []stdio.Tool { } return reg.MirrorAnswer{Digest: in.Digest, Reference: ref}, nil }}, + stdio.Tool{Name: holder.ImageSeat + "." + holder.VerbNameOf, Description: "The reference an outside image, as a manifest's from names it pinned by its digest, is kept under in the store (upstream//@ in the seat's form), the one mirror answers; reads only, asks no copy, refuses a from with no digest.", + Input: obj(map[string]any{"from": s("[:]@sha256:…")}, "from"), + Run: func(args map[string]any) (any, error) { + in, err := arg[reg.NameOfInput](args) + if err != nil { + return nil, err + } + ref, err := v.NameOf(holder.ImageSeat, in.From) + if err != nil { + return nil, err + } + return reg.NameOfAnswer{Reference: ref}, nil + }}, stdio.Tool{Name: "registry_health", Description: "distribution's health check, run by the runtime each minute: versions of each seat asked through the store's read side (the program's port 5100); fails naming the program when it does not answer.", Input: obj(map[string]any{}), Run: func(map[string]any) (any, error) { @@ -488,11 +496,11 @@ func main() { }() base, _ := url.Parse("http://127.0.0.1:5001") store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}} - h := &holder.Holder{Logf: logf, Objects: boundedObjects{parts.BusObjects(holder.IncomingObjects)}, Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: boundedFinding(findings.Say), + h := &holder.Holder{Logf: logf, Objects: boundedObjects{parts.BusObjects(holder.IncomingObjects), busstate.ObjectsOf(holder.IncomingObjects).Purge}, Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: boundedFinding(findings.Say), Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))} files := &holder.Files{Container: or(os.Getenv("MESH_REGISTRY_CONTAINER"), "mesh-registry"), Run: holder.ExecRunner, UID: os.Getuid()} v := &holder.Verbs{Holder: h, Catalog: store, Holds: kept[holder.Hold]{state: "holds", key: holder.Hold.Key}, Mirrors: mirrors{}, - Files: files, SweepHolder: func() (string, error) { return seatlist.HolderOf(stdio.Ask, holder.SweepSeat) }} + Files: files} go followMirrors(v) go parts.FollowIdle(holder.IdleState, parts.IDs(h.Transfers), h.Expired, func(id string, dropped bool, err error) { if err != nil { @@ -502,7 +510,13 @@ func main() { logf("transfer %s had no part for %s: dropped with its parts", id, holder.TransferIdle) }) windows := kept[holder.Window]{state: "windows", key: func(w holder.Window) string { return w.Name }} - if err := stdio.Serve("", tools(v, windows)); err != nil { + bound, err := stdio.SettingDuration(askTakenBound, askTakenDefault) + if err != nil { + logf("the setting %s: %v", askTakenBound, err) + os.Exit(1) + } + taken := &asks{take: stdio.State(stdio.TakenState).TakeOnce, bound: bound} + if err := stdio.Serve("", tools(v, windows, taken)); err != nil { logf("%v", err) os.Exit(1) } @@ -514,3 +528,41 @@ func or(v, d string) string { } return v } + +// listTool is the seat's verb list. On oci-artifact-registry it filters by name or module while it reads and pages at 768 KB +// by the cursor next (design 47 H2 §779, §811, §813 (7)); on container-image-registry, whose form takes no cursor, it answers +// whole. +func listTool(v *holder.Verbs, seat string) stdio.Tool { + s := func(d string) map[string]any { return map[string]any{"type": "string", "description": d} } + description := "What the store holds of one repository, or of every repository the seat holds: each manifest's digest, whether it is an index and the manifests it names, the tags naming it, its size and whether it is held (ADR 0632 §3). Read from the store's own files; changes nothing." + props := map[string]any{"name": s("/; every repository when not given")} + if seat == holder.ArtifactSeat { + description += " Filtered by name or module while it reads and paged by the cursor next, at most 768 KB a page, capped saying the rest is read from next." + props["module"] = s("only the repositories of this module, /*") + props["next"] = s("the cursor the previous page answered; absent for the first page") + } + return stdio.Tool{Name: seat + "." + holder.VerbList, Description: description, Input: map[string]any{"type": "object", "properties": props}, + Run: func(args map[string]any) (any, error) { + if seat != holder.ArtifactSeat { + page, err := v.List(context.Background(), seat, stdio.CallerOf(args), holder.ListQuery{Name: str(args, "name")}) + if err != nil { + return nil, err + } + return reg.ListAnswer{Repositories: page.Repositories}, nil + } + in, err := arg[oci.ListInput](args) + if err != nil { + return nil, err + } + page, err := v.List(context.Background(), seat, stdio.CallerOf(args), holder.ListQuery{Name: in.Name, Module: in.Module, Next: in.Next, PageBytes: holder.ListPageBytes}) + if err != nil { + return nil, err + } + out := oci.ListAnswer{Form: oci.Form, Repositories: []oci.Repository{}, Capped: page.Capped, Next: page.Next, Total: int64(page.Total)} + raw, _ := json.Marshal(page.Repositories) + if err := json.Unmarshal(raw, &out.Repositories); err != nil { + return nil, err + } + return out, nil + }} +} diff --git a/modules/distribution/cmd/distribution-tools/taken.go b/modules/distribution/cmd/distribution-tools/taken.go new file mode 100644 index 000000000..4c5ec9f8e --- /dev/null +++ b/modules/distribution/cmd/distribution-tools/taken.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "sync" + "time" + + "distribution/internal/holder" +) + +// askTakenBound is the setting the taken key of a publish ask lives (design 47 H2 §775, H-A-381 (2)): the holder never +// receives the caller's bound, so it keeps an ask's id this long, the largest caller's bound by default. +const askTakenBound = "ask-taken-bound" + +// askTakenDefault is ask-taken-bound's default, the runner's ask-unanswered-bound (H-A-381 (2)). +const askTakenDefault = 10 * time.Minute + +// asks takes each publish ask once by its id (design 47 H2 §775; ADR 0668 §2; H-A-381): the first call with an id is +// kept in the state taken and acts; a repeat while that act runs joins it and gets its answer; a repeat after it ended +// answers the act's state read afresh (holder.Repeat), never acting twice. No answer is kept in taken. A call that +// carries no ask id is no kept call, and acts as it did before. +type asks struct { + take func(seat, ask string, bound time.Duration) (bool, error) + bound time.Duration + mu sync.Mutex + running map[string]*flight + // joined, when set, is told each repeat that joins a running act (a test's hook). + joined func() +} + +// flight is one act of a taken ask while it runs, which a repeat joins. +type flight struct { + done chan struct{} + a holder.PublishAnswer + err error +} + +func (k *asks) once(seat, ask string, act, repeat func() (holder.PublishAnswer, error)) (holder.PublishAnswer, error) { + if ask == "" || k == nil || k.take == nil { + return act() + } + key := seat + "." + ask + k.mu.Lock() + if f, ok := k.running[key]; ok { + k.mu.Unlock() + if k.joined != nil { + k.joined() + } + <-f.done + return f.a, f.err + } + if k.running == nil { + k.running = map[string]*flight{} + } + f := &flight{done: make(chan struct{})} + k.running[key] = f + k.mu.Unlock() + defer func() { + k.mu.Lock() + delete(k.running, key) + k.mu.Unlock() + close(f.done) + }() + took, err := k.take(seat, ask, k.bound) + switch { + case err != nil: + f.err = fmt.Errorf("publish: the ask %s of %s cannot be taken: %w", ask, seat, err) + case took: + f.a, f.err = act() + default: + logf("%s.publish: the ask %s was taken before; it answers the act's state, acting not again", seat, ask) + f.a, f.err = repeat() + } + return f.a, f.err +} diff --git a/modules/distribution/cmd/distribution-tools/taken_test.go b/modules/distribution/cmd/distribution-tools/taken_test.go new file mode 100644 index 000000000..2107a7265 --- /dev/null +++ b/modules/distribution/cmd/distribution-tools/taken_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "distribution/internal/holder" +) + +// A publish ask given twice acts once (design 47 H2 §775; H-A-381): a repeat while the act runs joins it and gets its +// answer, a repeat after it ended answers the act's state, a call with no ask id acts as before, a take that fails is said. +func TestAPublishAskIsTakenOnce(t *testing.T) { + taken := map[string]bool{} + var mu sync.Mutex + k := &asks{bound: time.Minute, take: func(seat, ask string, bound time.Duration) (bool, error) { + mu.Lock() + defer mu.Unlock() + if ask == "broken" { + return false, errors.New("no responders") + } + if bound != time.Minute || taken[seat+"."+ask] { + return false, nil + } + taken[seat+"."+ask] = true + return true, nil + }} + var acts, repeats atomic.Int32 + release, started, joined := make(chan struct{}), make(chan struct{}, 1), make(chan struct{}, 1) + k.joined = func() { joined <- struct{}{} } + act := func() (holder.PublishAnswer, error) { + acts.Add(1) + started <- struct{}{} + <-release + return holder.PublishAnswer{Transfer: "t", Missing: []string{"d"}}, nil + } + repeat := func() (holder.PublishAnswer, error) { repeats.Add(1); return holder.PublishAnswer{Transfer: "t"}, nil } + answers := make(chan holder.PublishAnswer, 2) + go func() { a, _ := k.once(holder.ArtifactSeat, "a1", act, repeat); answers <- a }() + <-started + go func() { a, _ := k.once(holder.ArtifactSeat, "a1", act, repeat); answers <- a }() + <-joined + close(release) + for range 2 { + if a := <-answers; len(a.Missing) != 1 { + t.Errorf("an answer of the running act = %+v", a) + } + } + if a, _ := k.once(holder.ArtifactSeat, "a1", act, repeat); acts.Load() != 1 || repeats.Load() != 1 || a.Transfer != "t" { + t.Errorf("acts %d, repeats %d after a repeat of an ended act", acts.Load(), repeats.Load()) + } + release = make(chan struct{}) + close(release) + act2 := func() (holder.PublishAnswer, error) { acts.Add(1); return holder.PublishAnswer{}, nil } + if _, err := k.once(holder.ArtifactSeat, "", act2, repeat); err != nil || acts.Load() != 2 { + t.Errorf("a call with no ask id: acts %d, %v", acts.Load(), err) + } + if _, err := k.once(holder.ArtifactSeat, "broken", act2, repeat); err == nil || acts.Load() != 2 { + t.Errorf("a failed take: acts %d, %v", acts.Load(), err) + } +} diff --git a/modules/distribution/go.mod b/modules/distribution/go.mod index a16a3916a..4379a5784 100644 --- a/modules/distribution/go.mod +++ b/modules/distribution/go.mod @@ -10,6 +10,7 @@ require ( git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 github.com/nats-io/nats.go v1.54.0 @@ -31,7 +32,6 @@ require ( require ( git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000 // indirect - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect ) require git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery v0.0.0-00010101000000-000000000000 // indirect diff --git a/modules/distribution/internal/holder/holder_test.go b/modules/distribution/internal/holder/holder_test.go index 08d6aee84..ec051f903 100644 --- a/modules/distribution/internal/holder/holder_test.go +++ b/modules/distribution/internal/holder/holder_test.go @@ -18,6 +18,7 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" artifactref "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient/reference" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/publishconformance" ) type memObjects map[string][]byte @@ -61,17 +62,35 @@ func (b fakeBuilder) Recorded(string, string, string) (bool, string, error) { } type fakeStore struct { - has map[string]bool - put []map[string][]byte + has map[string]bool + held map[string]heldAt // name@version to what the store holds there + put []map[string][]byte } +// heldAt is what a version's tag names in the store: the manifest's digest and, for a bundle or an archive, the one layer +// that manifest keeps, two digests as the store holds them (H-A-474). +type heldAt struct{ manifest, layer string } + func (s *fakeStore) Has(_, d string) (bool, error) { return s.has[d], nil } func (s *fakeStore) Put(t PublishRequest, parts map[string][]byte) (string, error) { s.put = append(s.put, parts) return t.Name + "@" + t.Digest, nil } -func (s *fakeStore) Held(string, string, string) (string, bool, error) { return "", false, nil } -func (s *fakeStore) Holds(r PublishRequest) (bool, error) { return s.has[r.Digest], nil } +func (s *fakeStore) Held(r PublishRequest) (string, string, error) { + at, ok := s.held[r.Name+"@"+r.Version] + if !ok { + return "", "", nil + } + d := at.layer + if r.Kind == KindImage || r.Kind == KindUpstream { + d = at.manifest + } + if d != r.Digest { + return "", d, nil + } + return r.Name + "@" + d, "", nil +} +func (s *fakeStore) Holds(r PublishRequest) (bool, error) { return s.has[r.Digest], nil } type said struct { seat, event string @@ -108,6 +127,9 @@ func (c *fakeCatalog) Versions(name string) ([]string, error) { func (c *fakeCatalog) Digest(name, version string) (string, error) { return c.tags[name+":"+version], nil } +func (c *fakeCatalog) Blob(name, version string) (string, error) { + return c.tags[name+":"+version], nil +} // Remove deletes by the digest, as the store does: every tag naming the digest goes with it. func (c *fakeCatalog) Remove(name, version string) error { @@ -202,8 +224,7 @@ func newBed(builderOK bool) *bed { return nil }, Finding: func(kind, subject, _ string, raised bool) { b.findings[kind+" "+subject] = raised }} - b.v = &Verbs{Holder: b.h, Catalog: b.cat, Holds: memHolds{}, Mirrors: memMirrors{}, - SweepHolder: func() (string, error) { return "artifact-store-tools", nil }} + b.v = &Verbs{Holder: b.h, Catalog: b.cat, Holds: memHolds{}, Mirrors: memMirrors{}} return b } @@ -247,6 +268,25 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { } }) + // A publish ask taken before answers the act's state read afresh and never publishes again (design 47 H2 §775; + // H-A-381): an open transfer its lacking parts, a transfer gone with nothing held a refusal naming it. + t.Run("a repeated ask answers the act's state", func(t *testing.T) { + b := newBed(true) + if _, err := b.h.Repeat(ArtifactSeat, builder, req("tr")); err == nil || !strings.Contains(err.Error(), "transfer tr is gone") { + t.Errorf("a repeat of an act that never happened answered %v", err) + } + if _, err := b.h.Publish(ArtifactSeat, builder, req("tr")); err != nil { + t.Fatal(err) + } + opened := len(b.h.Transfers.(memTransfers)) + if a, err := b.h.Repeat(ArtifactSeat, builder, req("tr")); err != nil || !reflect.DeepEqual(a.Missing, []string{part.Digest}) { + t.Errorf("a repeat of an open transfer = %+v, %v", a, err) + } + if len(b.h.Transfers.(memTransfers)) != opened || len(b.said) != 0 { + t.Errorf("a repeat acted: transfers %d, said %+v", len(b.h.Transfers.(memTransfers)), b.said) + } + }) + t.Run("a transfer in parts, cut and resumed, hashed, numbered by the builder, published", func(t *testing.T) { b := newBed(true) a, err := b.h.Publish(ArtifactSeat, builder, req("t1")) @@ -313,6 +353,16 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { _, err := b.h.Publish(ArtifactSeat, builder, req("t")) return err }, "the builder did not reserve it"}, + {"a version the store holds at another digest", func(b *bed) error { + b.store.held = map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}} + r := req("t") + r.Digest = "sha256:aa" + _, err := b.h.Publish(ArtifactSeat, builder, r) // the reservation names no digest yet: the bed's builder says yes + if !b.findings["publish-refused m/program@0.1.4"] || len(b.store.put) != 0 { + return errors.New("not refused loudly, or stored") + } + return err + }, "the store holds m/program@0.1.4 at digest sha256:bb, not sha256:aa"}, {"an image on the artifact seat", func(b *bed) error { r := req("t") r.Kind = KindImage @@ -323,10 +373,6 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { _, err := b.v.Remove(ArtifactSeat, "novox.mesh-delivery-builder", RemoveRequest{Name: "m/program", Version: "0.1.4", Reason: "branch ended"}) return err }, "has no tag"}, - {"a retention removal from another caller than the sweep", func(b *bed) error { - _, err := b.v.Remove(ArtifactSeat, "novox.mesh-delivery-builder", RemoveRequest{Name: "m/program", Digest: part.Digest, Reason: ReasonRetention}) - return err - }, "artifact sweep's alone"}, {"a retention removal of a held archive", func(b *bed) error { _ = b.v.HoldOne(ArtifactSeat, "novox.artifact-store-tools", HoldRequest{Name: "m/a", Kind: KindArchive, Digest: part.Digest}) _, err := b.v.Remove(ArtifactSeat, "novox.artifact-store-tools", RemoveRequest{Name: "m/a", Digest: part.Digest, Reason: ReasonRetention}) @@ -335,16 +381,6 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { {"a hold of an image", func(b *bed) error { return b.v.HoldOne(ImageSeat, "novox.artifact-store-tools", HoldRequest{Name: "m/i", Kind: KindImage, Digest: part.Digest}) }, "never held"}, - {"a retention removal by the module that held the sweep seat before", func(b *bed) error { - b.v.SweepHolder = func() (string, error) { return "artifact-sweeper", nil } // the seat's holder as the seat says it now - _, err := b.v.Remove(ArtifactSeat, "novox.artifact-store-tools", RemoveRequest{Name: "m/program", Digest: part.Digest, Reason: ReasonRetention}) - return err - }, "artifact sweep's alone"}, - {"a retention removal while the sweep's holder cannot be read", func(b *bed) error { - b.v.SweepHolder = func() (string, error) { return "", errors.New("the seat's holders are not answered") } - _, err := b.v.Remove(ArtifactSeat, "novox.artifact-store-tools", RemoveRequest{Name: "m/program", Digest: part.Digest, Reason: ReasonRetention}) - return err - }, "cannot be read"}, {"a release in distribution's own name", func(b *bed) error { _, err := b.v.Release(ArtifactSeat, "novox.distribution", HoldRequest{Name: "m/a", Digest: part.Digest}) return err @@ -360,6 +396,47 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { } } }) + // H-A-474: the store judges a held version like with like, through its own OCI code over a store in memory. A bundle + // is stored as a manifest whose digest is not its layer's: the same bytes published again are already held (ended, no + // error, nothing stored again, also on a repeated ask); other bytes are refused naming the layer the store holds. An + // image is judged by its manifest's digest. + t.Run("a held version is judged by the artifact's own digest", func(t *testing.T) { + reg := newFakeRegistry() + sts := httptest.NewServer(reg) + defer sts.Close() + u, _ := url.Parse(sts.URL) + o := &OCI{Base: u} + if _, err := o.Put(req("first"), map[string][]byte{part.Digest: blob}); err != nil { + t.Fatal(err) + } + if m, _ := o.Digest("m/program", "0.1.4"); m == "" || m == part.Digest { + t.Fatalf("the stored manifest's digest %q; want one, not the layer's %s", m, part.Digest) + } + b := newBed(true) + b.h.Store = o + uploads := len(reg.blobs) + a, err := b.h.Publish(ArtifactSeat, builder, req("again")) + if err != nil || !a.Ended || len(a.Missing) != 0 || len(b.said) != 1 || b.said[0].event != EventPublished || b.findings["publish-refused m/program@0.1.4"] { + t.Errorf("the same bundle again = %+v, %v; said %+v; want already held, published said, nothing refused", a, err, b.said) + } + if a, err := b.h.Repeat(ArtifactSeat, builder, req("again")); err != nil || !a.Ended { + t.Errorf("a repeated ask of the held bundle = %+v, %v; want ended", a, err) + } + other := req("other") + other.Digest = digestOf([]byte("other bytes")) + if _, err := b.h.Publish(ArtifactSeat, builder, other); err == nil || !strings.Contains(err.Error(), "at digest "+part.Digest+", not "+other.Digest) { + t.Errorf("other bytes at the held version = %v; want refused naming the held layer %s", err, part.Digest) + } + if len(reg.blobs) != uploads { + t.Errorf("the store took %d blobs more; want none", len(reg.blobs)-uploads) + } + img := []byte(`{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","layers":[]}`) + reg.manifests["m/image:0.2.0"], reg.types["m/image:0.2.0"] = img, mediaManifest + ir := PublishRequest{Name: "m/image", Version: "0.2.0", Kind: KindImage, Digest: digestOf(img)} + if ref, other, err := o.Held(ir); err != nil || ref != "m/image@"+digestOf(img) || other != "" { + t.Errorf("an image held at its manifest = %q, %q, %v; want held", ref, other, err) + } + }) t.Run("only the missing layers are sent, and an idle transfer is dropped", func(t *testing.T) { b := newBed(true) other := []byte("layer two") @@ -447,7 +524,8 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { t.Run("the sweep's removal, hold and release", func(t *testing.T) { b := newBed(true) sweep := "novox.artifact-store-tools" - if _, err := b.v.Remove(ArtifactSeat, sweep, RemoveRequest{Name: "m/a", Digest: part.Digest, Kind: KindArchive, Reason: ReasonRetention}); err != nil { + // A removal for retention is taken whoever asks it; the seat's holders are not read (design 47 H2 §813 (7)). + if _, err := b.v.Remove(ArtifactSeat, "novox.artifact-sweeper", RemoveRequest{Name: "m/a", Digest: part.Digest, Kind: KindArchive, Reason: ReasonRetention}); err != nil { t.Fatal(err) } if err := b.v.HoldOne(ArtifactSeat, sweep, HoldRequest{Name: "m/b", Kind: KindArchive, Digest: part.Digest}); err != nil { @@ -464,7 +542,7 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { for _, s := range b.said { events = append(events, s.event+" "+s.body.By) } - if want := []string{"removed " + sweep, "held " + sweep, "released person.jochen"}; !reflect.DeepEqual(events, want) { + if want := []string{"removed novox.artifact-sweeper", "held " + sweep, "released person.jochen"}; !reflect.DeepEqual(events, want) { t.Errorf("said %v, want %v", events, want) } b.cat.tags["m/p:0.1.5-feat-x.1"] = part.Digest @@ -666,6 +744,22 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { } } }) + // Design 47 G A-490: the publish contract's no-parts form, as every publish holder is held to it. + t.Run("the publish conformance cases", func(t *testing.T) { + publishconformance.Run(t, func(t *testing.T) publishconformance.Bed { + b := newBed(true) + return publishconformance.Bed{ + Hold: func(d string) { b.store.has[d] = true }, + Publish: func(name, version, digest string) publishconformance.Outcome { + got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"}) + o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err} + if len(b.said) > 0 { + o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason + } + return o + }} + }) + }) t.Run("a publish with a version and no parts tags the held digest at the store's size; one not held is not stored", func(t *testing.T) { // Design 47 G A-417, A-73, A-50: the build stored the bundle untagged; the builder's publish of its version with that // digest and no parts tags it and says published, nothing sent; a digest the store holds none of is refused as not @@ -692,6 +786,23 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { if err := json.Unmarshal(store.manifests["m/tools:0.1.4"], &man); err != nil || len(man.Layers) != 1 || man.Layers[0].Size != int64(len(blob)) || man.Layers[0].Digest != digestOf(blob) { t.Errorf("the version's manifest %s, want one layer of %d bytes", store.manifests["m/tools:0.1.4"], len(blob)) } + // `versions` answers the digest the version's reference names and its published carries (design 47 G A-430a): on the + // artifact seat the blob, which the node-engine fetches as /blobs/, never the manifest's own digest. + v := &Verbs{Holder: b.h, Catalog: &OCI{Base: base}} + for _, c := range []struct{ seat, version, want string }{ + {ArtifactSeat, "0.1.4", digestOf(blob)}, + {ImageSeat, "0.1.4", digestOf(store.manifests["m/tools:0.1.4"])}, + {ArtifactSeat, "0.1.9", ""}, + } { + if got, err := v.VersionDigest(c.seat, "m/tools", c.version); err != nil || got != c.want { + t.Errorf("VersionDigest(%s, m/tools, %s) = %q, %v, want %q", c.seat, c.version, got, err, c.want) + } + } + // A manifest that keeps no single blob answers no digest and says why. + store.manifests["m/tools:0.2.0"] = []byte(`{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:c"},"layers":[{"digest":"sha256:a"},{"digest":"sha256:b"}]}`) + if got, err := v.VersionDigest(ArtifactSeat, "m/tools", "0.2.0"); got != "" || err == nil || !strings.Contains(err.Error(), "2 layers") { + t.Errorf("VersionDigest of a manifest of two layers = %q, %v, want no digest and why", got, err) + } gone := "sha256:" + strings.Repeat("e", 64) _, err = b.h.Publish(ArtifactSeat, "x.mesh-delivery-builder", PublishRequest{Name: "m/tools", Version: "0.1.5", Kind: KindBundle, Digest: gone, Transfer: "republish-m-0-1-5-tools"}) if err == nil || !strings.Contains(err.Error(), "not stored: ") || !strings.Contains(err.Error(), gone) || store.manifests["m/tools:0.1.5"] != nil || @@ -712,6 +823,18 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { if strings.ContainsAny(key, ":@") { t.Errorf("the ask's key %q holds characters a key may not", key) } + // name-of answers the same reference for a manifest's pinned from, asking no copy (H-A-513); a from with no digest, + // and the artifact seat, are refused. + for _, from := range []string{"nats:2.11.17-alpine@" + d, "docker.io/library/nats@" + d} { + if named, err := b.v.NameOf(ImageSeat, from); err != nil || named != want || len(asked) != 1 { + t.Errorf("name-of %s = %q, %v, asks %d: want %s and no copy asked", from, named, err, len(asked), want) + } + } + for seat, from := range map[string]string{ImageSeat: "nats:2.11.17-alpine", ArtifactSeat: "nats@" + d} { + if named, err := b.v.NameOf(seat, from); err == nil { + t.Errorf("name-of %s on %s = %q: want a refusal", from, seat, named) + } + } if err := b.v.Mirrored(asked[key]); err != nil || len(b.said) != 1 || b.said[0].event != EventPublished || b.said[0].body.Reference != want || b.said[0].body.Kind != KindUpstream || len(asked) != 0 { t.Fatalf("the copy's end = %v, said %+v, asks %v: want published with the reference and the ask gone", err, b.said, asked) @@ -867,10 +990,24 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { Name string `json:"name"` Port int `json:"port"` } `json:"listens"` + Class string `json:"class"` + State []struct { + Name string `json:"name"` + MaxMiB int `json:"max-mib"` + } `json:"state"` } if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } + // Design 47 H2 H-A-411 (2): a core module, and every state names its cap, 8 MiB. + if m.Class != "core" { + t.Errorf("class %q, want core", m.Class) + } + for _, st := range m.State { + if st.MaxMiB != 8 { + t.Errorf("the state %s names max-mib %d, want 8", st.Name, st.MaxMiB) + } + } // The reservation is asked through the seat mesh-builds, so the manifest takes no package of the builder (design 47 §381). if len(m.Packages) != 0 { t.Errorf("packages %v: want none", m.Packages) diff --git a/modules/distribution/internal/holder/list.go b/modules/distribution/internal/holder/list.go index 022387c4b..4ae7e7ca7 100644 --- a/modules/distribution/internal/holder/list.go +++ b/modules/distribution/internal/holder/list.go @@ -9,9 +9,12 @@ package holder import ( "context" + "encoding/base64" + "encoding/json" "errors" "fmt" "sort" + "strings" reg "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry" ) @@ -25,27 +28,52 @@ type StoreFiles interface { Manifests(ctx context.Context, l *Listing) (map[string]*Manifest, map[string]string) } -// List is `list` on seat: the repositories it holds, or name alone; a repository the seat holds nothing of is not named, -// and name not held is an empty answer. A manifest whose content cannot be read fails the answer, by name: a listing -// missing one would read as the store not holding it. -func (v *Verbs) List(ctx context.Context, seat, caller, name string) ([]reg.Repository, error) { +// ListPageBytes is the most a page of oci-artifact-registry's list answers (design 47 H2 §811): 768 KB. +const ListPageBytes = 768 << 10 + +// ListQuery is what a list is asked: Name or Module (`/*`) filter the repositories while the files are read, Next +// is the cursor a page answered, and PageBytes the most a page answers, 0 for the whole answer at once (the seat +// container-image-registry's list, whose form takes no cursor). +type ListQuery struct { + Name, Module, Next string + PageBytes int +} + +// ListPage is one page of a list: its repositories in order of their names, Total the repositories the filters hold in +// all, and Next the cursor of the next page, empty at the end; Capped says the page stopped at PageBytes. +type ListPage struct { + Repositories []reg.Repository + Capped bool + Total int + Next string +} + +// List is `list` on seat: the repositories it holds, or those q's filters name; a repository the seat holds nothing of is +// not named, and a name not held is an empty answer. A paged list continues after the repository its cursor names, in +// order of the names (design 47 H2 §779, §811, §813 (7)). A manifest whose content cannot be read fails the answer, by +// name: a listing missing one would read as the store not holding it. +func (v *Verbs) List(ctx context.Context, seat, caller string, q ListQuery) (ListPage, error) { if seat != ImageSeat && seat != ArtifactSeat { - return nil, fmt.Errorf("list: %s is no seat of distribution's", seat) + return ListPage{}, fmt.Errorf("list: %s is no seat of distribution's", seat) } if v.Files == nil { - return nil, errors.New("list: this process reads no store files") + return ListPage{}, errors.New("list: this process reads no store files") + } + after, err := listCursor(q.Next) + if err != nil { + return ListPage{}, err } l, err := v.Files.List(ctx) if err != nil { - return nil, fmt.Errorf("list: the store's files cannot be listed: %w", err) + return ListPage{}, fmt.Errorf("list: the store's files cannot be listed: %w", err) } - if name != "" { - r, held := l.Repos[name] - l = &Listing{Blobs: l.Blobs, Repos: map[string]*Repo{}} - if held { - l.Repos[name] = r + kept := &Listing{Blobs: l.Blobs, Repos: map[string]*Repo{}} + for name, r := range l.Repos { + if (q.Name == "" || name == q.Name) && (q.Module == "" || strings.HasPrefix(name, q.Module+"/")) { + kept.Repos[name] = r } } + l = kept docs, unread := v.Files.Manifests(ctx, l) if len(unread) > 0 { keys := make([]string, 0, len(unread)) @@ -53,11 +81,11 @@ func (v *Verbs) List(ctx context.Context, seat, caller, name string) ([]reg.Repo keys = append(keys, k) } sort.Strings(keys) - return nil, fmt.Errorf("list: %d manifests cannot be read, the first %s: %s", len(keys), keys[0], unread[keys[0]]) + return ListPage{}, fmt.Errorf("list: %d manifests cannot be read, the first %s: %s", len(keys), keys[0], unread[keys[0]]) } holds, err := v.Holds.List() if err != nil { - return nil, fmt.Errorf("list: the holds cannot be read: %w", err) + return ListPage{}, fmt.Errorf("list: the holds cannot be read: %w", err) } held := map[string]bool{} for _, h := range holds { @@ -102,5 +130,37 @@ func (v *Verbs) List(ctx context.Context, seat, caller, name string) ([]reg.Repo out = append(out, reg.Repository{Name: repo, Manifests: manifests}) } } - return out, nil + page := ListPage{Repositories: []reg.Repository{}, Total: len(out)} + size := 0 + for _, r := range out { + if r.Name <= after { + continue + } + if q.PageBytes > 0 { + raw, _ := json.Marshal(r) + if size+len(raw) > q.PageBytes { + if len(page.Repositories) == 0 { + return ListPage{}, fmt.Errorf("list: the repository %s alone is over a page's %d bytes (%d)", r.Name, q.PageBytes, len(raw)) + } + page.Capped = true + page.Next = base64.RawURLEncoding.EncodeToString([]byte(page.Repositories[len(page.Repositories)-1].Name)) + break + } + size += len(raw) + } + page.Repositories = append(page.Repositories, r) + } + return page, nil +} + +// listCursor is the repository a page's cursor continues after, "" for the first page; a cursor no page answered is refused. +func listCursor(next string) (string, error) { + if next == "" { + return "", nil + } + name, err := base64.RawURLEncoding.DecodeString(next) + if err != nil || len(name) == 0 { + return "", fmt.Errorf("list: %q is no cursor a page of list answered", next) + } + return string(name), nil } diff --git a/modules/distribution/internal/holder/list_test.go b/modules/distribution/internal/holder/list_test.go index b49cd7dc7..3f1562738 100644 --- a/modules/distribution/internal/holder/list_test.go +++ b/modules/distribution/internal/holder/list_test.go @@ -2,6 +2,7 @@ package holder import ( "context" + "encoding/json" "fmt" "reflect" "strings" @@ -132,7 +133,8 @@ func TestListAnswersTheStoreThroughTheSeat(t *testing.T) { t.Fatal(err) } ctx := context.Background() - images, err := b.v.List(ctx, ImageSeat, "mesh-anyone", "") + page, err := b.v.List(ctx, ImageSeat, "mesh-anyone", ListQuery{}) + images := page.Repositories if err != nil { t.Fatal(err) } @@ -155,7 +157,8 @@ func TestListAnswersTheStoreThroughTheSeat(t *testing.T) { if !reflect.DeepEqual(images, want) { t.Errorf("the image seat lists %+v\nwant %+v", images, want) } - artifacts, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", "") + page, err = b.v.List(ctx, ArtifactSeat, "mesh-anyone", ListQuery{}) + artifacts := page.Repositories if err != nil { t.Fatal(err) } @@ -166,16 +169,42 @@ func TestListAnswersTheStoreThroughTheSeat(t *testing.T) { if !reflect.DeepEqual(artifacts, wantA) { t.Errorf("the artifact seat lists %+v\nwant %+v", artifacts, wantA) } - if one, err := b.v.List(ctx, ImageSeat, "mesh-anyone", "app/tools"); err != nil || len(one) != 0 { + if one, err := b.v.List(ctx, ImageSeat, "mesh-anyone", ListQuery{Name: "app/tools"}); err != nil || len(one.Repositories) != 0 { t.Errorf("the image seat's list of a bundle's repository: %+v, %v", one, err) } - if one, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", "mesh/facts"); err != nil || len(one) != 1 || one[0].Name != "mesh/facts" { + if one, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", ListQuery{Name: "mesh/facts"}); err != nil || len(one.Repositories) != 1 || one.Repositories[0].Name != "mesh/facts" { t.Errorf("one repository: %+v, %v", one, err) } + // Design 47 H2 §813 (7), §811, §779: the artifact seat's list filters by module while it reads, and pages by its cursor in + // order of the names, each page within its bytes, saying capped and the total the filters hold. + if mod, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", ListQuery{Module: "app", PageBytes: ListPageBytes}); err != nil || + !reflect.DeepEqual(mod, ListPage{Repositories: wantA[:1], Total: 1}) { + t.Errorf("the module app's repositories: %+v, %v", mod, err) + } + first, _ := json.Marshal(wantA[0]) + second, _ := json.Marshal(wantA[1]) + var paged []reg.Repository + q := ListQuery{PageBytes: max(len(first), len(second))} // one repository a page + for pages := 0; ; pages++ { + p, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", q) + if err != nil || p.Total != 2 || p.Capped != (p.Next != "") || pages > 2 { + t.Fatalf("page %d: %+v, %v", pages, p, err) + } + paged = append(paged, p.Repositories...) + if q.Next = p.Next; q.Next == "" { + break + } + } + if !reflect.DeepEqual(paged, wantA) { + t.Errorf("the pages hold %+v, want %+v", paged, wantA) + } + if _, err := b.v.List(ctx, ArtifactSeat, "mesh-anyone", ListQuery{Next: "!"}); err == nil { + t.Error("a cursor no page answered was taken") + } // A manifest whose content cannot be read fails the answer: a listing without it would read as the store not holding it. delete(f.manifests, dg("m-old")) b.v.Files = &Files{Container: "mesh-registry", Run: f.run(t)} // what was read is kept: a fresh reader reads again - if _, err := b.v.List(ctx, ImageSeat, "mesh-anyone", ""); err == nil || !strings.Contains(err.Error(), "cannot be read") { + if _, err := b.v.List(ctx, ImageSeat, "mesh-anyone", ListQuery{}); err == nil || !strings.Contains(err.Error(), "cannot be read") { t.Errorf("an unreadable manifest: %v", err) } // The files' listing: a repository with slashes read, a cut or stray one refused. diff --git a/modules/distribution/internal/holder/oci.go b/modules/distribution/internal/holder/oci.go index 65abad32f..74a7d1a07 100644 --- a/modules/distribution/internal/holder/oci.go +++ b/modules/distribution/internal/holder/oci.go @@ -207,16 +207,25 @@ func (o *OCI) layerSize(t PublishRequest, parts map[string][]byte) (int64, error return resp.ContentLength, nil } -// Held is the reference of name at version when the store holds digest under it. -func (o *OCI) Held(name, version, digest string) (string, bool, error) { - d, err := o.Digest(name, version) +// Held is the reference of r's name at r's version when the store holds r's digest under it, compared like with like +// (H-A-474): an image's by the manifest's digest the version's tag names, a bundle's or an archive's by the one layer +// that manifest keeps (the blob Put stored and the reference names). When the store holds the version at another digest, +// other names that digest of the same kind. +func (o *OCI) Held(r PublishRequest) (string, string, error) { + var d string + var err error + if r.Kind == KindImage || r.Kind == KindUpstream { + d, err = o.Digest(r.Name, r.Version) + } else { + d, err = o.Blob(r.Name, r.Version) + } if err != nil || d == "" { - return "", false, err + return "", "", err } - if d != digest { - return "", false, nil + if d != r.Digest { + return "", d, nil } - return name + "@" + d, true, nil + return r.Name + "@" + d, "", nil } // Holds is whether the store holds what r's digest names under r's name: an image's manifest by its digest, or a bundle's @@ -273,6 +282,29 @@ func (o *OCI) Digest(name, version string) (string, error) { return resp.Header.Get("Docker-Content-Digest"), nil } +// Blob is the one blob the manifest name holds at version keeps (Manifest.Holder's shape): a bundle's or an archive's, +// what its reference names. Empty when none is held at version; an error naming why when the manifest keeps no single blob. +func (o *OCI) Blob(name, version string) (string, error) { + resp, b, err := o.do(http.MethodGet, "/v2/"+name+"/manifests/"+version, "", nil, mediaManifest) + if err != nil { + return "", err + } + if resp.StatusCode == http.StatusNotFound { + return "", nil + } + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("the store answered %d for %s:%s", resp.StatusCode, name, version) + } + m, err := ParseManifest(b) + if err != nil { + return "", fmt.Errorf("the manifest of %s:%s cannot be read: %w", name, version, err) + } + if !m.Holder() { + return "", fmt.Errorf("the manifest of %s:%s keeps %d layers under a %q configuration, not one blob", name, version, len(m.Layers), m.ConfigMedia) + } + return m.Layers[0], nil +} + // ErrNoTagAlone is a store that cannot delete a tag alone. registry 2.8.3, the store's pinned image, is one: its // DeleteManifest (distribution v2.8.3 registry/handlers/manifests.go) ignores a tag reference and deletes the empty // digest, whose check fails, answered 400 DIGEST_INVALID; registry 3 untags alone. diff --git a/modules/distribution/internal/holder/reserved.go b/modules/distribution/internal/holder/reserved.go index b649431d5..13e873378 100644 --- a/modules/distribution/internal/holder/reserved.go +++ b/modules/distribution/internal/holder/reserved.go @@ -3,13 +3,14 @@ package holder import ( "encoding/json" "fmt" + "strings" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds" ) // Reserved is the holder's check of a publish against the builder's reservation (novox/hq design 47 §381, §478, §504): it asks the // seat mesh-builds' verb reserved with the publish's name and version, a package's name in its ecosystem, and accepts the publish -// only when that version is the one reserved and an artifact of it has the publish's digest. It reads no catalog and a publish gains +// only when that version is the one reserved and an artifact of it has the publish's digest or none recorded yet (A-490j). It reads no catalog and a publish gains // no field. It is the Builder the holder's Check asks. type Reserved struct { // Ask is the runtime's request and reply over the bus (mesh-sdk stdio.Ask). @@ -31,12 +32,20 @@ func (r Reserved) Recorded(name, version, digest string) (bool, string, error) { return false, "", fmt.Errorf("%s answered no reservation for %s@%s: %s", Address, name, version, raw) } if a.Version != version { - return false, fmt.Sprintf("%s reserved %s for %s, not %s", a.Module, a.Version, name, version), nil + return false, fmt.Sprintf("%s has no reservation of version %s of %s (it reserved %s)", a.Module, version, name, a.Version), nil } + var reserved []string for _, art := range a.Artifacts { - if art.Digest == digest { + // An artifact whose build has not recorded its digest yet takes the publish: the builder records a build's digests only when + // the build ends, while the build module publishes during it with the reserved version (design 47 G §369, A-415, A-490j, + // H-A-387). A digest the build then records that differs from what the holder holds fails the build. + if art.Digest == digest || art.Digest == "" { return true, "", nil } + reserved = append(reserved, art.Digest) } - return false, fmt.Sprintf("%s reserved %s@%s for another digest than %s", a.Module, name, version, digest), nil + if len(reserved) == 0 { + return false, fmt.Sprintf("%s reserved %s@%s with no artifact, so no digest takes %s", a.Module, name, version, digest), nil + } + return false, fmt.Sprintf("%s reserved %s@%s for digest %s, not %s", a.Module, name, version, strings.Join(reserved, ", "), digest), nil } diff --git a/modules/distribution/internal/holder/reserved_test.go b/modules/distribution/internal/holder/reserved_test.go index faa32b074..18852f080 100644 --- a/modules/distribution/internal/holder/reserved_test.go +++ b/modules/distribution/internal/holder/reserved_test.go @@ -19,8 +19,10 @@ func reservedChecksAPublishAgainstTheReservation(t *testing.T) { }{ {name: "the reserved version and digest", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[{"artifact":"mesh-image:image","digest":"sha256:aa"}]}`, ok: true}, {name: "another artifact of it carries the digest", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[{"artifact":"mesh-image:aux"},{"artifact":"mesh-image:image","digest":"sha256:aa"}]}`, ok: true}, - {name: "another digest", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[{"artifact":"mesh-image:image","digest":"sha256:bb"}]}`, why: "another digest than sha256:aa"}, - {name: "another version reserved", answer: `{"module":"mesh-image","version":"0.1.8","artifacts":[]}`, why: "reserved 0.1.8 for registry/mesh-image, not 0.1.7"}, + {name: "no digest recorded yet", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[{"artifact":"mesh-image:image"}]}`, ok: true}, + {name: "another digest", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[{"artifact":"mesh-image:image","digest":"sha256:bb"}]}`, why: "reserved registry/mesh-image@0.1.7 for digest sha256:bb, not sha256:aa"}, + {name: "no artifact reserved", answer: `{"module":"mesh-image","version":"0.1.7","artifacts":[]}`, why: "with no artifact, so no digest takes sha256:aa"}, + {name: "another version reserved", answer: `{"module":"mesh-image","version":"0.1.8","artifacts":[]}`, why: "no reservation of version 0.1.7 of registry/mesh-image (it reserved 0.1.8)"}, {name: "the builder refused the name", err: errors.New("no entry carries registry/mesh-image"), why: "no entry carries registry/mesh-image"}, {name: "an answer that is none", answer: `{"error":"x"}`, why: "answered no reservation"}, } { diff --git a/modules/distribution/internal/holder/seats.go b/modules/distribution/internal/holder/seats.go index 3acec39c8..9e6b6a98e 100644 --- a/modules/distribution/internal/holder/seats.go +++ b/modules/distribution/internal/holder/seats.go @@ -19,9 +19,6 @@ const ( OldSeat = "mesh-artifact-store" ) -// SweepSeat is the seat of the artifact sweep, whose holder alone removes an untagged version for retention. -const SweepSeat = "mesh-artifact-sweep" - // The verbs of the seats (design 26 *A seat's definition*; design 51 *One contract*). const ( VerbPublish = "publish" @@ -29,6 +26,7 @@ const ( VerbVersions = "versions" VerbRemove = "remove" VerbMirror = "mirror" + VerbNameOf = "name-of" VerbTags = "tags" VerbHold = "hold" VerbRelease = "release" @@ -37,11 +35,11 @@ const ( // Seats are the seats distribution answers verbs on. var Seats = []string{ImageSeat, ArtifactSeat} -// VerbsOf are a seat's verbs: mirror and tags on the image seat alone; hold, release and list on both of distribution's. +// VerbsOf are a seat's verbs: mirror, name-of and tags on the image seat alone; hold, release and list on both of distribution's. func VerbsOf(seat string) []string { v := []string{VerbPublish, VerbPublishPart, VerbVersions, VerbRemove, VerbHold, VerbRelease, VerbList} if seat == ImageSeat { - v = append(v, VerbMirror, VerbTags) + v = append(v, VerbMirror, VerbNameOf, VerbTags) } sort.Strings(v) return v diff --git a/modules/distribution/internal/holder/transfer.go b/modules/distribution/internal/holder/transfer.go index 7b3bcba67..4114ae5e3 100644 --- a/modules/distribution/internal/holder/transfer.go +++ b/modules/distribution/internal/holder/transfer.go @@ -140,9 +140,11 @@ type Store interface { Has(name, digest string) (bool, error) // Put stores a publish's parts under its name and version and answers the reference's path (SeatReference). Put(r PublishRequest, parts map[string][]byte) (reference string, err error) - // Held is the reference's path of name at version when the store already holds digest under it: a rebuild of a held - // fingerprint answers it and stores nothing. - Held(name, version, digest string) (reference string, ok bool, err error) + // Held is the reference's path of a publish's name at its version when the store already holds its digest under it: a + // rebuild of a held fingerprint answers it and stores nothing. The digest is compared like with like (H-A-474): an + // image's manifest digest, a bundle's or an archive's blob digest. When the store holds the version at another digest, + // other names that digest and reference is empty; neither is set when the store holds no such version. + Held(r PublishRequest) (reference, other string, err error) // Holds says whether the store holds what a publish's digest names under its name: an image's manifest, or a bundle's or // an archive's blob. The store is the artifact store (A-50): `artifact-store:///blobs/` is that blob. Holds(r PublishRequest) (bool, error) @@ -266,15 +268,19 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer, } // A rebuild of a held fingerprint answers the held version and stores nothing. if r.Version != "" { - var ref string - var ok bool + var ref, other string err := h.timed("the store's read of what it holds (the program's registry)", func() (err error) { - ref, ok, err = h.Store.Held(r.Name, r.Version, r.Digest) + ref, other, err = h.Store.Held(r) return err }) if err != nil { return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err) - } else if ok { + } else if other != "" { + // A second publish of a held version with another digest is refused before the reservation is asked, as the forge + // holds the first (A-490j, H-A-393): while the reserved digest is still empty it would pass, and the store's Put + // would move the version's tag. + return h.refusePublish(seat, r, fmt.Sprintf("the store holds %s@%s at digest %s, not %s", r.Name, r.Version, other, r.Digest)) + } else if ref != "" { return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.timed("the published event on the seat", func() error { return h.Say(seat, EventPublished, h.eventOf(seat, r, SeatReference(seat, ref), "")) }) @@ -298,6 +304,16 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer, return answerOf(got), nil } +// refusePublish ends a publish refused before anything is stored: its finding raised, refused said on the seat, the reason +// answered. +func (h *Holder) refusePublish(seat string, r PublishRequest, reason string) (PublishAnswer, error) { + h.Finding("publish-refused", r.Name+"@"+r.Version, reason, true) + if err := h.Say(seat, EventRefused, h.eventOf(seat, r, "", reason)); err != nil { + return PublishAnswer{}, fmt.Errorf("publish: %s, and the refused is not said: %w", reason, err) + } + return PublishAnswer{Transfer: r.Transfer, Ended: true}, errors.New("publish: " + reason) +} + // tagHeld is a publish with a version, a digest and no parts (design 47 G A-417, A-73, A-50): what the store holds of that // digest under the name (the build's untagged publish, the artifact store's blob) is checked against the builder's reservation // and tagged with the version, and published is said; when the store holds none of it, the publish is refused as not stored, @@ -311,13 +327,7 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) { if err != nil { return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s of %s: %w", r.Digest, r.Name, err) } - refuse := func(reason string) (PublishAnswer, error) { - h.Finding("publish-refused", r.Name+"@"+r.Version, reason, true) - if err := h.Say(seat, EventRefused, h.eventOf(seat, r, "", reason)); err != nil { - return PublishAnswer{}, fmt.Errorf("publish: %s, and the refused is not said: %w", reason, err) - } - return PublishAnswer{Transfer: r.Transfer, Ended: true}, errors.New("publish: " + reason) - } + refuse := func(reason string) (PublishAnswer, error) { return h.refusePublish(seat, r, reason) } if !held { return refuse(fmt.Sprintf("not stored: the store holds no %s of %s, so version %s names nothing", r.Digest, r.Name, r.Version)) } @@ -397,6 +407,38 @@ func (h *Holder) DropIdle() ([]string, error) { return h.receiver().DropIdle() } // already gone. It answers whether it dropped the transfer. func (h *Holder) Expired(id string) (bool, error) { return h.receiver().Expired(id) } +// Repeat is `publish` given again with an ask id the holder already took and whose first act ended (design 47 H2 §775; +// H-A-381): it never publishes twice and keeps no answer, but answers the act's state as it stands, read afresh, which is +// what the act answers when done: a version the store holds ended, an open transfer the parts it lacks; a transfer that +// is gone, with nothing held, says the act never happened, and is refused naming it. +func (h *Holder) Repeat(seat, caller string, r PublishRequest) (PublishAnswer, error) { + if err := checkPublish(seat, r); err != nil { + return PublishAnswer{}, err + } + if r.Version != "" { + var ref string + err := h.timed("the store's read of what it holds (the program's registry)", func() (err error) { + ref, _, err = h.Store.Held(r) + return err + }) + if err != nil { + return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err) + } else if ref != "" { + return PublishAnswer{Transfer: r.Transfer, Ended: true}, nil + } + } + t, found, err := h.Transfers.Get(r.Transfer) + switch { + case err != nil: + return PublishAnswer{}, fmt.Errorf("publish: the transfer %s of a repeated ask cannot be read: %w", r.Transfer, err) + case !found: + return PublishAnswer{}, fmt.Errorf("publish: refused: the ask was taken before, and transfer %s is gone with nothing of %s held: the act did not happen", r.Transfer, r.Name) + case t.Opener != caller: + return PublishAnswer{}, fmt.Errorf("publish: refused for %s: transfer %s was opened by another caller", caller, r.Transfer) + } + return PublishAnswer{Transfer: t.ID, Missing: t.Lacks()}, nil +} + func checkPublish(seat string, r PublishRequest) error { switch { case !slices.Contains(Seats, seat): diff --git a/modules/distribution/internal/holder/verbs.go b/modules/distribution/internal/holder/verbs.go index 113697d9d..0edb6caa4 100644 --- a/modules/distribution/internal/holder/verbs.go +++ b/modules/distribution/internal/holder/verbs.go @@ -19,6 +19,9 @@ type Catalog interface { Versions(name string) ([]string, error) // Digest is the digest name holds at version, empty when none. Digest(name, version string) (string, error) + // Blob is the one blob the manifest name holds at version keeps, for a bundle or an archive: the digest its reference + // names and its published event carries. Empty when none is held; an error when the manifest keeps no single blob. + Blob(name, version string) (string, error) // Remove deletes name at version by its manifest's digest, every tag naming that digest with it; the store's // collector frees its blobs. Remove(name, version string) error @@ -85,9 +88,6 @@ type Verbs struct { Mirrors Mirrors // Files are the store's own files, which list reads (ADR 0632 §3). Files StoreFiles - // SweepHolder is the module holding the seat `mesh-artifact-sweep`, as the seat's holders say it now (design 47 G §7, §428); - // a removal for retention is that module's alone. - SweepHolder func() (string, error) } // VersionsAnswer is `versions`: the versions the seat holds of name. @@ -112,6 +112,16 @@ func (v *Verbs) Versions(seat, caller, name string) (VersionsAnswer, error) { return VersionsAnswer{Seat: seat, Name: name, Versions: got}, nil } +// VersionDigest is the digest `versions` answers for name at version on seat: the one an artifact's reference names and +// its event `published` carries (the contract's Artifact), so a node-engine fetches the bytes by it (design 47 G A-430a): +// on the artifact seat a bundle's or an archive's blob, on the image seat the image's manifest. Empty when none is held. +func (v *Verbs) VersionDigest(seat, name, version string) (string, error) { + if seat == ArtifactSeat { + return v.Catalog.Blob(name, version) + } + return v.Catalog.Digest(name, version) +} + // RemoveRequest is `remove`: a tagged version, or with the reason retention an untagged one by its digest. type RemoveRequest struct { Name string `json:"name"` @@ -137,7 +147,7 @@ type Removal struct { const ReasonSharedDigest = reg.RemoveAnswerReasonSharedDigest // Remove is `remove`: the builder removes a tagged version; the artifact sweep's holder an untagged bundle, archive or -// copied base with the reason retention, which a hold keeps. Every removal says `removed` with its reason. +// copied base with the reason retention, which a hold keeps, its caller not judged (design 47 H2 §813 (7)). Every removal says `removed` with its reason. func (v *Verbs) Remove(seat, caller string, r RemoveRequest) (Removal, error) { if strings.TrimSpace(r.Name) == "" || strings.TrimSpace(r.Reason) == "" { return Removal{}, errors.New("remove: a name and a reason are required") @@ -145,13 +155,8 @@ func (v *Verbs) Remove(seat, caller string, r RemoveRequest) (Removal, error) { ev := Event{Name: r.Name, Version: r.Version, Kind: r.Kind, Digest: r.Digest, Holder: Self, Reason: r.Reason, By: caller} switch { case r.Reason == ReasonRetention: - sweep, err := v.SweepHolder() - if err != nil { - return Removal{}, fmt.Errorf("remove: the holder of %s cannot be read, so nothing is removed for retention: %w", SweepSeat, err) - } - if CallerModule(caller) != sweep { - return Removal{}, fmt.Errorf("remove: refused for %s: a removal for retention is the artifact sweep's alone", caller) - } + // The removal for retention the holder of mesh-artifact-sweep asks; its caller is not judged, as every account may call + // every verb (design 47 H2 §813 (7)). if r.Digest == "" { return Removal{}, errors.New("remove: a removal for retention names the digest") } @@ -328,6 +333,25 @@ func (v *Verbs) Mirror(seat, caller string, r MirrorRequest) (string, error) { return SeatReference(seat, v.Catalog.Reference(src.Name(), r.Digest)), nil } +// NameOf is `name-of` on the image seat (design 47 H2 H-A-513): the reference mirror answers, and keeps the copy under, for an +// outside image as a manifest's from names it, pinned ([:]@sha256:): the holder's own name for the copy, +// upstream//, with that digest, in the seat's form. It reads only and asks no copy; a from that pins no digest is +// refused, as mirror refuses it. +func (v *Verbs) NameOf(seat, from string) (string, error) { + if seat != ImageSeat { + return "", fmt.Errorf("name-of: %s serves no name-of", seat) + } + _, digest, pinned := strings.Cut(strings.TrimSpace(from), "@") + if !pinned || !strings.HasPrefix(digest, "sha256:") || len(digest) != len("sha256:")+64 { + return "", fmt.Errorf("name-of: refused: %q pins no digest, and an upstream image is named only by its pinned digest", from) + } + src, err := ParseSource(from) + if err != nil { + return "", err + } + return SeatReference(seat, v.Catalog.Reference(src.Name(), digest)), nil +} + // Mirrored runs one asked copy and says its outcome on the image seat's events: published with the reference, or // refused with the reason; the ask leaves the state either way. An outcome that cannot be said keeps the ask, so the // next watch takes it on again. diff --git a/modules/distribution/module.json b/modules/distribution/module.json index 0aca09da3..54d97d94d 100644 --- a/modules/distribution/module.json +++ b/modules/distribution/module.json @@ -1,6 +1,7 @@ { "module": "distribution", "version": "0.1", + "class": "core", "provides": [ { "name": "artifact-store", @@ -23,6 +24,7 @@ "hold", "list", "mirror", + "name-of", "publish", "publish-part", "release", @@ -249,14 +251,44 @@ } ], "state": [ - "transfers", + { + "name": "transfers", + "max-mib": 8 + }, { "name": "idle", - "key-ttl": true + "key-ttl": true, + "max-mib": 8 }, - "holds", - "windows", - "mirrors", - "findings" - ] + { + "name": "holds", + "max-mib": 8 + }, + { + "name": "windows", + "max-mib": 8 + }, + { + "name": "mirrors", + "max-mib": 8 + }, + { + "name": "findings", + "max-mib": 8 + }, + { + "name": "taken", + "key-ttl": true, + "max-mib": 8 + } + ], + "config": { + "ask-taken-bound": { + "type": "string", + "description": "How long the registry keeps the id of a publish ask it took, as a duration such as 10m (design 47 H2 §775): a publish given again with that id within it acts not again but answers the transfer as it stands. The largest caller's bound, the pipeline runner's ask-unanswered-bound, by default.", + "trusted": false, + "runtime": true, + "default": "10m" + } + } } diff --git a/modules/dmenu/module.json b/modules/dmenu/module.json index 61986d1e2..71d0c4172 100644 --- a/modules/dmenu/module.json +++ b/modules/dmenu/module.json @@ -1,6 +1,7 @@ { "module": "dmenu", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/dnsmasq/module.json b/modules/dnsmasq/module.json index 2318baa09..8516bb620 100644 --- a/modules/dnsmasq/module.json +++ b/modules/dnsmasq/module.json @@ -1,6 +1,7 @@ { "module": "dnsmasq", "version": "0.1", + "class": "core", "upgrade": { "policy": "record", "why": "the mesh's resolver: a build that breaks it can stop a machine resolving the bus, and then neither the gate's rollback nor a push reaches it (hq ADR 0236, issue 260)" diff --git a/modules/docker-compose/module.json b/modules/docker-compose/module.json index 7ace4b8ce..92caf5835 100644 --- a/modules/docker-compose/module.json +++ b/modules/docker-compose/module.json @@ -1,6 +1,7 @@ { "module": "docker-compose", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/docker/module.json b/modules/docker/module.json index a51d21c9d..c4be0284b 100644 --- a/modules/docker/module.json +++ b/modules/docker/module.json @@ -1,6 +1,7 @@ { "module": "docker", "version": "0.1", + "class": "core", "capabilities": [ "package-manager", "service-manager", diff --git a/modules/dunst/cmd/dunst-tools/manifest_helpers_test.go b/modules/dunst/cmd/dunst-tools/manifest_helpers_test.go index 2959a8b63..6ed0e52eb 100644 --- a/modules/dunst/cmd/dunst-tools/manifest_helpers_test.go +++ b/modules/dunst/cmd/dunst-tools/manifest_helpers_test.go @@ -1,85 +1,15 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Config map[string]config `json:"config"` - Emits []string `json:"emits"` - Items []item `json:"items"` - Contributions []any `json:"contributions"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -// config is one config value as the definition declares it (novox/hq ADR 0348 §4). -type config struct { - Type string `json:"type"` - Description string `json:"description"` - Enum []any `json:"enum"` - Minimum *float64 `json:"minimum"` - Maximum *float64 `json:"maximum"` - Pattern string `json:"pattern"` - Trusted bool `json:"trusted"` - Predefined string `json:"predefined"` - Default any `json:"default"` - Required bool `json:"required"` - Runtime bool `json:"runtime"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -90,7 +20,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -106,9 +36,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -128,7 +58,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -137,10 +67,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -150,9 +80,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -165,7 +95,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -207,14 +137,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } @@ -239,7 +169,7 @@ const displaySession = "contribution:node-display-session:config" // i3Lines is what the module contributes to the window manager: the text of its item of the collection // contribution:node-display-session:config (design 57 L3, issue 848). -func (m manifest) i3Lines() string { +func i3Lines(m catalogue.Manifest) string { var out string for _, it := range m.Items { if it.Collection == displaySession { @@ -255,7 +185,7 @@ func (m manifest) i3Lines() string { // i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no // old-form contribution to node-display-session is left. -func (m manifest) i3LinesAreSource(t *testing.T, source string) { +func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) { t.Helper() if len(m.Contributions) != 0 { t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession) @@ -269,14 +199,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) { if len(templates) != 1 || templates[0] != source { t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source) } - if m.i3Lines() == "" { + if i3Lines(m) == "" { t.Fatalf("the template %s holds no line", source) } } - -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} diff --git a/modules/dunst/cmd/dunst-tools/manifest_test.go b/modules/dunst/cmd/dunst-tools/manifest_test.go index 3f56b5fd8..6a785622e 100644 --- a/modules/dunst/cmd/dunst-tools/manifest_test.go +++ b/modules/dunst/cmd/dunst-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // dunst's shape (novox/hq ADR 0208): it claims node-notifier serving send and history, owns its @@ -12,28 +16,44 @@ import ( // activation, so it requires no display of its own. func TestItClaimsTheNotifierSeatServingSendAndHistory(t *testing.T) { - m := readManifest(t) - if m.Module != "dunst" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "dunst" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) { t.Fatalf("claims: %+v", m.Claims) } // rofi, the context menu the dunstrc calls by name, is the rofi module's package: two modules on one // machine may not declare the same package, and the rofi module holds node-launcher on every // machine dunst serves. - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) { - m := readManifest(t) - m.fromTemplate(t, "configuration", "files/dunstrc") - if p := m.resource(t, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + fromTemplate(t, m, "configuration", "files/dunstrc") + if p := resource(t, m, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" { t.Fatalf("path: %v", p) } - if d := m.resource(t, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" { + if d := resource(t, m, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" { t.Fatalf("drop-ins: %v", d) } for _, r := range m.Resources { @@ -44,8 +64,16 @@ func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) { } func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) { - m := readManifest(t) - c := m.text(t, "configuration") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + c := templateText(t, m, "configuration") for _, want := range []string{"origin = top-right", "transparency = 0", "corner_radius = 0", "font = Inter ${config:font-size}", "width = ${config:width}", "dmenu = rofi -dmenu -no-custom -p dunst"} { if !strings.Contains(c, " "+want+"\n") { @@ -66,8 +94,16 @@ func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) { // of them (dunst holds it open until the menu answers, and an Escape leaves it shown), and one without // actions closes. Every other click is as it was. func TestATapChoosesTheNotificationsAction(t *testing.T) { - m := readManifest(t) - c := m.text(t, "configuration") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + c := templateText(t, m, "configuration") for _, want := range []string{"mouse_left_click = do_action, close_current", "mouse_middle_click = do_action, close_current", "mouse_right_click = close_all"} { if !strings.Contains(c, " "+want+"\n") { @@ -82,9 +118,17 @@ func TestATapChoosesTheNotificationsAction(t *testing.T) { // The key that chooses from the keyboard is a line i3 places from this contribution (novox/hq ADR // 0212): a binding only, never a start, so the bus stays the only thing that starts dunst. func TestTheMenuKeyIsABindingI3Places(t *testing.T) { - m := readManifest(t) - m.i3LinesAreSource(t, "files/i3/50-dunst.conf") - lines := m.i3Lines() + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + i3LinesAreSource(t, m, "files/i3/50-dunst.conf") + lines := i3Lines(m) if !strings.Contains(lines, "bindsym $mod+n exec --no-startup-id dunstctl context\n") { t.Fatalf("no key for the context menu: %s", lines) } @@ -100,23 +144,31 @@ func TestTheMenuKeyIsABindingI3Places(t *testing.T) { // predefined font-size (ADR 0348 §2), so a machine with a denser screen sets its own and every other // machine's file is unchanged. Neither is trusted: the file says "trusted": false. func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } want := map[string]float64{"font-size": 10, "width": 250} - if len(m.Config) != len(want) { - t.Fatalf("config: %+v", m.Config) + if len(m.Settings) != len(want) { + t.Fatalf("config: %+v", m.Settings) } for key, value := range want { - s, ok := m.Config[key] + s, ok := m.Settings[key] if !ok || s.Type != "number" || s.Default != value || s.Required || s.Trusted || strings.TrimSpace(s.Description) == "" || s.Minimum == nil || s.Maximum == nil { t.Errorf("%s: %+v, want an untrusted number defaulting to %v, with a description and bounds", key, s, value) } } - if p := m.Config["font-size"].Predefined; p != "font-size" { + if p := m.Settings["font-size"].Predefined; p != "font-size" { t.Errorf("the font size falls back to %q, want the predefined font-size", p) } // Filled with the defaults, the file is the one every machine had before it took config values. - c := m.text(t, "configuration") + c := templateText(t, m, "configuration") c = strings.ReplaceAll(c, "${config:font-size}", "10") c = strings.ReplaceAll(c, "${config:width}", "250") for _, want := range []string{"font = Inter 10", "width = 250"} { @@ -130,7 +182,15 @@ func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) { } func TestNothingStartsItButTheBus(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } if m.Shell != nil { t.Fatalf("a session start: %+v", m.Shell) } @@ -147,25 +207,50 @@ func TestNothingStartsItButTheBus(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } // dunst moves first (design 57 P6, issue 672): marked moved, its dunstrc is filled on the node by the provisioner's // client from its template, and reloaded as the file declares. func TestItIsHandedToTheProvisioner(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } if !m.Moved { t.Fatal("dunst is not marked moved") } - m.fromTemplate(t, "configuration", "files/dunstrc") - if on := m.resource(t, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) { + fromTemplate(t, m, "configuration", "files/dunstrc") + if on := resource(t, m, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) { t.Fatalf("the notifier is not reloaded on its dunstrc: %v", on) } } diff --git a/modules/dunst/cmd/dunst-tools/reload_test.go b/modules/dunst/cmd/dunst-tools/reload_test.go index dc31bb571..54fa01889 100644 --- a/modules/dunst/cmd/dunst-tools/reload_test.go +++ b/modules/dunst/cmd/dunst-tools/reload_test.go @@ -6,6 +6,8 @@ import ( "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // The running dunst reads its file again when the file changes (novox/hq ADR 0262: a setting the @@ -83,8 +85,16 @@ func TestAReloadDunstRefusesIsAFailure(t *testing.T) { } func TestTheRunningDunstIsReloadedWhenItsFileChanges(t *testing.T) { - m := readManifest(t) - s := m.resource(t, "notifier") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + s := resource(t, m, "notifier") want := map[string]any{ "id": "notifier", "type": "service", "unit": "dunst.service", "scope": "user", "user": "${machine:account}", diff --git a/modules/dunst/module.json b/modules/dunst/module.json index 7321e05e7..7821e3f9d 100644 --- a/modules/dunst/module.json +++ b/modules/dunst/module.json @@ -1,6 +1,7 @@ { "module": "dunst", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/fail2ban/module.json b/modules/fail2ban/module.json index 7e5008ab3..1fe831870 100644 --- a/modules/fail2ban/module.json +++ b/modules/fail2ban/module.json @@ -1,6 +1,7 @@ { "module": "fail2ban", "version": "0.1", + "class": "core", "capabilities": [ "firewall" ], diff --git a/modules/feh/cmd/feh-tools/main.go b/modules/feh/cmd/feh-tools/main.go index 3a42f8ef5..fd4a550e5 100644 --- a/modules/feh/cmd/feh-tools/main.go +++ b/modules/feh/cmd/feh-tools/main.go @@ -1,5 +1,6 @@ // feh's Go tools bundle (novox/hq ADR 0188, ADR 0193, ADR 0208): the wallpaper's tools, served by the // node's runtime as the operator account. +// Design 47 H1, proof 1: this comment is the single-module change its pipeline delivers. package main import ( diff --git a/modules/feh/cmd/feh-tools/manifest_helpers_test.go b/modules/feh/cmd/feh-tools/manifest_helpers_test.go index 28adb6607..740a42250 100644 --- a/modules/feh/cmd/feh-tools/manifest_helpers_test.go +++ b/modules/feh/cmd/feh-tools/manifest_helpers_test.go @@ -1,66 +1,19 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Items []item `json:"items"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - // Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here. - Contributions []any `json:"contributions"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest. -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} - // shell is the code the module adds to a shell's or the session's start, read from the templates of its items of // the collections shell::, in the order they are declared. -func (m manifest) shell(t *testing.T) []shellCode { +func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode { t.Helper() - var out []shellCode + var out []catalogue.ShellCode for _, it := range m.Items { parts := strings.Split(it.Collection, ":") if len(parts) != 3 || parts[0] != "shell" { @@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode { if err != nil { t.Fatal(err) } - out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)}) + out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)}) } return out } // environmentOf is the variables the module sets, read from the templates of its items of the environment. -func (m manifest) environmentOf(t *testing.T) *environment { +func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment { t.Helper() - var env *environment + var env *catalogue.Environment for _, it := range m.Items { if it.Collection != "environment" || it.Attributes["kind"] != "variable" { continue @@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment { t.Fatal(err) } if env == nil { - env = &environment{Variables: map[string]string{}} + env = &catalogue.Environment{Variables: map[string]string{}} } env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n") } return env } -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - m.Environment = m.environmentOf(t) - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } @@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config" // i3Lines is what the module contributes to the window manager: the text of its item of the collection // contribution:node-display-session:config (design 57 L3, issue 848). -func (m manifest) i3Lines() string { +func i3Lines(m catalogue.Manifest) string { var out string for _, it := range m.Items { if it.Collection == displaySession { @@ -287,7 +224,7 @@ func (m manifest) i3Lines() string { // i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no // old-form contribution to node-display-session is left. -func (m manifest) i3LinesAreSource(t *testing.T, source string) { +func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) { t.Helper() if len(m.Contributions) != 0 { t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession) @@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) { if len(templates) != 1 || templates[0] != source { t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source) } - if m.i3Lines() == "" { + if i3Lines(m) == "" { t.Fatalf("the template %s holds no line", source) } } diff --git a/modules/feh/cmd/feh-tools/manifest_test.go b/modules/feh/cmd/feh-tools/manifest_test.go index 0dc0de863..fa64fc88a 100644 --- a/modules/feh/cmd/feh-tools/manifest_test.go +++ b/modules/feh/cmd/feh-tools/manifest_test.go @@ -6,6 +6,8 @@ import ( "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // feh's shape (novox/hq ADR 0208): no seat; it requires the X display on its own machine, carries @@ -13,27 +15,43 @@ import ( // the session's start. func TestItRequiresTheXDisplayAndClaimsNothing(t *testing.T) { - m := readManifest(t) - if m.Module != "feh" || m.Seats != nil || m.Claims != nil { - t.Fatalf("module %q, seats %v, claims %v", m.Module, m.Seats, m.Claims) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "feh" || m.DefinesSeats != nil || m.Claims != nil { + t.Fatalf("module %q, seats %v, claims %v", m.Module, m.DefinesSeats, m.Claims) } if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("requires: %v", m.Requires) } - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) { - m := readManifest(t) - a := m.resource(t, "wallpapers") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + a := resource(t, m, "wallpapers") if a["type"] != "archive" || a["artifact"] != "wallpapers" || a["path"] != "${machine:account-home}/.local/share/feh/wallpapers" || a["owner"] != "${machine:account}" { t.Fatalf("%v", a) } found := false for _, art := range m.Build.Artifacts { - if art["name"] == "wallpapers" && art["kind"] == "archive" && art["from"] == "wallpaper" { + if art.Name == "wallpapers" && art.Kind == "archive" && art.From == "wallpaper" { found = true } } @@ -47,38 +65,71 @@ func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) { } func TestFehbgIsOwnedAndTheSessionStartRunsItOnce(t *testing.T) { - m := readManifest(t) - m.fromTemplate(t, "fehbg", "files/fehbg") - f := m.resource(t, "fehbg") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + fromTemplate(t, m, "fehbg", "files/fehbg") + f := resource(t, m, "fehbg") if f["path"] != "${machine:account-home}/.fehbg" || f["mode"] != "0755" { t.Fatalf("%v", f) } - if c := m.text(t, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") { + if c := templateText(t, m, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") { t.Fatalf("%s", c) } - if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" || strings.Count(m.shell(t)[0].Code, `"$HOME/.fehbg"`) != 1 { - t.Fatalf("%+v", m.shell(t)) + if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" || strings.Count(shell(t, m)[0].Code, `"$HOME/.fehbg"`) != 1 { + t.Fatalf("%+v", shell(t, m)) } } func TestTheKeyThatRestoresTheWallpaperIsAnI3DropIn(t *testing.T) { - m := readManifest(t) - m.i3LinesAreSource(t, "files/i3/50-feh.conf") - if p := m.i3Lines(); p == "" { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + i3LinesAreSource(t, m, "files/i3/50-feh.conf") + if p := i3Lines(m); p == "" { t.Fatalf("path: %v", p) } - if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") { + if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") { t.Fatalf("%s", c) } } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/feh/files/fehbg b/modules/feh/files/fehbg index 2ea58adcf..a78c8b9cf 100755 --- a/modules/feh/files/fehbg +++ b/modules/feh/files/fehbg @@ -2,5 +2,5 @@ # The wallpaper (module feh, novox/hq ADR 0208). Owned by the mesh: replaced at every delivery. The # session's start runs it, and so may anything that wants the declared wallpaper back. The image is # the module's own, in ~/.local/share/feh/wallpapers. feh_set changes the wallpaper for a session -# without touching this file (the second single-module proof, 2026-11-17). +# without touching this file (design 47 H1, proof 1 (second run): delivered by its pipeline, 2026-11-21). feh --no-fehbg --bg-fill "$HOME/.local/share/feh/wallpapers/default.jpg" diff --git a/modules/feh/module.json b/modules/feh/module.json index 14de69d04..49dada45b 100644 --- a/modules/feh/module.json +++ b/modules/feh/module.json @@ -1,6 +1,7 @@ { "module": "feh", "version": "0.1", + "class": "leaf", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/flatpak/module.json b/modules/flatpak/module.json index d7fc53c52..da3d6ae04 100644 --- a/modules/flatpak/module.json +++ b/modules/flatpak/module.json @@ -1,6 +1,7 @@ { "module": "flatpak", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/fonts/module.json b/modules/fonts/module.json index cac0dc2d9..14b7463c2 100644 --- a/modules/fonts/module.json +++ b/modules/fonts/module.json @@ -1,6 +1,7 @@ { "module": "fonts", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/forticlient/cmd/forticlient-tools/manifest_test.go b/modules/forticlient/cmd/forticlient-tools/manifest_test.go index 55060939c..4ae55c25e 100644 --- a/modules/forticlient/cmd/forticlient-tools/manifest_test.go +++ b/modules/forticlient/cmd/forticlient-tools/manifest_test.go @@ -1,12 +1,13 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // forticlient's shape (novox/hq ADR 0205, ADR 0207, ADR 0208): no package (the client is outside the @@ -15,48 +16,17 @@ import ( // start), nothing of the VPN's configuration, and the Go bundle serving exactly the listed forticlient_ // tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Upgrade struct { - Policy string `json:"policy"` - Why string `json:"why"` - } `json:"upgrade"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Contributions []struct { - Seat string `json:"seat"` - Kind string `json:"kind"` - Content string `json:"content"` - } `json:"contributions"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestTheToolsAgreeWithTheManifest(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -77,8 +47,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/forticlient-tools" || b["binary"] != "forticlient-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/forticlient-tools" || b.Binary != "forticlient-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) @@ -90,7 +60,16 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { } func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) // split-dns (novox/hq ADR 0247): the machine's own resolver, which its adapter hands the client's // resolver file to. Required at the machine's reach, so the module is assigned only beside one. if m.Module != "forticlient" || !reflect.DeepEqual(m.Requires, []string{"x11-display", "split-dns"}) || @@ -110,7 +89,7 @@ func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) { if m.Upgrade.Policy != "record" || m.Upgrade.Why == "" { t.Error("a build of what routes the person's work names rolls out on its own") } - if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { t.Fatal("no seat, no environment, and no second start") } for _, never := range []string{"/etc/forticlient", "/opt/forticlient", "autostart", "\"package\"", "vpn.", "gateway", "profile"} { diff --git a/modules/forticlient/module.json b/modules/forticlient/module.json index 24ce2f444..c849b0fe4 100644 --- a/modules/forticlient/module.json +++ b/modules/forticlient/module.json @@ -1,6 +1,7 @@ { "module": "forticlient", "version": "0.1", + "class": "leaf", "upgrade": { "policy": "record", "why": "its adapter routes the company's domains on the machine a person works on: a build that breaks it cuts the person off from work names until a person pushes the next (hq ADR 0236, ADR 0247)" diff --git a/modules/gitea/README.md b/modules/gitea/README.md index c946a02b0..321c54e1f 100644 --- a/modules/gitea/README.md +++ b/modules/gitea/README.md @@ -100,7 +100,8 @@ search that reaches the call's deadline stops there and answers what it found, w It reaches the forge through the same HTTP client as the package-registry bundle (`internal/forgehttp`), as the tools' own account (novox/hq ADR 0365 §2, issue 469): the token the TypeScript bundle mints for `mesh-tools` and -keeps (`MESH_GITEA_TOKEN_FILE`), sent only when its scopes line names that account, never the admin login. One tool +keeps in the vault as the module's own (`module/gitea/mesh-tools`, design 47 H2 §808), read through the vault seat's +`get` at start and at each `secret-changed` naming it, never the admin login. One tool call takes at most 50 seconds. `go test ./cmd/forge` runs it against a fake forge: the files of one commit created, updated and deleted on a new branch from its base; an existing branch committed on; the default branch, a protected branch and @@ -247,9 +248,10 @@ version already gone counts as deleted. Over the forge's HTTP interface on the machine (`MESH_GITEA_URL`), never as the admin account (design 51: each holder keeps its write side as an own secret beside a read-only tool token). It **reads** as the tools' account, -with the token the TypeScript bundle keeps for it (`MESH_GITEA_TOKEN_FILE`, scopes including `read:package`), and -**writes** (a publish, a remove, retention's deletion) as the packages account `mesh-packages` -(`MESH_GITEA_PACKAGES_USER`), with its own token (`MESH_GITEA_PACKAGES_TOKEN_FILE`, the one scope `write:package`). +with the token the TypeScript bundle keeps for it in the vault (`module/gitea/mesh-tools`, scopes including +`read:package`), and **writes** (a publish, a remove, retention's deletion) as the packages account `mesh-packages` +(`MESH_GITEA_PACKAGES_USER`), with its own token (`module/gitea/mesh-packages`, the one scope `write:package`), both +read through the vault seat's `get` at start and at each `secret-changed` (design 47 H2 §808). That account is plain, a member of the team `mesh-packages` that writes the organisation's packages and nothing else; the watcher makes it with the administrator's login and mints and keeps its token at its start (`packages-account.ts`). No timer looks at it after that: when the forge refuses a write (401) this bundle raises the finding diff --git a/modules/gitea/calls.ts b/modules/gitea/calls.ts new file mode 100644 index 000000000..d4b4e40c9 --- /dev/null +++ b/modules/gitea/calls.ts @@ -0,0 +1,113 @@ +// **The call is written before its first merge** (novox/hq design 47 H §766; H-A-18, H-A-47, H-A-71): before it merges +// anything, the forge module writes the call's key `call.` in its own template state `calls` (the seat git's +// definition declares it): `by`, the bus account the tool runner proved, `at`, the members, each with its base `branch` +// and `state` judged, merged with its commit, or refused with why, and `said`, whether its `merge-called` was said. Each +// member is updated as it merges. A call is kept `call-retention` (a setting, default 30 days), then deleted by the forge +// module on each new call's write, oldest first, with no timer (H-A-47). + +import { readFileSync } from "node:fs"; +import type { State } from "@novox/mesh-sdk/state"; +import { + callsByCallCallKey, mergeCalledSubject, parseCallsByCallCallKey, type Call, type CallMember, type MergeCalledEvent, +} from "@novox/mesh-delivery-contracts-git"; + +/** call-retention's default, in days (§766). */ +export const CALL_RETENTION_DAYS = 30; + +/** call-retention as the module's config file says it, in days; the default when it says none (mainrules.ts' form). */ +export function callRetentionDays(env: NodeJS.ProcessEnv = process.env): number { + const file = env.MESH_GITEA_CONFIG_FILE; + if (!file) return CALL_RETENTION_DAYS; + try { + const v = Number((JSON.parse(readFileSync(file, "utf8")) as Record)["call-retention"]); + return Number.isInteger(v) && v >= 1 ? v : CALL_RETENTION_DAYS; + } catch { return CALL_RETENTION_DAYS; } +} + +/** One kept call with its id. */ +export interface KeptCall extends Call { + call: string; +} + +/** The state `calls`: one key per merge call. */ +export class Calls { + constructor(private readonly st: State, private readonly retentionDays: () => number = () => CALL_RETENTION_DAYS, + private readonly log: (line: string) => void = () => {}) {} + + /** Every call kept, newest first. */ + async all(): Promise { + const out: KeptCall[] = []; + for (const key of await this.st.keys()) { + const parsed = parseCallsByCallCallKey(key); + if (!parsed) continue; + const e = await this.st.get(key); + if (e?.value) out.push({ ...(e.value as Call), call: parsed.call }); + } + return out.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.call < b.call ? 1 : -1)); + } + + /** One call, or undefined. */ + async get(call: string): Promise { + const e = await this.st.get(callsByCallCallKey(call)); + return e?.value ? { ...(e.value as Call), call } : undefined; + } + + /** Writes a call. A new call (none kept under its key) first deletes the calls past call-retention, oldest first. */ + async put(call: string, value: Call, now: Date = new Date()): Promise { + if (!(await this.st.get(callsByCallCallKey(call)))?.value) await this.expire(now); + await this.st.put(callsByCallCallKey(call), value); + } + + /** Deletes the calls whose `at` is past call-retention before now, oldest first; answers the calls deleted. */ + async expire(now: Date): Promise { + const before = now.getTime() - this.retentionDays() * 86_400_000; + const old = (await this.all()).filter((c) => (Date.parse(c.at) || 0) < before).reverse(); + for (const c of old) await this.st.delete(callsByCallCallKey(c.call)); + if (old.length) this.log(`${old.length} merge calls past ${this.retentionDays()} days deleted: ${old.map((c) => c.call).join(", ")}`); + return old.map((c) => c.call); + } +} + +/** A kept member of a call. */ +export const keptMember = (m: { repository: string; number: number; branch: string; head: string; state: CallMember["state"]; + commit?: string; why?: string; note?: string }): CallMember => ({ repository: m.repository, number: m.number, branch: m.branch, + head: m.head, state: m.state, ...(m.commit ? { commit: m.commit } : {}), ...(m.why ? { why: m.why } : {}), + ...(m.note ? { note: m.note } : {}) }); + +/** Says a seat event on its subject, under an id the bus keeps once. */ +export type Say = (subject: string, body: unknown, id?: string) => Promise; + +/** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its + * refused ones; undefined for a call that landed no member, which says none. A member merged plainly, carrying the note + * no delivery (its repository has no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */ +export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined { + const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note); + if (landed.length === 0) return undefined; + // A member judged and not merged (a stop mid-call) is in neither: its head is an untaken head (§740). + const refused = c.members.filter((m) => m.state === "refused"); + return { call: c.call, by: c.by, account: c.account, at: c.at, + members: landed.map((m) => ({ repository: m.repository, number: m.number, branch: m.branch, head: m.head, commit: m.commit! })), + ...(refused.length ? { refused: refused.map((m) => ({ repository: m.repository, number: m.number, why: m.why ?? "not merged" })) } : {}) }; +} + +/** Says a call's merge-called, when it landed a member; answers whether it said one. */ +export async function sayCall(c: KeptCall, say: Say): Promise { + const body = mergeCalledOf(c); + if (!body) return false; + await say(mergeCalledSubject(c.call), body, `merge-called.${c.call}`); + return true; +} + +/** At the start (§766): every call whose event is not said says merge-called for what landed, and is kept said, so a stop + * between the last merge and the event loses nothing it recorded. Answers the calls said. */ +export async function sayUnsaid(calls: Calls, say: Say, log: (line: string) => void = () => {}): Promise { + const said: string[] = []; + for (const c of await calls.all()) { + if (c.said) continue; + if (await sayCall(c, say)) said.push(c.call); + const { call, ...value } = c; + await calls.put(call, { ...value, said: true }); + } + if (said.length) log(`merge-called said again at the start for ${said.join(", ")}`); + return said; +} diff --git a/modules/gitea/client.ts b/modules/gitea/client.ts index 7720ff58d..54c39d5d4 100644 --- a/modules/gitea/client.ts +++ b/modules/gitea/client.ts @@ -182,7 +182,19 @@ export const FORGE_REQUEST_TIMEOUT_MS = 20_000; /** The most a tool's answer carries of one file: the bus's message bound is 1 MiB and a file travels as text (issue 1577). */ export const MAX_FILE_BYTES = 512 * 1024; +/** A directory of a listing's `files` the commit does not hold: the seat git answers it with the kind not-found, the error + * naming the directory (seat.ts failure; novox/hq design 47 H H-A-232). */ +export class DirectoryNotInTree extends Error { + constructor(message: string) { + super(message); + this.name = "DirectoryNotInTree"; + } +} + /** One request to the forge, cut at the limit and failing loud naming the request. */ +/** What a forge's answer says when its store does not answer (design 47 H2 §776). */ +const STORE_UNAVAILABLE = /database|\bdb\b|store/i; + async function timedFetch(url: string, init: RequestInit, label: string, timeoutMs: number): Promise { try { return await fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) }); @@ -267,6 +279,28 @@ export class GiteaClient { return this.request(path, options); } + /** + * The forge's own version read, unauthenticated (GET /api/v1/version): whether the forge answers at all, and whether + * it names its store unavailable (design 47 H2 §776). What the seat git reads before it says a 401, a 502, a 503 or a + * connection fault is the forge's refusal or the forge away; never throws. + */ + async forgeVersion(): Promise<{ ok: true; version: string } | { ok: false; words: string; store: boolean }> { + const label = "GET /version"; + try { + const res = await timedFetch(`${this.baseUrl}/api/v1/version`, { headers: { Accept: "application/json" } }, label, this.requestTimeoutMs); + const text = await res.text(); + const store = STORE_UNAVAILABLE.test(text); + if (!res.ok) return { ok: false, words: `the forge's version read answered ${res.status} ${text}`.trim(), store }; + let version = ""; + try { version = String(JSON.parse(text)?.version ?? ""); } catch { /* no version said */ } + if (store) return { ok: false, words: `the forge's version read names its store unavailable: ${text}`, store }; + if (!version) return { ok: false, words: `the forge's version read named no version: ${text}`, store }; + return { ok: true, version }; + } catch (err) { + return { ok: false, words: `the forge's version read: ${err instanceof Error ? err.message : String(err)}`, store: false }; + } + } + // ---- Repositories ---- /** Every repository this token can see, one page. `/user/repos` is only what the token's own @@ -490,11 +524,17 @@ export class GiteaClient { } /** One page of a repository's tags, newest first, by name: what the seat git's `tags` answers. */ - async tags(owner: string, repo: string, page: number, limit: number): Promise { + async tags(owner: string, repo: string, page: number, limit: number): Promise<{ tag: string; commit: string }[]> { if (!Number.isInteger(page) || page < 1) throw new Error(`${page} is not a page, from 1`); const list = await this.request(`${repoPath(owner, repo)}/tags?page=${page}&limit=${limit}`); if (!Array.isArray(list)) throw new Error(`the forge answered no list of the tags of ${owner}/${repo}`); - return list.map((t) => String(t?.name ?? "")).filter((n) => n !== ""); + // Each tag with the commit it names (design 47 H2 §796): a tag the forge names no commit for is no answer, never a + // tag without its commit. + return list.filter((t) => String(t?.name ?? "") !== "").map((t) => { + const tag = String(t.name), commit = String(t?.commit?.sha ?? ""); + if (!/^[0-9a-f]{40}$/.test(commit)) throw new Error(`the forge named no commit for ${owner}/${repo}'s tag ${tag}`); + return { tag, commit }; + }); } /** The commit a tag names, or null when the repository has no such tag (the forge's 404 only). */ @@ -634,7 +674,7 @@ export class GiteaClient { // is whole (a cut one failed above), so a directory absent from it is absent at the commit. filesOf = {}; for (const dir of files) { - if (dir !== "" && dirOf.get(dir) === undefined) throw new Error(`the directory ${dir} is not in ${owner}/${repo} at ${sha}`); + if (dir !== "" && dirOf.get(dir) === undefined) throw new DirectoryNotInTree(`the directory ${dir} is not in ${owner}/${repo} at ${sha}`); const prefix = dir === "" ? "" : `${dir}/`; const blobs: Record = {}; for (const e of entries) { diff --git a/modules/gitea/cmd/forge/account_test.go b/modules/gitea/cmd/forge/account_test.go index d37c6594d..f0995aa60 100644 --- a/modules/gitea/cmd/forge/account_test.go +++ b/modules/gitea/cmd/forge/account_test.go @@ -1,35 +1,54 @@ package main // The commit and the reads act as the tools' own account (novox/hq ADR 0365 §2, issue 469): the token the module -// keeps for `mesh-tools`, never the admin login. That account is no repository's administrator, so the forge +// keeps for `mesh-tools` in the vault (design 47 H2 §808), never the admin login. That account is no repository's administrator, so the forge // refuses it the protection rules (403, as gitea's reqAdmin does); the commit then judges an existing branch by the // protection the forge says it applies, and leaves a branch not made yet to the forge's own judgement. import ( "context" + "encoding/json" + "fmt" "net/http" "net/http/httptest" - "os" - "path/filepath" "strings" "testing" + "git.novox.be/novox/mesh-sdk/go/seal" + "gitea/internal/forgehttp" ) const toolsToken = "tools-token-never-shown" -// asTools serves the fake forge to a bundle holding the tools' token: only that token is taken, the rules are -// refused as to a non-administrator, and the branches named protected say so as the forge does. -func asTools(t *testing.T, f *fakeForge, protected map[string]string, scopes string) (*Forge, *[]string) { - dir := t.TempDir() - file := filepath.Join(dir, "token") - if err := os.WriteFile(file, []byte(toolsToken+"\n"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(file+".scopes", []byte(scopes+"\n"), 0o600); err != nil { +// vaultHolding is the vault seat's get answering account's token sealed to the key it is asked with; "" holds none. +func vaultHolding(t *testing.T, account, token string) *forgehttp.VaultToken { + t.Helper() + v, err := forgehttp.NewVaultToken(account, func(address string, args any) (json.RawMessage, error) { + a := args.(map[string]any) + if address != forgehttp.VaultGet || a["name"] != forgehttp.VaultName(account) { + return nil, fmt.Errorf("asked %s for %v", address, a["name"]) + } + if token == "" { + return nil, fmt.Errorf("the vault holds no secret named %s", a["name"]) + } + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), a["public_key"].(string)) + if err != nil { + return nil, err + } + return json.Marshal(map[string]any{"name": a["name"], "generation": 1, "sealed": box}) + }) + if err != nil { t.Fatal(err) } + return v +} + +// asTools serves the fake forge to a bundle holding the token the vault hands: only the tools' token is taken, the +// rules are refused as to a non-administrator, and the branches named protected say so as the forge does. +func asTools(t *testing.T, f *fakeForge, protected map[string]string, held string) (*Forge, *[]string) { var seen []string const repo = "/api/v1/repos/acme/app" srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -52,12 +71,12 @@ func asTools(t *testing.T, f *fakeForge, protected map[string]string, scopes str f.handle(w, r) })) t.Cleanup(srv.Close) - return &Forge{Client: forgehttp.Client{URL: srv.URL, TokenFile: file, Account: "mesh-tools"}}, &seen + return &Forge{Client: forgehttp.Client{URL: srv.URL, Token: vaultHolding(t, "mesh-tools", held), Account: "mesh-tools"}}, &seen } func TestTheToolsAccountCommitsOnANewBranchWithItsTokenThoughTheRulesAreNotItsToRead(t *testing.T) { f := newFake(t) - forge, _ := asTools(t, f, nil, "read:user,write:issue,write:repository for mesh-tools") + forge, _ := asTools(t, f, nil, toolsToken) got, err := commit(context.Background(), forge, ask(t, map[string]any{"branch": "fix/365", "files": filesArg(map[string]any{"path": "x", "content": "x"})})) if err != nil { @@ -75,7 +94,7 @@ func TestTheToolsAccountIsRefusedAProtectedBranchTheForgeSaysItGuardsAndTheDefau if rule != "" { protected[branch] = rule } - forge, _ := asTools(t, f, protected, "read:user,write:issue,write:repository for mesh-tools") + forge, _ := asTools(t, f, protected, toolsToken) _, err := commit(context.Background(), forge, ask(t, map[string]any{"branch": branch, "files": filesArg(map[string]any{"path": "x", "content": "x"})})) if err == nil || !strings.Contains(err.Error(), "refused") || !strings.Contains(err.Error(), "ADR 0266") { @@ -90,13 +109,13 @@ func TestTheToolsAccountIsRefusedAProtectedBranchTheForgeSaysItGuardsAndTheDefau } } -func TestATokenKeptForTheAdministratorIsNeverSent(t *testing.T) { +func TestNoTokenIsSentWhileTheVaultHoldsNoneForTheAccount(t *testing.T) { f := newFake(t) - // What the module kept before ADR 0365: the admin's token, its scopes line naming no account. - forge, seen := asTools(t, f, nil, "read:user,write:issue,write:repository") + // Design 47 H2 §808: the token is read through the vault seat's get; while the module has minted none, nothing goes. + forge, seen := asTools(t, f, nil, "") _, err := commit(context.Background(), forge, ask(t, map[string]any{"branch": "fix/365", "files": filesArg(map[string]any{"path": "x", "content": "x"})})) - if err == nil || !strings.Contains(err.Error(), "not mesh-tools's") { + if err == nil || !strings.Contains(err.Error(), "not kept yet") { t.Fatalf("%v", err) } if len(*seen) != 0 { @@ -104,9 +123,8 @@ func TestATokenKeptForTheAdministratorIsNeverSent(t *testing.T) { } } -func TestTheBundleHandedATokenFileNeedsNoAdminLogin(t *testing.T) { +func TestTheBundleReadsItsTokenFromTheVaultAndNeedsNoAdminLogin(t *testing.T) { t.Setenv("MESH_GITEA_URL", "http://127.0.0.1:3000") - t.Setenv("MESH_GITEA_TOKEN_FILE", "/state/token") t.Setenv("MESH_GITEA_TOOLS_USER", "") t.Setenv("MESH_GITEA_ADMIN_USER", "") t.Setenv("MESH_GITEA_ADMIN_PASSWORD_FILE", "") @@ -114,7 +132,7 @@ func TestTheBundleHandedATokenFileNeedsNoAdminLogin(t *testing.T) { if err != nil { t.Fatal(err) } - if f.TokenFile != "/state/token" || f.Account != "mesh-tools" || f.User != "" || f.PasswordFile != "" { + if f.Token == nil || f.Token.Account != "mesh-tools" || f.Account != "mesh-tools" || f.User != "" || f.PasswordFile != "" { t.Fatalf("%+v", f.Client) } } diff --git a/modules/gitea/cmd/forge/forge.go b/modules/gitea/cmd/forge/forge.go index a9d279306..1be60c00b 100644 --- a/modules/gitea/cmd/forge/forge.go +++ b/modules/gitea/cmd/forge/forge.go @@ -21,7 +21,10 @@ type Forge struct { // ForgeFromEnv is the forge as the manifest hands it to this bundle. func ForgeFromEnv() (*Forge, error) { - c, missing := forgehttp.FromEnv() + c, missing, err := forgehttp.ToolsFromEnv() + if err != nil { + return nil, err + } if len(missing) > 0 { return nil, fmt.Errorf("the forge cannot be reached: %s not set by the manifest", strings.Join(missing, ", ")) } diff --git a/modules/gitea/cmd/forge/forge_test.go b/modules/gitea/cmd/forge/forge_test.go index 427330873..1113d946b 100644 --- a/modules/gitea/cmd/forge/forge_test.go +++ b/modules/gitea/cmd/forge/forge_test.go @@ -691,8 +691,15 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) { // The tools' own account, never the admin login (novox/hq ADR 0365 §2); the package registry's bundle also writes // as the packages account (design 51: the write side an own secret beside a read-only tool token). wants := map[string][]string{ - "cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_TOKEN_FILE"}, - "cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_USER", "MESH_GITEA_PACKAGES_TOKEN_FILE"}, + "cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"}, + "cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_USER"}, + } + // H-A-564: until gitea runs as its own account, each Go bundle is handed the token files gitea's TypeScript bundle + // keeps under its state directory, read when the vault refuses the caller's account. + files := map[string]map[string]string{ + "cmd/forge": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token"}, + "cmd/package-registry": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token", + "MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token"}, } for _, a := range m.Build.Artifacts { want, ok := wants[a.From] @@ -713,6 +720,11 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) { t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k) } } + for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} { + if a.Env[k] != files[a.From][k] { + t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][k]) + } + } } for from := range wants { t.Errorf("the manifest builds no %s bundle", from) diff --git a/modules/gitea/cmd/forge/main.go b/modules/gitea/cmd/forge/main.go index fadedecdd..ec2132339 100644 --- a/modules/gitea/cmd/forge/main.go +++ b/modules/gitea/cmd/forge/main.go @@ -14,6 +14,8 @@ import ( "strings" stdio "git.novox.be/novox/mesh-sdk/go" + + "gitea/internal/forgehttp" ) // ToolNames are the tools this bundle serves. The module's manifest lists no `tools` (see the package-registry @@ -21,6 +23,16 @@ import ( var ToolNames = []string{"gitea_commit", "gitea_commits", "gitea_compare", "gitea_pull_reviews", "gitea_list_dir", "gitea_search_code"} func main() { + // The tools' account's token, read from the vault at start and at each secret-changed naming it (design 47 H2 §808). + go func() { + account := os.Getenv("MESH_GITEA_TOOLS_USER") + if account == "" { + account = forgehttp.ToolsAccount + } + if err := forgehttp.Follow(func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) }, account); err != nil { + fmt.Fprintln(os.Stderr, "the vault's changes of the forge token are not heard:", err) + } + }() if err := stdio.Serve("", Tools(ForgeFromEnv)); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) diff --git a/modules/gitea/cmd/package-registry/forge.go b/modules/gitea/cmd/package-registry/forge.go index 82fb0e69a..3823e2e5a 100644 --- a/modules/gitea/cmd/package-registry/forge.go +++ b/modules/gitea/cmd/package-registry/forge.go @@ -78,8 +78,14 @@ func (f *Forge) As(typ string) *Forge { // ForgeFromEnv is the forge as the manifest hands it to this bundle. func ForgeFromEnv() (*Forge, error) { - c, missing := forgehttp.FromEnv() - w, writeMissing := forgehttp.WriterFromEnv() + c, missing, err := forgehttp.ToolsFromEnv() + if err != nil { + return nil, err + } + w, writeMissing, err := forgehttp.WriterFromEnv() + if err != nil { + return nil, err + } for _, m := range writeMissing { if m != "MESH_GITEA_URL" { missing = append(missing, m) @@ -168,7 +174,7 @@ func (f *Forge) DistTags(ctx context.Context, name string) (map[string]string, e // write is the registry's write side, refused when the manifest handed none. func (f *Forge) write() (*forgehttp.Client, error) { if f.Writer == nil { - return nil, errors.New("the package registry's write side is not handed to this bundle (MESH_GITEA_PACKAGES_TOKEN_FILE); nothing was written") + return nil, errors.New("the package registry's write side is not handed to this bundle (the packages account's token); nothing was written") } return f.Writer, nil } diff --git a/modules/gitea/cmd/package-registry/main.go b/modules/gitea/cmd/package-registry/main.go index 02de1384c..96adda433 100644 --- a/modules/gitea/cmd/package-registry/main.go +++ b/modules/gitea/cmd/package-registry/main.go @@ -17,6 +17,7 @@ import ( stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/views" + "gitea/internal/forgehttp" "gitea/internal/packageseats" ) @@ -49,6 +50,19 @@ func main() { os.Exit(1) } }() + // Both accounts' tokens, read from the vault at start and at each secret-changed naming one (design 47 H2 §808). + go func() { + tools, packages := os.Getenv("MESH_GITEA_TOOLS_USER"), os.Getenv("MESH_GITEA_PACKAGES_USER") + if tools == "" { + tools = forgehttp.ToolsAccount + } + if packages == "" { + packages = forgehttp.PackagesAccount + } + if err := forgehttp.Follow(func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) }, tools, packages); err != nil { + fmt.Fprintln(os.Stderr, "the vault's changes of the forge tokens are not heard:", err) + } + }() forge := func() (*Forge, error) { return ForgeFromEnv() } holder := func() (*packageseats.Holder, error) { return busHolder(forge) } go followIdle(holder) diff --git a/modules/gitea/cmd/package-registry/retention_test.go b/modules/gitea/cmd/package-registry/retention_test.go index 4eb926efb..9dd5ee5cd 100644 --- a/modules/gitea/cmd/package-registry/retention_test.go +++ b/modules/gitea/cmd/package-registry/retention_test.go @@ -480,22 +480,24 @@ func TestToolsAreTheOnesTheReadmeNamesAndSayWhatTheyDo(t *testing.T) { Objects any `json:"objects"` State any `json:"state"` }{m.Objects, m.State}) - for _, want := range []string{`"name":"incoming"`, `"transfers"`, `"key-ttl":true,"name":"idle"`} { + // Each with its cap (design 47 H2 §812, H-A-411 (2)). + for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`} { if !strings.Contains(string(req), want) { t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req) } } // findings is one local name in one form (novox/hq ADR 0595 §11): the old section state, which the TypeScript bundle // announces readable for the condition keeper (kept.ts), never also under requires. - if strings.Contains(string(req), `"name":"findings"`) { - t.Errorf("findings is required as well as kept in state: %s", req) + if required, _ := json.Marshal(m.Requires); strings.Contains(string(required), `"name":"findings"`) { + t.Errorf("findings is required as well as kept in state: %s", required) } // transfers keeps for good: a lifetime of its own would drop a transfer's key and leave its chunks in incoming. if strings.Contains(string(req), `"name":"transfers","options"`) { t.Errorf("transfers has options (a lifetime): %s", req) } // The retention asks the builder's versions; the forge's other bundles ask the catalog half and record a re-read. - if strings.Join(m.Invokes, ",") != "seat:mesh-catalog.revision,seat:mesh-catalog.registrations,seat:mesh-hand-acts.hand-act,seat:mesh-builds.reserved" { + // The forge module's tokens through the vault seat: own-put by the minter, get by every process (design 47 H2 §808). + if strings.Join(m.Invokes, ",") != "seat:mesh-catalog.revision,seat:mesh-catalog.registrations,seat:mesh-hand-acts.hand-act,seat:mesh-builds.reserved,seat:mesh-vault.own-put,seat:mesh-vault.get" { t.Errorf("the manifest invokes %v", m.Invokes) } if len(m.Tools) != 0 { @@ -505,7 +507,7 @@ func TestToolsAreTheOnesTheReadmeNamesAndSayWhatTheyDo(t *testing.T) { for _, a := range m.Build.Artifacts { if a.From == "cmd/package-registry" { found = true - for _, k := range []string{"MESH_GITEA_URL", "MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE", "MESH_NPM_OWNER"} { + for _, k := range []string{"MESH_GITEA_URL", "MESH_NPM_OWNER"} { if a.Env[k] == "" { t.Errorf("the bundle is not given %s", k) } diff --git a/modules/gitea/cmd/package-registry/seats.go b/modules/gitea/cmd/package-registry/seats.go index 246da7580..63ddb1f49 100644 --- a/modules/gitea/cmd/package-registry/seats.go +++ b/modules/gitea/cmd/package-registry/seats.go @@ -291,7 +291,7 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func() } return []stdio.Tool{ {Name: seat + "." + packageseats.VerbPublish, Input: obj, - Description: "Open a transfer of a package's one file (ADR 0611): its name, the builder's version, kind package, its sha256 digest and the file as its one part; answers the part the forge lacks. A version held with that digest answers held and says published.", + Description: "Open a transfer of a package's one file (ADR 0611): its name, the builder's version, kind package, its sha256 digest and the file as its one part; answers the part the forge lacks. A version held with that digest answers held and says published; with no part at all (the builder's publish again) nothing moves: held says published, else refused as not stored, naming the digest (design 47 G A-490).", Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) { in, err := as[PI](args) if err != nil { diff --git a/modules/gitea/cmd/package-registry/seats_test.go b/modules/gitea/cmd/package-registry/seats_test.go index 13d4fbd0f..5d30aff98 100644 --- a/modules/gitea/cmd/package-registry/seats_test.go +++ b/modules/gitea/cmd/package-registry/seats_test.go @@ -9,17 +9,17 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" - "os" - "path/filepath" "strings" "sync" "testing" "time" keyparts "git.novox.be/novox/mesh-sdk/go/keys" + "git.novox.be/novox/mesh-sdk/go/seal" "git.novox.be/novox/mesh-sdk/go/views" "gitea/internal/forgehttp" @@ -116,15 +116,10 @@ func TestThePackageSeatsStoreIntoTheForge(t *testing.T) { g := ®istry{uploaded: map[string][]byte{}, held: map[string][]byte{}} srv := httptest.NewServer(http.HandlerFunc(g.handle)) defer srv.Close() - dir := t.TempDir() - kept := func(name, token, line string) string { - file := filepath.Join(dir, name) - _ = os.WriteFile(file, []byte(token+"\n"), 0o600) - _ = os.WriteFile(file+".scopes", []byte(line+"\n"), 0o600) - return file - } - reader := forgehttp.Client{URL: srv.URL, TokenFile: kept("token", "reader", "read:package,read:user for mesh-tools"), Account: "mesh-tools"} - writer := forgehttp.Client{URL: srv.URL, TokenFile: kept("packages-token", "writer", "write:package for mesh-packages"), Account: "mesh-packages"} + vault := map[string]string{"mesh-tools": "reader", "mesh-packages": "writer"} + writerToken := vaultHolding(t, "mesh-packages", vault) + reader := forgehttp.Client{URL: srv.URL, Token: vaultHolding(t, "mesh-tools", vault), Account: "mesh-tools"} + writer := forgehttp.Client{URL: srv.URL, Token: writerToken, Account: "mesh-packages"} forge := &Forge{Client: reader, Writer: &writer, Owner: "acme"} if _, err := (seatStore{forge: func() (*Forge, error) { return &Forge{Client: reader, Owner: "acme"}, nil }}).Put(packageseats.GoSeat, packageseats.Publish{}, nil); err == nil || !strings.Contains(err.Error(), "write side") { @@ -138,12 +133,22 @@ func TestThePackageSeatsStoreIntoTheForge(t *testing.T) { if k := views.FindingKey("seat", keyparts.EscapeName(packageseats.Self)+".write", PackagesTokenRefused); k != PackagesTokenRefusedKey { t.Errorf("the refusal's key is %s, the watcher watches %s", k, PackagesTokenRefusedKey) } - _ = os.WriteFile(writer.TokenFile, []byte("stale\n"), 0o600) + vault["mesh-packages"] = "stale" + if read, err := writerToken.Changed([]byte(`{"name":"module/gitea/mesh-packages","generation":2}`)); !read || err != nil { + t.Fatalf("the secret-changed of the packages token was not read again: %v %v", read, err) + } if _, err := s.Put(packageseats.GoSeat, packageseats.Publish{Version: "0.1.15"}, moduleZip(t, "git.example/acme/sdk@v0.1.15")); err == nil || len(refused) != 1 || !refused[0] { t.Errorf("a write the forge refused with 401 raised no finding: %v %v", err, refused) } - _ = os.WriteFile(writer.TokenFile, []byte("writer\n"), 0o600) + vault["mesh-packages"] = "writer" + // Design 47 H2 §808: a secret-changed naming another secret reads nothing; the one naming this token reads it again. + if read, _ := writerToken.Changed([]byte(`{"name":"module/gitea/mesh-tools","generation":3}`)); read { + t.Error("a secret-changed of the tools' token read the packages token again") + } + if read, err := writerToken.Changed([]byte(`{"name":"module/gitea/mesh-packages","generation":3}`)); !read || err != nil { + t.Fatalf("the secret-changed of the packages token was not read again: %v %v", read, err) + } tgz := tarball(t, `{"name":"@acme/contracts","version":"0.1.15-feat-x.2","main":"index.js"}`) p := packageseats.Publish{Name: "@acme/contracts", Version: "0.1.15-feat-x.2", Tag: "feat-x", Kind: packageseats.KindPackage, Digest: "sha256:" + sha(tgz)} @@ -197,3 +202,30 @@ func TestThePackageSeatsStoreIntoTheForge(t *testing.T) { t.Errorf("a write the forge took after the refusal did not clear it: %v", refused) } } + +// vaultHolding is the vault seat's get answering account's token from held, sealed to the key it is asked with; an +// account held has no entry is a secret the vault holds none of. +func vaultHolding(t *testing.T, account string, held map[string]string) *forgehttp.VaultToken { + t.Helper() + v, err := forgehttp.NewVaultToken(account, func(address string, args any) (json.RawMessage, error) { + a := args.(map[string]any) + if address != forgehttp.VaultGet || a["name"] != forgehttp.VaultName(account) { + return nil, fmt.Errorf("asked %s for %v", address, a["name"]) + } + token, ok := held[account] + if !ok { + return nil, fmt.Errorf("the vault holds no secret named %s", a["name"]) + } + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), a["public_key"].(string)) + if err != nil { + return nil, err + } + return json.Marshal(map[string]any{"name": a["name"], "generation": 1, "sealed": box}) + }) + if err != nil { + t.Fatal(err) + } + return v +} diff --git a/modules/gitea/cmd/package-registry/whole_integration_test.go b/modules/gitea/cmd/package-registry/whole_integration_test.go index b7b76057f..1f4f511f4 100644 --- a/modules/gitea/cmd/package-registry/whole_integration_test.go +++ b/modules/gitea/cmd/package-registry/whole_integration_test.go @@ -40,6 +40,7 @@ import ( "github.com/nats-io/nats.go/jetstream" "git.novox.be/novox/mesh-sdk/go/buscalls" + "git.novox.be/novox/mesh-sdk/go/seal" "git.novox.be/novox/mesh-sdk/go/testbus" "gitea/internal/packageseats" @@ -65,6 +66,7 @@ type player struct { answers map[string]chan wire puts map[string][]byte // the put sessions open, by call gets map[string][]byte // the get sessions open, by call + vault map[string]string // the vault's secrets the seat's get hands, by name (design 47 H2 §808) } func (p *player) send(m map[string]any) { @@ -130,6 +132,21 @@ func (p *player) handle(m wire) { break } p.answer(m.ID, map[string]any{"module": "m", "version": q.Version, "artifacts": []map[string]any{{"artifact": "m:a", "digest": d}}}, nil) + case m.Method == "mesh/ask" && a.Key == "seat:mesh-vault.get": + var q struct { + Name string `json:"name"` + PublicKey string `json:"public_key"` + } + _ = json.Unmarshal(a.Body, &q) + token, ok := p.vault[q.Name] + if !ok { + p.answer(m.ID, nil, errors.New("the vault holds no secret named "+q.Name)) + break + } + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), q.PublicKey) + p.answer(m.ID, map[string]any{"name": q.Name, "generation": 1, "sealed": box}, err) case m.Method == "mesh/seat.publish": p.answer(m.ID, map[string]any{}, p.nc.Publish(a.Subject, a.Body)) case m.Method == "mesh/capabilities": @@ -378,17 +395,9 @@ func TestThePackageSeatsWhole(t *testing.T) { } })) t.Cleanup(srv.Close) - dir := t.TempDir() - kept := func(name, token, line string) string { - file := filepath.Join(dir, name) - _ = os.WriteFile(file, []byte(token+"\n"), 0o600) - _ = os.WriteFile(file+".scopes", []byte(line+"\n"), 0o600) - return file - } cmd := exec.CommandContext(ctx, bin) cmd.Env = append(os.Environ(), "MESH_NODE=novox", "MESH_GITEA_URL="+srv.URL, "MESH_NPM_OWNER=acme", "MESH_GITEA_TOOLS_USER=mesh-tools", - "MESH_GITEA_TOKEN_FILE="+kept("token", "reader", "read:package,read:user,write:issue,write:repository for mesh-tools"), - "MESH_GITEA_PACKAGES_TOKEN_FILE="+kept("packages-token", "writer", "write:package for mesh-packages")) + "MESH_GITEA_PACKAGES_USER=mesh-packages") cmd.Stderr = os.Stderr in, _ := cmd.StdinPipe() out, _ := cmd.StdoutPipe() @@ -400,6 +409,7 @@ func TestThePackageSeatsWhole(t *testing.T) { zipped := bigZip(t, "git.example/acme/sdk@v0.1.15") digest := "sha256:" + sha(zipped) p := &player{ctx: ctx, t: t, nc: nc, js: js, in: in, answers: map[string]chan wire{}, + vault: map[string]string{"module/gitea/mesh-tools": "reader", "module/gitea/mesh-packages": "writer"}, numbered: map[string]string{"git.example/acme/sdk@0.1.15": digest}} go p.serve(out) p.send(map[string]any{"id": "init", "method": "initialize", "params": map[string]any{}}) diff --git a/modules/gitea/cmd/repositories/main.go b/modules/gitea/cmd/repositories/main.go index fea644bc2..a6b791ec0 100644 --- a/modules/gitea/cmd/repositories/main.go +++ b/modules/gitea/cmd/repositories/main.go @@ -36,10 +36,6 @@ func runSync() int { missing = append(missing, k) } } - if forge.TokenFile != "" { - // The tools' account cannot make or protect a repository, and must not (ADR 0428 §8). - missing = append(missing, "the setup login (MESH_GITEA_TOKEN_FILE is set instead)") - } if len(missing) > 0 { fmt.Fprintf(os.Stderr, "repositories: %v not set by the manifest; nothing was changed\n", missing) return 1 diff --git a/modules/gitea/delivery.ts b/modules/gitea/delivery.ts index ed65da6f4..6548954e0 100644 --- a/modules/gitea/delivery.ts +++ b/modules/gitea/delivery.ts @@ -68,6 +68,15 @@ export async function appendNote(runner: Runner, container: string, owner: strin return { added: true, lines: lines.length + 1 }; } +/** Whether a commit's note holds a line carrying the act's id, read without writing (design 47 H2 §775: a repeat of a + * taken ask answers what its act did). */ +export async function noteHolds(runner: Runner, container: string, owner: string, repo: string, commit: string, + notesRef: string, id: string): Promise { + const shown = await runner("docker", noteArgs(container, owner, repo, commit, notesRef)); + if (shown.code !== 0 && shown.code !== 1) throw new Error(`the note on ${commit.slice(0, 8)} could not be read (git exited ${shown.code})`); + return shown.code === 0 && shown.stdout.split("\n").some((l) => l.includes(`[${id}]`)); +} + /** The marker that makes one comment of a pull request the delivery's view. */ export const VIEW_MARKER = ""; diff --git a/modules/gitea/failedsteps.ts b/modules/gitea/failedsteps.ts index 84473b12f..8e69a721b 100644 --- a/modules/gitea/failedsteps.ts +++ b/modules/gitea/failedsteps.ts @@ -19,6 +19,7 @@ import { failedStepsByModuleFingerprintStepKey as failedKey, type FailedStep, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent, } from "@novox/mesh-delivery-contracts-git"; import type { StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner"; +import { findingKey } from "./catalog.js"; /** The key prefix of the commits' fingerprints (§487). */ export const SEEN = "seen."; @@ -58,6 +59,22 @@ const safe = (s: string): string => s.replace(/[^A-Za-z0-9_=/-]/g, "_"); export const seenKey = (commit: string, module: string): string => `${SEEN}${commit}.${safe(module)}`; export const failedStepKey = (module: string, fingerprint: string, step: string): string => failedKey(safe(module), safe(fingerprint), safe(step)); +/** The finding of a step-ended the forge module could not record (G §585). */ +export const STEP_UNREAD = "step-unread"; + +/** step-unread of one step of one run (H-A-93): its key in the state findings and its value. */ +export function stepUnreadFinding(run: string, module: string, step: string, at: string): { key: string; value: Record } { + const key = findingKey("module", `${run}.${module}.${step}`, STEP_UNREAD); + const summary = `the step-ended of ${step} of ${module} in run ${run} names no build-input fingerprint, so a failure of it cannot be recorded`; + return { key, value: { + v: 1, key, kind: STEP_UNREAD, subject: { scope: "module", id: module }, severity: "warning", resolver: "operator", summary, + headline: `A step the forge module could not read: ${step} of ${module}`, + explanation: `merge-pull judges a head by the failed required steps at its fingerprint; this step-ended of run ${run} carries no fingerprint, ` + + "so the forge module could not keep it. A later step-ended of the step with its fingerprint clears this.", + resolved: "", evidence: [{ at, said: summary }], source: `gitea.${STEP_UNREAD}`, observer: "gitea", at, + } }; +} + export class FailedSteps { /** Every act runs after the one before it, so a step-ended and a head's loss never interleave their reads and writes. */ private chain: Promise = Promise.resolve(); @@ -66,7 +83,9 @@ export class FailedSteps { /** Whether a commit is now a watched branch's head or an open pull request's head. */ private readonly current: (commit: string) => boolean = () => false, /** The state's fill against its caps: the bundle's state call (§623). */ - private readonly fillOf: () => Promise = askFill) {} + private readonly fillOf: () => Promise = askFill, + /** The module's state findings, where step-unread is written (G §585, H-A-93); none writes no finding. */ + private readonly findings?: State) {} private turn(act: () => Promise): Promise { const r = this.chain.then(act, act); @@ -98,9 +117,13 @@ export class FailedSteps { private record(ev: StepEndedEvent): Promise { const r = ev?.result; - const fingerprint = r?.fingerprint || ev?.fingerprint || ""; - if (!r || !SHA.test(String(ev.commit ?? "")) || !fingerprint || !ev.module) return Promise.resolve(); + // The fingerprint is the body's, the build-input fingerprint the runner fills in every step-ended; no field of the step's + // result is read for it (G §585, H-A-93). + const fingerprint = ev?.fingerprint || ""; + if (!r || !SHA.test(String(ev.commit ?? "")) || !ev.module) return Promise.resolve(); + if (!fingerprint) return this.turn(() => this.unread(ev, true)); return this.turn(async () => { + await this.unread(ev, false); const at = ev.at ?? new Date().toISOString(); const sk = seenKey(ev.commit, ev.module); const held = (await this.st.get(sk))?.value as Seen | undefined; @@ -137,6 +160,26 @@ export class FailedSteps { }); } + /** + * step-unread (G §585, H-A-93): a step-ended without its fingerprint writes the finding, scope module, its subject the step's + * module, keyed `..`, naming the run, the module and the step, severity warning, resolver operator; a + * later step-ended of that step with its fingerprint clears it, so a failure that could not be recorded is seen. + */ + private async unread(ev: StepEndedEvent, raise: boolean): Promise { + if (!this.findings) return; + const step = String(ev.result?.step ?? ""), run = String(ev.pipeline ?? ""); + const { key, value } = stepUnreadFinding(run, ev.module, step, String(ev.at ?? new Date().toISOString())); + if (!raise) { + if ((await this.findings.get(key))?.value) { + await this.findings.delete(key); + this.log(`${ev.module} ${step} of ${run} is read with its fingerprint: step-unread cleared`); + } + return; + } + await this.findings.put(key, value); + this.log(String(value.summary)); + } + /** The failed `required` step that refuses this head, or null: a head with a `seen` key is judged by it, one with none merges (§487). */ judge(head: string): Promise { return this.turn(async () => { diff --git a/modules/gitea/gate.ts b/modules/gitea/gate.ts deleted file mode 100644 index e738bc70e..000000000 --- a/modules/gitea/gate.ts +++ /dev/null @@ -1,103 +0,0 @@ -// **One writer of a head's mesh/merge-gate** (novox/hq issue 446). -// -// A pending check says where it is: "waiting in the build queue since …" when the head is announced. The forge keeps only -// the newest status of a context, so two writers cannot order their writes; this module is the one writer of -// mesh/merge-gate, and every write of one head's gate goes through one chain, in the order it was asked. A recheck's -// pending (novox/hq issue 456) and a trunk's move (ADR 0323 §4) take their turns on the same chain. No verdict is written -// here any more: the controller's `checked` is no event (ADR 0571 clause 13), and main requires the checker's mesh/check. - -import { CHECK_CONTEXT, pendingWords } from "./pulls.js"; -import type { CommitStatus, HeadCheck } from "./client.js"; - -/** What the gate writer needs of the forge: a status set, and a head's statuses as the forge holds them. */ -export interface GateForge { - setCommitStatus(owner: string, repo: string, sha: string, status: CommitStatus): Promise; - /** The head's statuses by context, the newest of each, with their words (novox/hq ADR 0323). */ - headChecks(owner: string, repo: string, sha: string): Promise>; -} - -/** Whether a repository as the mesh clones it (`http://forge/novox/hq.git`) is owner/repo. */ -export function clonedAs(url: string | undefined, owner: string, repo: string): boolean { - const u = (url ?? "").trim().toLowerCase().replace(/\.git$/, ""); - const full = `${owner}/${repo}`.toLowerCase(); - return u === full || u.endsWith("/" + full); -} - -interface Head { - /** The chain the head's writes take their turns on. */ - chain: Promise; -} - -export class GateWriter { - private heads = new Map(); - private forge: GateForge; - private now: () => Date; - - constructor(forge: GateForge, now: () => Date = () => new Date()) { - this.forge = forge; - this.now = now; - } - - private head(owner: string, repo: string, sha: string): Head { - const key = `${owner}/${repo}@${sha}`.toLowerCase(); - let h = this.heads.get(key); - if (!h) { - h = { chain: Promise.resolve() }; - this.heads.set(key, h); - // Kept for the heads still in play; the oldest go first, past what any forge holds open at once. - if (this.heads.size > 2000) this.heads.delete(this.heads.keys().next().value as string); - } - return h; - } - - /** One turn on the head's chain; a turn that fails never stops the next. Its failure is the caller's. */ - private turn(h: Head, fn: () => Promise): Promise { - const run = h.chain.then(fn); - h.chain = run.catch(() => {}); - return run; - } - - /** A turn whose failure is said here: a pending word not written is not worth the event again. */ - private said(h: Head, what: string, fn: () => Promise): Promise { - return this.turn(h, fn).catch((err) => { - console.error(`[gitea] ${what} — ${err instanceof Error ? err.message : err}`); - }); - } - - /** The head announced: it waits in the build queue from now. A new check of the head, so no verdict yet. */ - pending(owner: string, repo: string, sha: string): Promise { - const h = this.head(owner, repo, sha); - const at = this.now(); - return this.said(h, `${owner}/${repo}@${sha.slice(0, 8)}: could not say a check is pending`, () => - this.forge.setCommitStatus(owner, repo, sha, { state: "pending", context: CHECK_CONTEXT, description: pendingWords(at) })); - } - - /** - * A status the seat git's `status` verb sets (seat.ts), a recheck's pending among them (novox/hq issue 456): it takes - * its turn after every write of the head already asked for, so it lands over them, and a later write lands over it. A - * write that fails fails the caller. - */ - status(owner: string, repo: string, sha: string, status: CommitStatus): Promise { - return this.turn(this.head(owner, repo, sha), () => this.forge.setCommitStatus(owner, repo, sha, status)); - } - - /** - * **A trunk's move puts the head's verdict out of date** (novox/hq ADR 0323 §4): its merge check statuses are put back - * to pending, with the reason, in their turn after every write of the head already asked for — a verdict in flight - * lands first. What is written is decided in the turn, from the statuses the forge holds then (`decide`, trunk.ts's - * outOfDateStatuses): a check on its way, or a verdict already judged against the trunk's head, is left as it is. It - * opens no check — nothing is asked — so a verdict of a check asked before it keeps its weight. Answers what it wrote; - * a write that fails fails the caller, and the move is weighed again on the next pass. - */ - outOfDate(owner: string, repo: string, sha: string, - decide: (checks: Record) => CommitStatus[] | Promise, target?: string): Promise { - const h = this.head(owner, repo, sha); - const written: CommitStatus[] = []; - return this.turn(h, async () => { - for (const s of await decide(await this.forge.headChecks(owner, repo, sha))) { - await this.forge.setCommitStatus(owner, repo, sha, target ? { ...s, target_url: target } : s); - written.push(s); - } - }).then(() => written); - } -} diff --git a/modules/gitea/index.ts b/modules/gitea/index.ts index d26359575..6bd700ba7 100644 --- a/modules/gitea/index.ts +++ b/modules/gitea/index.ts @@ -4,8 +4,7 @@ // Emits (novox/hq ADR 0041/0042): // module.gitea.repo.created — a repository appeared, however it was made (push, web UI, or tool) // module.gitea.pull.merged — a pull request was merged, however it was merged (web UI, API, or tool) -// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to: the mesh checks it -// before it merges (novox/hq to-be 45 §9) +// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to, said from the forge's event alone // // module.gitea.pull.closed — a pull request closed unmerged: the delivery it was is stopped (novox/hq ADR 0239) // @@ -16,13 +15,8 @@ // It reads no other module's state: mesh/check, and every act of a delivery part on the forge, arrive as verbs of the seat // git (seat.ts), asked by the forge bridge (novox/hq design 47 *The seat git*). // -// This module is the one writer of mesh/merge-gate. It hears no build seat's event: since R4g a check's steps are asks -// on the build seats' streams, whose backlog the delivery view shows (novox/hq ADR 0525 §9; issue 1887). -// -// **A trunk's move puts every open verdict into it out of date** (novox/hq ADR 0323 §4, trunk.ts): each pass reads the -// head of every trunk an open pull request merges into, and when one moved, the merge check statuses of every open pull -// request into it go back to pending with the reason. Nothing is run for it. A verdict that lands judged against a trunk -// commit that is no longer the trunk's head is said out of date in place of its pass or failure. +// No merge check is asked, weighed or written here (design 47 H §764; H-A-28, H-A-100): a merge is one merge call of the +// seat git (mergecall.ts), its members judged by their heads and failed steps alone. // // Every pull request the forge holds is announced, whatever its repository: the controller holds the // module graph and decides what is checked — a repository is never asked to opt in. @@ -38,7 +32,7 @@ import { emit } from "@novox/mesh-sdk/events"; import { registerModuleTools } from "@novox/mesh-sdk/tools"; import { statesAnnouncement } from "./kept.js"; -import { state } from "@novox/mesh-sdk/state"; +import { state, TAKEN_STATE } from "@novox/mesh-sdk/state"; import { on } from "@novox/mesh-sdk/events"; import { broker } from "@novox/mesh-sdk/messaging"; import { STATUS_STATE, keepStatus, statusTools, viewWaitsFinding, type Follower, type Status } from "@novox/mesh-sdk/views"; @@ -50,22 +44,25 @@ import { FORGE_CONTAINER, seatTools } from "./seat.js"; import { REGISTRATION_CHANGED_EVENT, Registrations } from "./registrations.js"; import { FailedSteps, Heads, readHeads } from "./failedsteps.js"; import { failedStepsTools } from "./tools/failedsteps.js"; +import { Calls, callRetentionDays, sayUnsaid } from "./calls.js"; +import { Once, askTakenBoundMs, takenState } from "./taken.js"; +import { Partials } from "./partials.js"; +import { callTools, mergedTool } from "./tools/calls.js"; +import { tokenLeaseTool } from "./tools/tokenlease.js"; +import { processVaultAndLease } from "./token.js"; +import { seatPublish } from "@novox/mesh-sdk/runtime"; import { seat as GIT, events as GIT_EVENTS, type BranchMovedEvent, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent } from "@novox/mesh-delivery-contracts-git"; import { seat as RUNNER, events as RUNNER_EVENTS, type StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner"; import { run } from "./delivery.js"; import { GiteaAdmin, GiteaClient, movedSince } from "./client.js"; -import { keepMainRules, mainRulesStep } from "./mainrules.js"; -import { CHECK_CONTEXT, CHECK_STATUS, REPO_CHECK_CONTEXT, headKey, requiredOf, writesGate, type Announced } from "./pulls.js"; -import { actOn, announceNewHeads, startPass } from "./watch.js"; -import { GateWriter } from "./gate.js"; -import { HOOK_PATH, HOOK_PORT, Pace, claimHead, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js"; -import { keepSiblings, readSiblings, siblingsFile, weighSiblings } from "./siblings.js"; +import { actOn } from "./watch.js"; +import { HOOK_PATH, HOOK_PORT, Pace, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js"; import { bindInBackground, bindUntilHeld } from "./bind.js"; -import { announcementOf, weighTrunks } from "./trunk.js"; +import { announcementOf } from "./updated.js"; import { ReadAll, readAllTools } from "./readall.js"; import { DeliveredWrites, writeTools } from "./writes.js"; import { TOOLS_ACCOUNT, TOOLS_ORG, meshAccounts } from "./tools-account.js"; -import { PACKAGES_TOKEN_REFUSED, keepPackagesToken, packagesToken, renewOnRefusal } from "./packages-account.js"; +import { PACKAGES_ACCOUNT, PACKAGES_TOKEN_REFUSED, keepPackagesToken, packagesToken, renewOnRefusal } from "./packages-account.js"; // Without a way to a token — configured, or mintable with the admin account (token.ts) — there is // nothing to watch; log and stay quiet rather than crash the runtime. With one, the first poll mints @@ -107,7 +104,7 @@ async function pollRepos(client: GiteaClient): Promise { // What has been announced is kept beside the module's state, so a restart does not announce the // whole history again — and the first tick on a machine with no record announces nothing, because // everything it sees then predates the watching. -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; // What has been announced is no longer kept in a file (novox/hq ADR 0406 §6, §7, issue 976): an announcement carries a // message id (announce.ts), so the same merge announced by the poll and by the forge's event, or again after a restart, @@ -179,7 +176,6 @@ async function announceClosed(client: GiteaClient, repo: RepoOf, pull: PullOf): throw err; } console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`); - await siblingMoves(client, repo.full_name, pull.number); return true; } @@ -239,8 +235,6 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P // Said, because a trigger that fires silently is indistinguishable from one that did not // fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told. console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`); - // Its own merge of the head that was read is no sibling's move; any other is (ADR 0382 §5). - await siblingMoves(client, repo.full_name, pull.number); } catch (err) { announced.delete(pull.merge_commit_sha); throw err; @@ -248,123 +242,12 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P return true; } -// **Every new head of an open pull request is announced** (novox/hq to-be 45 §9): the mesh checks it against every -// machine of its facts before it merges. What this process announced is remembered in memory only (novox/hq ADR 0406 -// §6, §7, issue 976): the announcement carries a message id (announce.ts), so the poll's, the forge event's and the -// merge tool's are one to the bus. After a start, the first look announces a head only if the forge shows no merge check -// of it yet — a head with one was announced — and only what moved in the last day, so a forge's whole backlog is not -// checked at once and a restart asks no check again against a trunk that moved. -let heads: Announced = {}; -let primedPulls = false; -/** **A head, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */ -async function announceHead(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise { - const key = headKey(repo.full_name, pull.number, pull.base); - const sha = String(pull.head_sha ?? ""); - const before = heads[key]; - // Claimed before the first wait, so the other path finds it taken while this one is still announcing. - if (!claimHead(heads, key, sha)) return false; - try { - // The announcement the merge tool makes too when it asks a check (trunk.ts, novox/hq ADR 0323 §5). - await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull)); - } catch (err) { - if (before === undefined) delete heads[key]; - else heads[key] = before; - throw err; - } - // A sibling's new head puts out of date every verdict that read the sibling at another head (ADR 0382 §5). - await siblingMoves(client, repo.full_name, pull.number); - // Said, so an operator knows the mesh was asked to check it. - console.log(`[gitea] announced ${key} at ${sha.slice(0, 8)} to be checked before it merges`); - // Pending until the verdict comes, so the pull request says a check is running rather than nothing — and - // where it is: in the build queue from now, until a build machine takes it (novox/hq issue 446). Only where the base - // still requires mesh/merge-gate (issue 1301): a main that requires mesh/check is the checker's; - // a rule that cannot be read is said pending, as before. - const rule = pull.base ? await client.appliedProtection(repo.owner, repo.name, String(pull.base)).catch(() => undefined) : undefined; - if (writesGate(requiredOf(rule))) await gates.pending(repo.owner, repo.name, sha); - return true; +/** **A pull request's new head, said as pull.updated from the forge's event alone** (design 47 H §764; H-A-100): no + * poll, no pending status and no sibling's weighing. */ +async function announceUpdated(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise { + await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull)); + console.log(`[gitea] said ${repo.full_name}#${pull.number} at ${String(pull.head_sha ?? "").slice(0, 8)} updated`); } -type OpenOf = Awaited>[number]; - -/** Whether the forge shows a merge check of the head, in any state: only an announced head has one. */ -async function alreadyChecked(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise { - try { - const checks = await client.headChecks(repo.owner, repo.name, String(pull.head_sha)); - return CHECK_CONTEXT in checks || REPO_CHECK_CONTEXT in checks || CHECK_STATUS in checks; - } catch { - return false; // the forge cannot say: announced, and the bus's message id collapses it if it was - } -} - -let lastPullLook = ""; -/** The pass over every open pull request: run at the start and when the receiver listens, never on a timer (issue 1422). */ -async function passPulls(client: GiteaClient): Promise { - const began = new Date().toISOString(); - const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString(); - for (const repo of await client.listAllRepos()) { - // Every open pull request, paged (novox/hq issue 579). - const open = await client.listOpenPullsSince(repo.owner, repo.name, ""); - await announceNewHeads(repo.full_name, open, heads, primedPulls, dayAgo, { - alreadyChecked: (pull) => alreadyChecked(client, repo, pull), - announceHead: (pull) => announceHead(client, repo, pull), - missed: (what) => pace.miss(what), - }); - if (await trunksMoved(client, repo.owner, repo.name)) changedTrunks = true; - } - if (changedTrunks) keepTrunks(); - changedTrunks = false; - primedPulls = true; - lastPullLook = began; -} - -// **The trunks' heads, as this module last read them** (novox/hq ADR 0323 §4), by `owner/repo:branch`: kept beside the -// other records, so a move made while this module was away is weighed on its first pass back. With no record — the -// first pass after this rolls out — a trunk's head is taken as it is and nothing is put out of date: the verdicts -// then standing are weighed on the trunk's next move, and the merge tool compares commits whatever this holds. -const trunksRecord = process.env.MESH_GITEA_STATE_DIR ? join(process.env.MESH_GITEA_STATE_DIR, "trunks-seen.json") : null; -let trunks: Record = {}; -let changedTrunks = false; -if (trunksRecord && existsSync(trunksRecord)) { - try { - trunks = (JSON.parse(readFileSync(trunksRecord, "utf8")) as { trunks: Record }).trunks ?? {}; - } catch { - // An unreadable record is no record: the next pass takes each trunk's head as it is. - } -} -function keepTrunks(): void { - if (!trunksRecord) return; - mkdirSync(join(trunksRecord, ".."), { recursive: true }); - const tmp = trunksRecord + ".tmp"; - writeFileSync(tmp, JSON.stringify({ trunks })); - renameSync(tmp, trunksRecord); -} - -/** Whether a trunk of one repository moved, weighed with this module's forge and its one writer (trunk.ts). */ -function trunksMoved(client: GiteaClient, owner: string, name: string): Promise { - return weighTrunks(client, gates, trunks, owner, name, () => siblingMoves(client, `${owner}/${name}`)); -} - -// **The siblings each open pull request's latest verdict names** (novox/hq ADR 0382 §5, siblings.ts), by member, kept beside -// the other records. A sibling's new head, close unmerged, merge, or a move of its base puts the merge check of every -// member whose verdict names it back to pending, with the reason; nothing is run for it. -const siblingsRecord = siblingsFile(process.env.MESH_GITEA_STATE_DIR); -const siblingNamed = readSiblings(siblingsRecord); - -/** A sibling moved, weighed (ADR 0382 §5): never fatal to what heard it. */ -async function siblingMoves(client: GiteaClient, repository: string, number?: number): Promise { - try { - if (await weighSiblings(client, gates, siblingNamed, repository, number)) keepSiblings(siblingsRecord, siblingNamed); - } catch (err) { - console.error(`[gitea] whether a sibling of ${repository}${number ? "#" + number : ""} moved could not be weighed — ${err instanceof Error ? err.message : err}`); - } -} - -// **This module is the one writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words, -// where the check is when a build machine takes it, and the verdict — each head's writes in one chain, the verdict last -// (gate.ts). A second writer elsewhere raced the verdict and could leave a pass reading pending. -const gates = new GateWriter({ - setCommitStatus: (owner, repo, sha, status) => (gitea as GiteaClient).setCommitStatus(owner, repo, sha, status), - headChecks: (owner, repo, sha) => (gitea as GiteaClient).headChecks(owner, repo, sha), -}); /** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are; and what * gitea_events says of them (webhook.ts). */ @@ -400,27 +283,41 @@ const registrations = new Registrations((verb, input) => broker().request(verb, // The failed steps the runner's step-ended said, and the heads that keep them (failedsteps.ts; design 47 §39, §475, §487, §135). const heldHeads = new Heads(); let reloadHeads: () => Promise = async () => {}; -const failedSteps = new FailedSteps(state("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit)); +// The merge calls, each written before its first merge (calls.ts; design 47 H §766). +const calls = new Calls(state("calls"), () => callRetentionDays(), (line) => console.log(`[gitea] ${line}`)); +// Each act of the seat git is taken once by its ask id, the ids kept in the state taken for ask-taken-bound (taken.ts; +// design 47 H2 §775). +const once = new Once(takenState(state(TAKEN_STATE), askTakenBoundMs(process.env, (line) => console.log(`[gitea] ${line}`))), + (line) => console.log(`[gitea] ${line}`)); +// At the start, every call whose merge-called is not said says it for what landed (§766). +const partials = new Partials(state("findings"), calls, (line) => console.log(`[gitea] ${line}`)); +void sayUnsaid(calls, seatPublish, (line) => console.log(`[gitea] ${line}`)).catch((err) => + console.error(`[gitea] the merge calls not said could not be said at the start — ${err instanceof Error ? err.message : err}`)); +const failedSteps = new FailedSteps(state("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit), + undefined, state("findings")); // The `seen` keys past their 30 days are deleted at the start, as on each step-ended (design 47 §581). void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys past 30 days could not be deleted at the start: ${err instanceof Error ? err.message : String(err)}`)); // gitea_events is served whether or not the forge is watched: it says so (novox/hq issue 729). The seat git's verbs are -// served here, beside the one writer of a head's statuses: the seat's status takes its turn on the head's chain, after the -// announcement's pending and a trunk's move, so a recheck's pending never lands over a later verdict (issue 456). +// served here. registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll), ...writeTools(writes), ...statusTools("gitea", "gitea_first_views", "gitea_first_view_again", followers, firstViews, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }), - ...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, statuses: gates, registered: () => registrations.written, judge: (head) => failedSteps.judge(head) }) : []), + ...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, registered: () => registrations.written, judge: (head) => failedSteps.judge(head), + watched: () => (registrations.current ? registrations.watched : null), calls, say: seatPublish, partials, once }) : []), + ...callTools(calls, partials, seatPublish, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }), + ...(gitea ? [mergedTool(gitea, calls)] : []), + tokenLeaseTool(processVaultAndLease().vault, processVaultAndLease().lease, + [process.env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT, process.env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT]), ...failedStepsTools(failedSteps, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); })]); /** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */ const actOnEvent = (client: GiteaClient, event: ForgeEvent): Promise => actOn(event, { getRepo: (o, r) => client.getRepo(o, r), getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise, - announceHead: (repo, pull) => announceHead(client, repo, pull as OpenOf), + announceUpdated: (repo, pull) => announceUpdated(client, repo, pull), announceMerge: (repo, pull) => announceMerge(client, repo, pull), announceClosed: (repo, pull) => announceClosed(client, repo, pull), - siblingMoves: (full, n) => siblingMoves(client, full, n), }); /** @@ -566,7 +463,11 @@ if (gitea) { const read = await readHeads(forge, registrations.watched, (line) => console.log(`[gitea] ${line}`)); await failedSteps.lost(heldHeads.replace(read.names, read.branches, read.pulls)); }; - void bindUntilHeld(`${RUNNER}.${RUNNER_EVENTS.stepEnded}`, () => on(`${RUNNER}.${RUNNER_EVENTS.stepEnded}`, (event) => failedSteps.stepEnded(event.body))); + // The runner's step-ended is said on step-ended... (the seat's definition); a source-only + // check's module is the registration's key source.. (design 47 H2 §815, H-A-408), one subject part as + // a key part escapes it (mesh-sdk keys.EscapeName), and its body names it whole. + const stepEnded = `${RUNNER}.${RUNNER_EVENTS.stepEnded}.*.*.*`; + void bindUntilHeld(stepEnded, () => on(stepEnded, (event) => failedSteps.stepEnded(event.body))); // A branch's head is read from the forge, never taken from the event (the seat's definition of branch-moved). void bindUntilHeld(`${GIT}.${GIT_EVENTS.branchMoved}`, () => on(`${GIT}.${GIT_EVENTS.branchMoved}`, async (event) => { const { repository, branch } = event.body; @@ -580,9 +481,8 @@ if (gitea) { } void registrations.start().then(() => reloadHeads()).catch(say); } - // Main takes no push and only the tools' account merges, in every repository, kept and not only when a token is - // minted: at the start and every ten minutes after, so a repository made later gets it too (issue 948, ADR 0398 §2). - // Only while the setting keep-main-rules is true (mainrules.ts); false, the default, leaves every repository's rule as set. + // Main's rule is put right only when the tools' account's token is minted, and only while the setting keep-main-rules is + // true (mainrules.ts); no timer keeps it (design 47 H §764, H-A-100). // The package seats' write token (packages-account.ts): minted at the start; after that renewed only when the Go // bundle that writes with it says the forge refused it (the finding PACKAGES_TOKEN_REFUSED), never on a timer. try { @@ -595,14 +495,13 @@ if (gitea) { } catch (err) { console.error(`[gitea] the package seats cannot write — ${err instanceof Error ? err.message : err}`); } - tick(mainRulesStep(keepMainRules(), () => GiteaAdmin.fromEnv().ensureMainMerges("novox"), (line) => console.log(line)), 600_000); tick(() => pollRepos(client), 60_000); // **No timer asks the forge for pull requests or merges** (issue 1422): the forge's events announce them. One pass over // every repository runs at the start and again once the receiver listens, so what happened while the module was away or // not yet listening is announced; passes run one at a time, a failed one is asked again a minute later. let passes: Promise = Promise.resolve(); const pass = (): Promise => (passes = passes.catch(() => {}).then(() => - startPass(async () => { await pollMerged(client); await passPulls(client); }, { retryMs: 60_000 }))); + pollMerged(client).catch((err) => console.error(`[gitea] the pass over every repository's merges failed — ${err instanceof Error ? err.message : err}`)))); void pass(); let catchUpAsked = false; catchUp = () => { diff --git a/modules/gitea/internal/forgehttp/forgehttp.go b/modules/gitea/internal/forgehttp/forgehttp.go index 3951ce342..b9d5a77e0 100644 --- a/modules/gitea/internal/forgehttp/forgehttp.go +++ b/modules/gitea/internal/forgehttp/forgehttp.go @@ -3,13 +3,12 @@ // // Two ways in, by what the manifest hands the bundle: // -// - **as the tools' account** (novox/hq ADR 0365 §2), when MESH_GITEA_TOKEN_FILE names the token the module -// keeps for it (token.ts mints it, for `mesh-tools`, and keeps it at 0600 with its scopes line beside it). A -// token whose scopes line does not say it is the tools' account's — one kept from before, the administrator's — -// is never sent: the call fails, saying so, until the module has minted the account's own. This bundle mints -// nothing; a token the forge rejects is renewed by the module's next call, and said here. +// - **as the tools' account or the packages account** (novox/hq ADR 0365 §2; design 47 H2 §808), with the account's +// token the module keeps in the vault as its own (token.ts mints it; vault.go reads it through the vault seat's +// `get` at start and at `secret-changed`). This bundle mints nothing; a token the forge rejects is renewed by the +// module's next call, and said here. // - **as the admin account**, whose password the vault delivered into a file this module owns (novox/hq ADR -// 0086), by basic authentication, when no token file is named. +// 0086), by basic authentication, when no token is given. // // A credential is read when a call is made and never logged, answered or put in an error. package forgehttp @@ -35,12 +34,12 @@ type Client struct { URL string // e.g. http://127.0.0.1:3000 User string PasswordFile string - // TokenFile, when set, is the tools' account's token (MESH_GITEA_TOKEN_FILE), sent instead of the admin login; - // Account the account its scopes line must name (MESH_GITEA_TOOLS_USER, default mesh-tools). - TokenFile string - Account string - HTTP *http.Client // when nil, a client with Timeout - Timeout time.Duration // one request's limit when HTTP is nil; 20 s when zero + // Token, when set, is the account's token as the vault holds it (vault.go), sent instead of the admin login; + // Account the account it is (MESH_GITEA_TOOLS_USER, default mesh-tools; MESH_GITEA_PACKAGES_USER for the writer). + Token *VaultToken + Account string + HTTP *http.Client // when nil, a client with Timeout + Timeout time.Duration // one request's limit when HTTP is nil; 20 s when zero } // ToolsAccount is the account the forge's tools act as when the manifest names none (token.ts, tools-account.ts). @@ -52,37 +51,35 @@ const ToolsAccount = "mesh-tools" const PackagesAccount = "mesh-packages" // WriterFromEnv is the package registry's write side as the manifest hands it to a bundle: the packages account's -// token (MESH_GITEA_PACKAGES_TOKEN_FILE, kept by the module beside the tools' token) and the names of the variables -// it left unset. Never the admin login: a bundle handed no writer's token writes nothing. -func WriterFromEnv() (Client, []string) { - c := Client{URL: strings.TrimRight(os.Getenv("MESH_GITEA_URL"), "/"), TokenFile: os.Getenv("MESH_GITEA_PACKAGES_TOKEN_FILE"), - Account: os.Getenv("MESH_GITEA_PACKAGES_USER")} - if c.Account == "" { - c.Account = PackagesAccount - } - var missing []string - for _, kv := range [][2]string{{"MESH_GITEA_URL", c.URL}, {"MESH_GITEA_PACKAGES_TOKEN_FILE", c.TokenFile}} { - if kv[1] == "" { - missing = append(missing, kv[0]) - } - } - return c, missing +// token, read from the vault (vault.go), and the names of the variables it left unset. Never the admin login. +func WriterFromEnv() (Client, []string, error) { + return accountFromEnv(os.Getenv("MESH_GITEA_PACKAGES_USER"), PackagesAccount) } -// FromEnv is the forge as the manifest hands it to a bundle, and the names of the variables it left unset. A bundle -// handed MESH_GITEA_TOKEN_FILE acts as the tools' account and needs no admin login. -func FromEnv() (Client, []string) { - if file := os.Getenv("MESH_GITEA_TOKEN_FILE"); file != "" { - c := Client{URL: strings.TrimRight(os.Getenv("MESH_GITEA_URL"), "/"), TokenFile: file, - Account: os.Getenv("MESH_GITEA_TOOLS_USER")} - if c.Account == "" { - c.Account = ToolsAccount - } - if c.URL == "" { - return c, []string{"MESH_GITEA_URL"} - } - return c, nil +// ToolsFromEnv is the forge as the tools' account, its token read from the vault (vault.go), and the names of the +// variables the manifest left unset; it needs no admin login. +func ToolsFromEnv() (Client, []string, error) { + return accountFromEnv(os.Getenv("MESH_GITEA_TOOLS_USER"), ToolsAccount) +} + +func accountFromEnv(account, fallback string) (Client, []string, error) { + if account == "" { + account = fallback } + token, err := TokenOf(account) + if err != nil { + return Client{}, nil, err + } + c := Client{URL: strings.TrimRight(os.Getenv("MESH_GITEA_URL"), "/"), Token: token, Account: account} + if c.URL == "" { + return c, []string{"MESH_GITEA_URL"}, nil + } + return c, nil, nil +} + +// FromEnv is the forge as the admin account, as the manifest hands it to a bundle, and the names of the variables it +// left unset. +func FromEnv() (Client, []string) { c := Client{ URL: strings.TrimRight(os.Getenv("MESH_GITEA_URL"), "/"), User: os.Getenv("MESH_GITEA_ADMIN_USER"), @@ -132,27 +129,10 @@ func (c *Client) password() (string, error) { return strings.TrimSpace(string(raw)), nil } -// token is the tools' account's token, refused unless its scopes line names that account. -func (c *Client) token() (string, error) { - raw, err := os.ReadFile(c.TokenFile) - if err != nil { - return "", fmt.Errorf("the token for %s is not kept yet (the module mints it): %w", c.Account, err) - } - line, err := os.ReadFile(c.TokenFile + ".scopes") - if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+c.Account) { - return "", fmt.Errorf("the token kept at %s is not %s's (novox/hq ADR 0365): the module mints that account's own at its next call; nothing was sent", c.TokenFile, c.Account) - } - token := strings.TrimSpace(string(raw)) - if token == "" { - return "", fmt.Errorf("the token kept at %s is empty; nothing was sent", c.TokenFile) - } - return token, nil -} - // authorize puts the bundle's credential on a request: the tools' token, or the admin login. func (c *Client) authorize(req *http.Request) error { - if c.TokenFile != "" { - token, err := c.token() + if c.Token != nil { + token, err := c.Token.Token() if err != nil { return err } @@ -212,7 +192,7 @@ func (c *Client) Send(ctx context.Context, method, path string, raw []byte, cont return nil, fmt.Errorf("the forge's answer to %s %s is larger than %d MiB and was not read whole", method, path, limit>>20) } switch { - case res.StatusCode == http.StatusUnauthorized && c.TokenFile != "": + case res.StatusCode == http.StatusUnauthorized && c.Token != nil: return nil, fmt.Errorf("the forge rejected %s's token for %s (401): the module mints it afresh; nothing was done: %w", c.Account, method+" "+path, &StatusError{method, path, res.StatusCode, "unauthorized"}) case res.StatusCode == http.StatusNotFound: diff --git a/modules/gitea/internal/forgehttp/vault.go b/modules/gitea/internal/forgehttp/vault.go new file mode 100644 index 000000000..3ed8dbeff --- /dev/null +++ b/modules/gitea/internal/forgehttp/vault.go @@ -0,0 +1,293 @@ +package forgehttp + +// The forge module's tokens as its Go bundles read them (design 47 H2 §808; H-A-422 (1), H-A-426): kept in the vault as +// the module's own, `module/gitea/`, written by the TypeScript bundle's minter through own-put, and read here +// through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at +// each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it. +// +// Until gitea runs as its own account (H-A-543), the vault refuses the tool runner's account these bundles are called +// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript +// bundle keeps it in under its state directory (MESH_GITEA_TOKEN_FILE for the tools' account, +// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, each with its scopes line beside it), and Follow says once +// at start which source each token came from. The fallback ends with H-A-543's delivery. + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/seal" +) + +// VaultGet is the vault seat's verb a token is read by, and SecretChanged the vault's event that a secret changed. +const ( + VaultGet = "seat:mesh-vault.get" + SecretChanged = "mesh-vault.secret-changed" +) + +// VaultName is the vault's name of an account's token (H-A-426). +func VaultName(account string) string { return "module/gitea/" + account } + +// Ask asks one seat verb and answers its reply (stdio.Ask). +type Ask func(address string, args any) (json.RawMessage, error) + +// Refusals are what the vault answers when it refuses the caller's account a module's own secret (mesh-vault's +// callerModule and its own-secret judgement): the only answers the token file is read after (H-A-564). +var Refusals = []string{"is no module's account", "handed only to an account of"} + +// refused is whether err is the vault refusing the caller's account. +func refused(err error) bool { + for _, r := range Refusals { + if strings.Contains(err.Error(), r) { + return true + } + } + return false +} + +// Sources of a token: the vault, or the file gitea's TypeScript bundle keeps (H-A-564). +const ( + SourceVault = "the vault" + SourceFile = "the file gitea keeps" +) + +// VaultToken is one account's token as this process holds it, read from the vault, or from File when the vault +// refuses the caller's account (H-A-564). +type VaultToken struct { + Account string + // File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none. + File string + // FileByDefault says File is DefaultStateDir's, the manifest naming none. + FileByDefault bool + ask Ask + keys seal.KeyPair + + mu sync.Mutex + token string + generation int + source string +} + +// NewVaultToken is an account's token read through ask, sealed to a key made for this process. +func NewVaultToken(account string, ask Ask) (*VaultToken, error) { + keys, err := seal.GenerateKeyPair() + if err != nil { + return nil, fmt.Errorf("no key to read %s's token with: %w", account, err) + } + return &VaultToken{Account: account, ask: ask, keys: keys}, nil +} + +// Load reads the account's token from the vault again; from File when the vault refuses the caller's account. +func (t *VaultToken) Load() error { + raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey}) + if err != nil { + if t.File != "" && refused(err) { + token, ferr := t.fromFile() + if ferr != nil { + return fmt.Errorf("the vault did not hand %s (%v), and %w", VaultName(t.Account), err, ferr) + } + t.mu.Lock() + t.token, t.generation, t.source = token, 0, SourceFile + t.mu.Unlock() + return nil + } + return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err) + } + var got struct { + Generation int `json:"generation"` + Sealed *seal.Box `json:"sealed"` + } + if err := json.Unmarshal(raw, &got); err != nil || got.Sealed == nil { + return fmt.Errorf("the vault answered no sealed %s", VaultName(t.Account)) + } + opened, err := seal.Open(*got.Sealed, t.keys.PrivateKey) + if err != nil { + return fmt.Errorf("%s does not open with this process's key: %w", VaultName(t.Account), err) + } + // The value holds the token and the scopes it was minted with (H-A-439); the minter judges the scopes, this reads the token. + var value struct { + Token string `json:"token"` + } + if err := json.Unmarshal([]byte(opened), &value); err != nil { + return fmt.Errorf("the vault's %s is not a token with its scopes: %w", VaultName(t.Account), err) + } + token := strings.TrimSpace(value.Token) + if token == "" { + return fmt.Errorf("the vault's %s is empty", VaultName(t.Account)) + } + t.mu.Lock() + t.token, t.generation, t.source = token, got.Generation, SourceVault + t.mu.Unlock() + return nil +} + +// fromFile is the token gitea's TypeScript bundle keeps in File, refused unless its scopes line names Account (as the +// bundle writes it: " for "). +func (t *VaultToken) fromFile() (string, error) { + raw, err := os.ReadFile(t.File) + if err != nil { + return "", fmt.Errorf("the token file gitea keeps for %s cannot be read: %w", t.Account, err) + } + line, err := os.ReadFile(t.File + ".scopes") + if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+t.Account) { + return "", fmt.Errorf("the token kept at %s is not %s's (its scopes line does not name it); nothing is sent", t.File, t.Account) + } + token := strings.TrimSpace(string(raw)) + if token == "" { + return "", fmt.Errorf("the token kept at %s is empty; nothing is sent", t.File) + } + return token, nil +} + +// Source is where the token held came from, SourceVault or SourceFile; "" when none is held. +func (t *VaultToken) Source() string { + t.mu.Lock() + defer t.mu.Unlock() + return t.source +} + +// Token is the token held; read from the vault when none is yet (the module mints it first). +func (t *VaultToken) Token() (string, error) { + t.mu.Lock() + token, source := t.token, t.source + t.mu.Unlock() + if source == SourceFile { + // gitea's TypeScript bundle mints into its file again on a refusal: the file is read at each call, as before C4. + return t.fromFile() + } + if token != "" { + return token, nil + } + if err := t.Load(); err != nil { + return "", fmt.Errorf("the token for %s is not kept yet (the module mints it): %w", t.Account, err) + } + t.mu.Lock() + defer t.mu.Unlock() + return t.token, nil +} + +// Generation is the vault's generation of the token held, 0 when none is held. +func (t *VaultToken) Generation() int { + t.mu.Lock() + defer t.mu.Unlock() + return t.generation +} + +// Changed takes one `secret-changed`: the token is read again when it names this account's; answers whether it did. +func (t *VaultToken) Changed(body []byte) (bool, error) { + var e struct { + Name string `json:"name"` + } + if err := json.Unmarshal(body, &e); err != nil { + return false, fmt.Errorf("%s is not a secret's change: %w", SecretChanged, err) + } + if e.Name != VaultName(t.Account) { + return false, nil + } + return true, t.Load() +} + +var ( + processTokens = map[string]*VaultToken{} + processTokensMu sync.Mutex +) + +// TokenOf is this process's one token of account, read through the runtime's seat calls. +func TokenOf(account string) (*VaultToken, error) { + processTokensMu.Lock() + defer processTokensMu.Unlock() + if t, ok := processTokens[account]; ok { + return t, nil + } + t, err := NewVaultToken(account, stdio.Ask) + if err != nil { + return nil, err + } + t.File, t.FileByDefault = TokenFile(account) + processTokens[account] = t + return t, nil +} + +// DefaultStateDir is gitea's runtime-state directory (the manifest's `${dir:mesh-state}/state`), where its TypeScript +// bundle keeps the token files, for a composition that hands the Go bundles no token file (gitea 0.1.316 hands them +// no variable naming that directory either; H-A-564). +const DefaultStateDir = "/var/lib/mesh/gitea/state" + +// TokenFile is the file the manifest names for account's token as gitea's TypeScript bundle keeps it (H-A-564): +// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, MESH_GITEA_TOKEN_FILE for the tools' account; when the +// variable is not handed, the file in DefaultStateDir, and byDefault says so. "" for any other account. +func TokenFile(account string) (file string, byDefault bool) { + packages := os.Getenv("MESH_GITEA_PACKAGES_USER") + if packages == "" { + packages = PackagesAccount + } + tools := os.Getenv("MESH_GITEA_TOOLS_USER") + if tools == "" { + tools = ToolsAccount + } + variable, name := "", "" + switch account { + case packages: + variable, name = "MESH_GITEA_PACKAGES_TOKEN_FILE", "packages-token" + case tools: + variable, name = "MESH_GITEA_TOKEN_FILE", "token" + default: + return "", false + } + if f := os.Getenv(variable); f != "" { + return f, false + } + return filepath.Join(DefaultStateDir, name), true +} + +// Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying +// through logf what it read and, once at start, from which source (never the token). It returns when the +// subscription ends. +func Follow(logf func(format string, args ...any), accounts ...string) error { + var held []*VaultToken + for _, a := range accounts { + t, err := TokenOf(a) + if err != nil { + return err + } + held = append(held, t) + } + <-stdio.Served() + Start(logf, held...) + return stdio.Subscribe(SecretChanged, func(e stdio.Envelope) error { + var errs []error + for _, t := range held { + if read, err := t.Changed(e.Body); err != nil { + errs = append(errs, err) + logf("%s changed and could not be read again: %v", VaultName(t.Account), err) + } else if read { + logf("read %s again at generation %d", VaultName(t.Account), t.Generation()) + } + } + return errors.Join(errs...) + }) +} + +// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token. +func Start(logf func(format string, args ...any), held ...*VaultToken) { + for _, t := range held { + switch err := t.Load(); { + case err != nil: + logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err) + case t.Source() == SourceFile: + how := "named by the manifest" + if t.FileByDefault { + how = "the default path, the manifest naming none" + } + logf("the vault refuses %s to this process's account, so %s's token is read from %s, %s (%s; H-A-564)", + VaultName(t.Account), t.Account, SourceFile, t.File, how) + default: + logf("read %s at generation %d from %s", VaultName(t.Account), t.Generation(), SourceVault) + } + } +} diff --git a/modules/gitea/internal/forgehttp/vault_test.go b/modules/gitea/internal/forgehttp/vault_test.go new file mode 100644 index 000000000..b89e1a6a7 --- /dev/null +++ b/modules/gitea/internal/forgehttp/vault_test.go @@ -0,0 +1,138 @@ +package forgehttp + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "git.novox.be/novox/mesh-sdk/go/seal" +) + +// H-A-564: until gitea runs as its own account, a Go bundle the vault refuses reads the token gitea's TypeScript +// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file. +func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) { + dir := t.TempDir() + keep := func(name, token, scopes string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if scopes != "" { + if err := os.WriteFile(p+".scopes", []byte(scopes+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + return p + } + tools := keep("token", "file-tools", "read:package,read:user,write:issue,write:repository for mesh-tools") + packages := keep("packages-token", "file-packages", "write:package for mesh-packages") + admins := keep("admins-token", "file-admin", "write:admin") + vaultHolds := func(token string) Ask { + return func(address string, args any) (json.RawMessage, error) { + a := args.(map[string]any) + value, _ := json.Marshal(map[string]any{"token": token}) + box, err := seal.Seal(string(value), a["public_key"].(string)) + if err != nil { + return nil, err + } + return json.Marshal(map[string]any{"generation": 3, "sealed": box}) + } + } + vaultSays := func(said string) Ask { + return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) } + } + notModule := vaultSays("novox.node-tools is no module's account (.), so it has no own secret here") + for _, c := range []struct { + name, account, file string + ask Ask + token, source, err string + }{ + {"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""}, + {"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""}, + {"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""}, + {"another module's account: the file", "mesh-tools", tools, + vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "file-tools", SourceFile, ""}, + {"the vault holds none: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"}, + {"no file named: the refusal stands", "mesh-tools", "", notModule, "", "", "no module's account"}, + {"a file whose scopes line names another account is not sent", "mesh-tools", admins, notModule, "", "", "is not mesh-tools's"}, + } { + t.Run(c.name, func(t *testing.T) { + v, err := NewVaultToken(c.account, c.ask) + if err != nil { + t.Fatal(err) + } + v.File = c.file + var said []string + Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v) + got, err := v.Token() + if c.err != "" { + if err == nil || !strings.Contains(err.Error(), c.err) { + t.Fatalf("token %q, error %v; want an error saying %q", got, err, c.err) + } + return + } + if err != nil || got != c.token || v.Source() != c.source { + t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source) + } + if len(said) != 1 || !strings.Contains(said[0], c.source) || strings.Contains(said[0], c.token) { + t.Fatalf("said %q: one line naming %q, never the token", said, c.source) + } + }) + } + // A token gitea mints into its file again is the one sent next. + v, _ := NewVaultToken("mesh-tools", notModule) + v.File = tools + Start(func(string, ...any) {}, v) + keep("token", "file-tools-2", "read:package for mesh-tools") + if got, _ := v.Token(); got != "file-tools-2" { + t.Fatalf("after gitea minted again, %q is sent", got) + } +} + +// H-A-564: the manifest's file for each account wins; without it, the file in gitea's runtime-state directory, said +// as the default. +func TestTheTokenFileOfAnAccountIsTheOneTheManifestNamesForItElseTheDefault(t *testing.T) { + type file struct { + path string + byDefault bool + } + for _, c := range []struct { + name string + tools, packs string + want map[string]file + }{ + {"named by the manifest", "/s/token", "/s/packages-token", map[string]file{ + "mesh-tools": {"/s/token", false}, "mesh-packages": {"/s/packages-token", false}, "other": {"", false}}}, + {"named by none: the default", "", "", map[string]file{ + "mesh-tools": {"/var/lib/mesh/gitea/state/token", true}, + "mesh-packages": {"/var/lib/mesh/gitea/state/packages-token", true}, "other": {"", false}}}, + } { + t.Run(c.name, func(t *testing.T) { + t.Setenv("MESH_GITEA_TOKEN_FILE", c.tools) + t.Setenv("MESH_GITEA_PACKAGES_TOKEN_FILE", c.packs) + for account, want := range c.want { + if p, d := TokenFile(account); (file{p, d}) != want { + t.Errorf("TokenFile(%s) = %q, %v; want %q, %v", account, p, d, want.path, want.byDefault) + } + } + }) + } + // The start line says the default as such. + dir := t.TempDir() + p := filepath.Join(dir, "token") + _ = os.WriteFile(p, []byte("t\n"), 0o600) + _ = os.WriteFile(p+".scopes", []byte("read:user for mesh-tools\n"), 0o600) + v, _ := NewVaultToken("mesh-tools", func(string, any) (json.RawMessage, error) { + return nil, errors.New("novox.node-tools is no module's account") + }) + v.File, v.FileByDefault = p, true + var said string + Start(func(f string, a ...any) { said = fmt.Sprintf(f, a...) }, v) + if !strings.Contains(said, "the default path") { + t.Fatalf("said %q, not that the file is the default", said) + } +} diff --git a/modules/gitea/internal/packageseats/holder.go b/modules/gitea/internal/packageseats/holder.go index f16b8a8f3..53ca97aa0 100644 --- a/modules/gitea/internal/packageseats/holder.go +++ b/modules/gitea/internal/packageseats/holder.go @@ -213,7 +213,9 @@ func (h *Holder) answer(transfer string, r parts.Received) Answer { return Answer{Transfer: transfer, Lacks: r.Lacks, Ended: r.Ended} } -// Publish is `publish` on seat for the proved caller: a package is one file, its digest the file's sha256. +// Publish is `publish` on seat for the proved caller: a package is one file, its digest the file's sha256. With its one +// part the file travels (design 51 *Publishing*); with none (the builder's publish again, design 47 G A-73, A-417) the +// version is said published when the forge holds it under the digest, and refused as not stored otherwise. func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) { if err := checkPublish(seat, p); err != nil { return Answer{}, err @@ -225,12 +227,25 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) { } else if ok { if d != p.Digest { reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest) + if len(p.Parts) == 0 { + // The builder's publish again names nothing the forge holds under that digest: refused as not stored (A-490, + // A-490a), the words its republish recognises. + reason = "not stored: " + reason + return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)) + } + // A one-part publish of a taken version is refused with an event only, as the registry would (the builder's "version taken"). return Answer{Transfer: p.Transfer, Ended: true}, h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason) } o := outcomeOf(p, "") o.Reference = Reference(p.Name, p.Version) return Answer{Transfer: p.Transfer, Ended: true}, h.Say(seat, EventPublished, o) } + // A publish with a version, a digest and no parts (design 47 G A-73, A-417): what the forge holds under the version has + // been said published above; nothing else travels, so the publish is refused as not stored, naming the digest. + if len(p.Parts) == 0 { + reason := fmt.Sprintf("not stored: the forge holds no %s of %s, so version %s names nothing", p.Digest, p.Name, p.Version) + return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)) + } // The transfer's name is the caller's own (the seat's contract): none would open the seat's one nameless transfer, // which key() still makes a valid id. if strings.TrimSpace(p.Transfer) == "" { @@ -377,8 +392,8 @@ func checkPublish(seat string, p Publish) error { return fmt.Errorf("publish: %s holds packages, not a %s", seat, p.Kind) case !strings.HasPrefix(p.Digest, "sha256:"): return fmt.Errorf("publish: digest %q is no sha256 digest", p.Digest) - case len(p.Parts) != 1 || p.Parts[0].Digest != p.Digest: - return errors.New("publish: a package is one file, its one part the package's digest") + case len(p.Parts) > 1 || (len(p.Parts) == 1 && p.Parts[0].Digest != p.Digest): + return errors.New("publish: a package is one file, its one part the package's digest, or no part at all") } return nil } diff --git a/modules/gitea/internal/packageseats/holder_test.go b/modules/gitea/internal/packageseats/holder_test.go index 9fd27c9b2..405b9e210 100644 --- a/modules/gitea/internal/packageseats/holder_test.go +++ b/modules/gitea/internal/packageseats/holder_test.go @@ -3,6 +3,7 @@ package packageseats import ( "crypto/sha256" "encoding/hex" + "encoding/json" "errors" "strings" "testing" @@ -10,6 +11,7 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/publishconformance" ) type memObjects map[string][]byte @@ -50,10 +52,21 @@ func (b builder) Recorded(_, _, _ string) (bool, string, error) { return b.ok, " // forge is the forge's package registry: seat -> name@version -> file. type forge struct { files map[string]map[string][]byte + digests map[string]string // seat+name@version -> a digest held with no bytes kept removed []string } +func (f *forge) holdDigest(seat, name, version, d string) { + if f.digests == nil { + f.digests = map[string]string{} + } + f.digests[seat+" "+name+"@"+version] = d +} + func (f *forge) Held(seat, name, version string) (string, bool, error) { + if d, ok := f.digests[seat+" "+name+"@"+version]; ok { + return d, true, nil + } b, ok := f.files[seat][name+"@"+version] if !ok { return "", false, nil @@ -150,6 +163,85 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) { } } }) + // Design 47 G A-490, A-490a: the publish contract's no-parts form, as every publish holder is held to it, per seat. + for _, seat := range []string{GoSeat, NpmSeat} { + t.Run("the publish conformance cases on "+seat, func(t *testing.T) { + publishconformance.Run(t, func(t *testing.T) publishconformance.Bed { + b := newBed(true) + return publishconformance.Bed{ + Hold: func(d string) { + b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d) + }, + Publish: func(name, version, digest string) publishconformance.Outcome { + a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest}) + o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err} + if len(b.said) > 0 { + o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason + } + return o + }} + }) + }) + } + // Design 47 G A-490j: the one-part publish a build module makes while it builds, as every publish holder is held to it, per + // seat, checked through the real Reserved against the builder's answer. + for _, seat := range []string{GoSeat, NpmSeat} { + t.Run("the publish while the build runs on "+seat, func(t *testing.T) { + publishconformance.RunReserved(t, func(t *testing.T) publishconformance.ReservedBed { + b := newBed(true) + whole := []byte("a package built now") + answer := "" + b.h.Builder = Reserved{Ask: func(string, any) (json.RawMessage, error) { + if answer == "" { + return nil, errors.New("no reserved version of mesh-sdk") + } + return json.RawMessage(answer), nil + }} + return publishconformance.ReservedBed{ + Reserve: func(r publishconformance.Reservation) { + d := map[publishconformance.Reservation]string{publishconformance.NoDigestYet: "", publishconformance.SameDigest: digest(whole), + publishconformance.OtherDigest: digest([]byte("another"))}[r] + answer = `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:` + seat + `","digest":"` + d + `"}]}` + }, + Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) }, + PublishWhole: func() publishconformance.Outcome { + a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole)) + if err == nil && !a.Ended { + _, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole) + } + o := publishconformance.Outcome{Err: err} + if len(b.said) > 0 { + o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason + } + return o + }} + }) + }) + } + // Design 47 G A-73, A-417: the builder's publish again names the version and the digest and no parts. + t.Run("a publish with a digest and no parts is published when held, refused as not stored when not", func(t *testing.T) { + for _, seat := range []string{NpmSeat, GoSeat} { + b := newBed(true) + none := pub("mesh-sdk", "0.1.0", file) + none.Parts = nil + a, err := b.h.Publish(seat, goBuild, none) + if err == nil || !strings.Contains(err.Error(), "not stored") || !strings.Contains(err.Error(), digest(file)) || !a.Ended { + t.Fatalf("%s: a publish of a digest the forge lacks answered %+v, %v; want refused as not stored, naming the digest", seat, a, err) + } + if len(b.said) != 1 || b.said[0].event != EventRefused || !strings.Contains(b.said[0].o.Reason, digest(file)) || !b.findings["publish-refused mesh-sdk@0.1.0"] { + t.Errorf("%s: said %+v, findings %v; want refused with the digest and the finding raised", seat, b.said, b.findings) + } + b = newBed(true) + if _, ok := b.forge.files[seat]; !ok { + b.forge.files[seat] = map[string][]byte{} + } + b.forge.files[seat]["mesh-sdk@0.1.0"] = file + a, err = b.h.Publish(seat, goBuild, none) + if err != nil || !a.Ended || len(a.Lacks) != 0 || len(b.said) != 1 || b.said[0].event != EventPublished || b.said[0].o.Reference != "mesh-sdk@0.1.0" { + t.Errorf("%s: a held digest answered %+v, %v, said %+v; want published", seat, a, err, b.said) + } + } + }) // Tools review F4 and running review F2's kind: a seat's incoming is read per seat with the cap its binding // carries; an open transfer is armed with its idle key, re-armed for the rest when it took a chunk since, and // dropped with its chunks when it had none for 24 hours; a cap from the binding refuses a transfer past it. diff --git a/modules/gitea/internal/packageseats/reserved.go b/modules/gitea/internal/packageseats/reserved.go index 15da4fad9..4373a31a5 100644 --- a/modules/gitea/internal/packageseats/reserved.go +++ b/modules/gitea/internal/packageseats/reserved.go @@ -9,7 +9,7 @@ import ( // Reserved is the holder's check of a publish against the builder's reservation (novox/hq design 47 §381, §478, §504): it asks the // seat mesh-builds' verb reserved with the publish's name and version, a package's name in its ecosystem, and accepts the publish -// only when that version is the one reserved and an artifact of it has the publish's digest. It reads no catalog and a publish gains +// only when that version is the one reserved and an artifact of it has the publish's digest or none yet (A-490j). It reads no catalog and a publish gains // no field. It is the Builder the holder's Check asks. type Reserved struct { // Ask is the runtime's request and reply over the bus (mesh-sdk stdio.Ask). @@ -34,7 +34,10 @@ func (r Reserved) Recorded(name, version, digest string) (bool, string, error) { return false, fmt.Sprintf("%s reserved %s for %s, not %s", a.Module, a.Version, name, version), nil } for _, art := range a.Artifacts { - if art.Digest == digest { + // An artifact whose build has not recorded its digest yet takes the publish: the builder records a build's digests only when + // the build ends, while the build module publishes during it (design 47 G §369, A-415, A-490j). Its record then meets what + // the holder holds: the published kept on the reservation marks the artifact, and a digest that differs fails the build. + if art.Digest == digest || art.Digest == "" { return true, "", nil } } diff --git a/modules/gitea/internal/packageseats/reserved_test.go b/modules/gitea/internal/packageseats/reserved_test.go index dff3f891f..ad81738ce 100644 --- a/modules/gitea/internal/packageseats/reserved_test.go +++ b/modules/gitea/internal/packageseats/reserved_test.go @@ -19,6 +19,7 @@ func reservedChecksAPublishAgainstTheReservation(t *testing.T) { }{ {name: "the reserved version and digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts","digest":"sha256:aa"}]}`, ok: true}, {name: "another artifact of it carries the digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:go"},{"artifact":"mesh-sdk:ts","digest":"sha256:aa"}]}`, ok: true}, + {name: "the artifact is not built yet", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts"}]}`, ok: true}, {name: "another digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts","digest":"sha256:bb"}]}`, why: "another digest than sha256:aa"}, {name: "another version reserved", answer: `{"module":"mesh-sdk","version":"0.1.20","artifacts":[]}`, why: "reserved 0.1.20 for @novox/mesh-sdk, not 0.1.19"}, {name: "the builder refused the name", err: errors.New("no entry carries @novox/mesh-sdk"), why: "no entry carries @novox/mesh-sdk"}, diff --git a/modules/gitea/internal/seatgit/doc.go b/modules/gitea/internal/seatgit/doc.go new file mode 100644 index 000000000..d718a85ea --- /dev/null +++ b/modules/gitea/internal/seatgit/doc.go @@ -0,0 +1,3 @@ +// Package seatgit holds the whole test of the seat git as the forge module serves it (novox/hq design 47 H §774, H-A-87): +// the module's TypeScript bundle run against a bus of the test alone and a fixture forge. It has no code of its own. +package seatgit diff --git a/modules/gitea/internal/seatgit/whole_integration_test.go b/modules/gitea/internal/seatgit/whole_integration_test.go new file mode 100644 index 000000000..f8bc98ae0 --- /dev/null +++ b/modules/gitea/internal/seatgit/whole_integration_test.go @@ -0,0 +1,808 @@ +//go:build integration + +package seatgit + +// The seat git whole, as the forge module serves it (novox/hq design 47 H §734 to §736, §766, §767, §774; acceptance tests +// 111, 114 and 115; H-A-61, H-A-87): the module's TypeScript bundle, built here and played over its real stdin and stdout +// as the node's tool runner plays it, its states key-value buckets of a nats-server of this test alone, its seat events +// published on that bus and read back from its stream, and the forge an httptest server. +// +// - At its start a call kept unsaid, stopped after the second of three merges, says one merge-called naming the two +// that landed, and is kept said (§766, test 111's stop case). +// - A runner's step-ended of a failed required step at a pull request's head and fingerprint is kept, and a merge call +// naming that head merges nothing and names the step (§735, test 114). +// - A call naming two pull requests in two repositories merges both, in order, and says one merge-called (§734, §736). +// - An hq pull request, of a source-only registration, whose Go checks failed is refused naming the step (H2 §815). +// - With the forge's store stopped a merge call answers away, and called again once it is back it lands (H2 §776). +// - A forge that refuses the second merge gives one merge-called with the first member and `refused`, and merge-partial +// raised; a later call landing the refused member clears it (§767, test 115). +// - No token is configured: the bundle mints the tools' account's token at the fixture forge with the admin's login, +// writes it through the vault seat's two-step sealed own-put and reads it through its sealed get, both answered +// here, and the forge holds one token for the account after, the old fixed-name token deleted (H2 §808, H-A-422, +// H-A-430 (1), H-A-453 (3)). + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + "git.novox.be/novox/mesh-sdk/go/seal" + "git.novox.be/novox/mesh-sdk/go/testbus" + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" + "golang.org/x/crypto/nacl/box" +) + +const within = 30 * time.Second + +// pull is one pull request of the fixture forge. +type pull struct { + repo, base, head string + number int + merged, refuse bool + merge string +} + +// forge is the fixture forge: the pull requests by `/#` and every merge asked. +type forge struct { + mu sync.Mutex + pulls map[string]*pull + merges []string + paths []string + // away is the forge's store stopped (§776): the API answers 503 and the version read names the store unavailable. + away bool + // admin is the admin's login, which mints (§808); tokens what each account holds; every other call is refused 401 + // unless it carries one of them. + admin string + tokens map[string][]forgeToken + nextID int +} + +// forgeToken is one access token the fixture forge minted. +type forgeToken struct { + ID int `json:"id"` + Name string `json:"name"` + sha1 string +} + +// authorized is the admin's basic login or a token the forge holds. +func (f *forge) authorized(r *http.Request) bool { + if u, p, ok := r.BasicAuth(); ok { + return u == f.admin && p == adminPassword + } + given := strings.TrimPrefix(r.Header.Get("Authorization"), "token ") + for _, held := range f.tokens { + for _, t := range held { + if given != "" && t.sha1 == given { + return true + } + } + } + return false +} + +// held answers the names of the tokens an account holds and their values. +func (f *forge) held(account string) (names, values []string) { + f.mu.Lock() + defer f.mu.Unlock() + for _, t := range f.tokens[account] { + names, values = append(names, t.Name), append(values, t.sha1) + } + return names, values +} + +// serveAdmin answers the admin API the mint uses: the admin's own read, the account and its team, and the account's +// tokens (mint, list, delete). False when the path is not one of them. +func (f *forge) serveAdmin(w http.ResponseWriter, r *http.Request) bool { + switch p := r.URL.Path; { + case p == "/api/v1/user": + _ = json.NewEncoder(w).Encode(map[string]any{"login": f.admin}) + case p == "/api/v1/admin/users" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + case p == "/api/v1/orgs/novox/teams" && r.Method == http.MethodGet: + _, _ = w.Write([]byte("[]")) + case p == "/api/v1/orgs/novox/teams" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":1}`)) + case strings.HasPrefix(p, "/api/v1/teams/1/members/"): + w.WriteHeader(http.StatusNoContent) + default: + m := regexp.MustCompile(`^/api/v1/users/([^/]+)/tokens(?:/(\d+))?$`).FindStringSubmatch(p) + if m == nil { + return false + } + account := m[1] + switch { + case r.Method == http.MethodPost: + var asked struct { + Name string `json:"name"` + } + _ = json.NewDecoder(r.Body).Decode(&asked) + for _, t := range f.tokens[account] { + if t.Name == asked.Name { + http.Error(w, `{"message":"access token name has been used already"}`, http.StatusUnprocessableEntity) + return true + } + } + f.nextID++ + t := forgeToken{ID: f.nextID, Name: asked.Name, sha1: fmt.Sprintf("%040x", 0xa0000+f.nextID)} + f.tokens[account] = append(f.tokens[account], t) + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"id": t.ID, "name": t.Name, "sha1": t.sha1}) + case r.Method == http.MethodGet: + if r.URL.Query().Get("page") != "1" { + _, _ = w.Write([]byte("[]")) + return true + } + _ = json.NewEncoder(w).Encode(f.tokens[account]) + case r.Method == http.MethodDelete: + kept := f.tokens[account][:0] + for _, t := range f.tokens[account] { + if fmt.Sprint(t.ID) != m[2] { + kept = append(kept, t) + } + } + f.tokens[account] = kept + w.WriteHeader(http.StatusNoContent) + } + } + return true +} + +// adminPassword is the admin's password the fixture forge takes, in the file the host would unseal it into. +const adminPassword = "admin-password" + +func (f *forge) serve(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + f.paths = append(f.paths, r.Method+" "+r.URL.Path) + if r.URL.Path == "/api/v1/version" { + if f.away { + http.Error(w, `{"message":"the database is unavailable"}`, http.StatusInternalServerError) + return + } + _, _ = w.Write([]byte(`{"version":"1.27.3"}`)) + return + } + if f.away { + http.Error(w, "Service Unavailable", http.StatusServiceUnavailable) + return + } + if !f.authorized(r) { + http.Error(w, `{"message":"token is required"}`, http.StatusUnauthorized) + return + } + if f.serveAdmin(w, r) { + return + } + m := regexp.MustCompile(`^/api/v1/repos/([^/]+/[^/]+)/pulls/(\d+)(/merge)?$`).FindStringSubmatch(r.URL.Path) + if m != nil { + p := f.pulls[m[1]+"#"+m[2]] + if p == nil { + http.Error(w, `{"message":"not found"}`, http.StatusNotFound) + return + } + if m[3] != "" && r.Method == http.MethodPost { + f.merges = append(f.merges, m[1]+"#"+m[2]) + if p.refuse { + http.Error(w, `{"message":"merge conflict"}`, http.StatusConflict) + return + } + p.merged, p.merge = true, strings.Repeat(fmt.Sprint(p.number%10), 40) + return + } + body := map[string]any{"number": p.number, "title": "t", "state": "open", "merged": p.merged, + "base": map[string]any{"ref": p.base}, "head": map[string]any{"ref": "feat", "sha": p.head}} + if p.merged { + body["state"], body["merge_commit_sha"] = "closed", p.merge + } + _ = json.NewEncoder(w).Encode(body) + return + } + if c := regexp.MustCompile(`^/api/v1/repos/[^/]+/[^/]+/git/commits/([0-9a-f]+)$`).FindStringSubmatch(r.URL.Path); c != nil { + _ = json.NewEncoder(w).Encode(map[string]any{"sha": c[1], "parents": []any{map[string]any{"sha": c[1]}}}) + return + } + http.Error(w, `{"message":"the fixture forge serves no `+r.URL.Path+`"}`, http.StatusNotFound) +} + +func (f *forge) merged() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.merges...) +} + +func (f *forge) asked(prefix string) bool { + f.mu.Lock() + defer f.mu.Unlock() + for _, p := range f.paths { + if strings.HasPrefix(p, prefix) { + return true + } + } + return false +} + +// runtime is the half of the conversation the tool runner plays for the bundle. +type runtime struct { + t *testing.T + in io.WriteCloser + js jetstream.JetStream + kvs map[string]jetstream.KeyValue + mu sync.Mutex + next int + wait map[string]chan json.RawMessage + // regs are what the seat mesh-catalog's registrations answers; subs the patterns the bundle subscribed. + regs []map[string]any + subs []string + // vault is the seat mesh-vault as this test answers it (§808, §822): the module's own secrets by name, and the + // own-put calls opened, each with the key its value is sealed to. + vault map[string]vaulted + puts map[string]openPut +} + +// openPut is an own-put call its first step opened: the name it puts and the key its value is sealed to. +type openPut struct { + name string + pub, priv *[32]byte +} + +// vaulted is one secret the test's vault keeps: its newest value and generation. +type vaulted struct { + value string + generation int +} + +// vaultAsk answers the seat mesh-vault's get, sealed to the asking process's key, and its two-step own-put, whose value +// comes sealed to the key the first step made (§822). +func (r *runtime) vaultAsk(key string, body json.RawMessage) (any, error) { + var b struct { + Name string `json:"name"` + PublicKey string `json:"public_key"` + Call string `json:"call"` + Sealed string `json:"sealed"` + } + _ = json.Unmarshal(body, &b) + r.mu.Lock() + defer r.mu.Unlock() + switch { + case key == "seat:mesh-vault.get": + v, ok := r.vault[b.Name] + if !ok { + return nil, fmt.Errorf("the vault holds no secret named %s", b.Name) + } + sealed, err := seal.Seal(v.value, b.PublicKey) + if err != nil { + return nil, err + } + return map[string]any{"generation": v.generation, "changed-at": time.Now().UTC().Format(time.RFC3339), "sealed": sealed}, nil + case b.Call == "": + pub, priv, err := box.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + r.next++ + call := fmt.Sprintf("put-%d", r.next) + r.puts[call] = openPut{name: b.Name, pub: pub, priv: priv} + return map[string]any{"call": call, "seal_to": base64.StdEncoding.EncodeToString(pub[:])}, nil + default: + put, ok := r.puts[b.Call] + if !ok { + return nil, fmt.Errorf("no own-put call %s is open", b.Call) + } + raw, err := base64.StdEncoding.DecodeString(b.Sealed) + if err != nil { + return nil, err + } + value, ok := box.OpenAnonymous(nil, raw, put.pub, put.priv) + if !ok { + return nil, fmt.Errorf("the own-put value of %s is not sealed to its call's key", b.Call) + } + // The module named by the caller's account, never by an argument: here always the forge module (§822). + name := "module/gitea/" + put.name + delete(r.puts, b.Call) + v := vaulted{value: string(value), generation: r.vault[name].generation + 1} + r.vault[name] = v + return map[string]any{"generation": v.generation}, nil + } +} + +func (r *runtime) subscribed(pattern string) bool { + r.mu.Lock() + defer r.mu.Unlock() + for _, s := range r.subs { + if s == pattern { + return true + } + } + return false +} + +func (r *runtime) say(m map[string]any) { + m["jsonrpc"] = "2.0" + raw, _ := json.Marshal(m) + r.mu.Lock() + defer r.mu.Unlock() + _, _ = r.in.Write(append(raw, '\n')) +} + +func (r *runtime) read(out io.Reader) { + sc := bufio.NewScanner(out) + sc.Buffer(make([]byte, 1<<20), 1<<24) + for sc.Scan() { + var m struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + Result json.RawMessage `json:"result"` + } + if json.Unmarshal(sc.Bytes(), &m) != nil { + continue + } + if m.Method == "" { + var id string + _ = json.Unmarshal(m.ID, &id) + r.mu.Lock() + ch := r.wait[id] + delete(r.wait, id) + r.mu.Unlock() + if ch != nil { + ch <- m.Result + } + continue + } + go r.answer(m.ID, m.Method, m.Params) + } +} + +// answer is the tool runner's answer to one method the bundle asks. +func (r *runtime) answer(id json.RawMessage, method string, params json.RawMessage) { + var p struct { + State string `json:"state"` + Key string `json:"key"` + Value json.RawMessage `json:"value"` + Subject string `json:"subject"` + Pattern string `json:"pattern"` + Body json.RawMessage `json:"body"` + ID string `json:"id"` + } + _ = json.Unmarshal(params, &p) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + result, err := func() (any, error) { + kv := r.kvs[p.State] + switch method { + case "mesh/subscribe": + r.mu.Lock() + r.subs = append(r.subs, p.Pattern) + r.mu.Unlock() + return map[string]any{}, nil + case "mesh/state.watch": + // The mint's lease is watched for its release (§808): its changes are delivered as the runtime delivers them. + if p.State == "token-lease" { + var watch string + _ = json.Unmarshal(id, &watch) + return map[string]any{}, r.watchState(kv, p.Key, watch) + } + return map[string]any{}, nil + case "mesh/publish", "mesh/seat.record": + return map[string]any{}, nil + case "mesh/capabilities": + return map[string]any{"words": []string{}}, nil + case "mesh/seat.publish": + // The seat's event, published on the bus under its id, as the runtime does. + _, err := r.js.Publish(ctx, p.Subject, p.Body, jetstream.WithMsgID(p.ID)) + return map[string]any{}, err + case "mesh/ask": + var a struct { + Key string `json:"key"` + } + _ = json.Unmarshal(params, &a) + switch a.Key { + case "seat:mesh-catalog.registrations": + return map[string]any{"registrations": r.regs}, nil + case "seat:mesh-hand-acts.hand-act": + return map[string]any{}, nil + case "seat:mesh-vault.get", "seat:mesh-vault.own-put": + return r.vaultAsk(a.Key, p.Body) + } + return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key) + case "mesh/state.get": + if kv == nil { + return nil, fmt.Errorf("the state %q is not declared", p.State) + } + e, err := kv.Get(ctx, p.Key) + if errors.Is(err, jetstream.ErrKeyNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + return map[string]any{"key": p.Key, "value": json.RawMessage(e.Value()), "revision": e.Revision()}, nil + case "mesh/state.create": + if kv == nil { + return nil, fmt.Errorf("the state %q is not declared", p.State) + } + rev, err := kv.Create(ctx, p.Key, p.Value) + if errors.Is(err, jetstream.ErrKeyExists) { + return nil, changed{err} + } + return map[string]any{"revision": rev}, err + case "mesh/state.put": + if kv == nil { + return nil, fmt.Errorf("the state %q is not declared", p.State) + } + rev, err := kv.Put(ctx, p.Key, p.Value) + return map[string]any{"revision": rev}, err + case "mesh/state.delete": + if kv == nil { + return nil, fmt.Errorf("the state %q is not declared", p.State) + } + return map[string]any{}, kv.Delete(ctx, p.Key) + case "mesh/state.keys": + if kv == nil { + return nil, fmt.Errorf("the state %q is not declared", p.State) + } + keys, err := kv.Keys(ctx) + if errors.Is(err, jetstream.ErrNoKeysFound) { + return []string{}, nil + } + return keys, err + case "mesh/state.info": + return map[string]any{"bytes": 0, "keys": 0, "max_bytes": 0}, nil + } + return nil, fmt.Errorf("the runtime offers no %s to this bundle", method) + }() + if id == nil { + return + } + if err != nil { + code := -32000 + if errors.As(err, new(changed)) { + code = -32010 + } + r.say(map[string]any{"id": id, "error": map[string]any{"code": code, "message": err.Error()}}) + return + } + r.say(map[string]any{"id": id, "result": result}) +} + +// watchState delivers each later change of one key of a state to the bundle's watch, as `mesh/state` requests naming +// the watch, a delete without its current value. +func (r *runtime) watchState(kv jetstream.KeyValue, key, watch string) error { + w, err := kv.Watch(context.Background(), key, jetstream.UpdatesOnly()) + if err != nil { + return err + } + r.t.Cleanup(func() { _ = w.Stop() }) + go func() { + for e := range w.Updates() { + if e == nil { + continue + } + change := map[string]any{"key": e.Key()} + if e.Operation() == jetstream.KeyValuePut { + change["current"] = map[string]any{"value": json.RawMessage(e.Value()), "revision": e.Revision()} + } + r.mu.Lock() + r.next++ + n := r.next + r.mu.Unlock() + r.say(map[string]any{"id": fmt.Sprintf("rt-watch-%d", n), "method": "mesh/state", "params": map[string]any{"watch": watch, "change": change}}) + } + }() + return nil +} + +// changed is the runtime's refusal of a create whose key has a value (mesh-sdk's CODE_CHANGED, -32010). +type changed struct{ error } + +// ask sends the bundle one request and answers its result. +func (r *runtime) ask(method string, params map[string]any) json.RawMessage { + r.t.Helper() + r.mu.Lock() + r.next++ + id := fmt.Sprintf("rt-%d", r.next) + ch := make(chan json.RawMessage, 1) + r.wait[id] = ch + r.mu.Unlock() + r.say(map[string]any{"id": id, "method": method, "params": params}) + select { + case raw := <-ch: + return raw + case <-time.After(within): + r.t.Fatalf("%s was not answered in %s", method, within) + } + return nil +} + +// mergePull calls the seat's verb as a proved caller and answers its result. +func (r *runtime) mergePull(pulls ...map[string]any) map[string]any { + r.t.Helper() + raw := r.ask("tools/call", map[string]any{"name": "git.merge-pull", "_meta": map[string]any{"mesh/caller": "shanks.claude-code"}, + "arguments": map[string]any{"by": "lead@shanks", "pulls": pulls}}) + var res struct { + Content []struct { + Text string `json:"text"` + } `json:"content"` + } + var out map[string]any + if json.Unmarshal(raw, &res) != nil || len(res.Content) == 0 || json.Unmarshal([]byte(res.Content[0].Text), &out) != nil { + r.t.Fatalf("merge-pull answered %s", raw) + } + return out +} + +func until(t *testing.T, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(within) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("within %s: %s did not happen", within, what) + } + select { + case <-time.After(20 * time.Millisecond): + } + } +} + +// said is every merge-called on the bus so far, by call. +func said(t *testing.T, js jetstream.JetStream) map[string]map[string]any { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + out := map[string]map[string]any{} + s, err := js.Stream(ctx, "SEAT_git_merge-called") + if err != nil { + t.Fatal(err) + } + info, err := s.Info(ctx) + if err != nil { + t.Fatal(err) + } + for seq := info.State.FirstSeq; seq <= info.State.LastSeq && info.State.Msgs > 0; seq++ { + m, err := s.GetMsg(ctx, seq) + if err != nil { + continue + } + var body map[string]any + _ = json.Unmarshal(m.Data, &body) + out[strings.TrimPrefix(m.Subject, "mesh.seat.git.event.merge-called.")] = body + } + return out +} + +func numbers(v any) []float64 { + var out []float64 + list, _ := v.([]any) + for _, m := range list { + n, _ := m.(map[string]any)["number"].(float64) + out = append(out, n) + } + return out +} + +// needTheModulesPackages ends the test NOT RUN, never failed, where what it builds and runs with is missing: node and npm +// on the PATH and the module's installed SDK package under node_modules. The Go integration level is given the tree +// without its npm packages and no network (issue 1960, H-A-294), as the Node build module's realMachine skips by name. +func needTheModulesPackages(t *testing.T, dir string) { + t.Helper() + for _, p := range []string{"node", "npm"} { + if _, err := exec.LookPath(p); err != nil { + t.Skipf("NOT RUN: no %s installed where this check runs; proven in a working copy of the module after npm install", p) + } + } + if _, err := os.Stat(filepath.Join(dir, "node_modules", "@novox", "mesh-sdk")); err != nil { + t.Skipf("NOT RUN: the forge module's npm packages are not installed in %s (%v); proven in a working copy of the module after npm install", dir, err) + } +} + +func TestTheSeatGitWholeOverARealBus(t *testing.T) { + dir, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + needTheModulesPackages(t, dir) + build := exec.Command("npm", "run", "build") + build.Dir = dir + if out, err := build.CombinedOutput(); err != nil { + t.Fatalf("the bundle does not build: %v\n%s", err, out) + } + + nc, err := nats.Connect(testbus.URL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(nc.Close) + js, _ := jetstream.New(nc) + ctx := context.Background() + // The seat's stream merge-called is kept on (the definition's keep); the template states as buckets. + if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "SEAT_git_merge-called", Subjects: []string{"mesh.seat.git.event.merge-called.*"}}); err != nil { + t.Fatal(err) + } + kvs := map[string]jetstream.KeyValue{} + for _, name := range []string{"bound", "announced", "findings", "first-views", "transfers", "idle", "failed-steps", "calls", "token-lease"} { + kv, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "gitea_" + name}) + if err != nil { + t.Fatal(err) + } + kvs[name] = kv + } + A, B, X, H := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("e", 40), strings.Repeat("f", 40) + // A call stopped after the second of three merges, kept and not said (§766). + stopped, _ := json.Marshal(map[string]any{"by": "lead@shanks", "account": "shanks.claude-code", "at": "2026-11-20T03:00:00Z", "said": false, + "members": []any{ + map[string]any{"repository": "novox/app", "number": 1, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("1", 40)}, + map[string]any{"repository": "novox/app", "number": 2, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("2", 40)}, + map[string]any{"repository": "novox/app", "number": 3, "branch": "main", "head": A, "state": "judged"}}}) + if _, err := kvs["calls"].Put(ctx, "call.00000000000000cc", stopped); err != nil { + t.Fatal(err) + } + + f := &forge{pulls: map[string]*pull{ + "novox/app#5": {repo: "novox/app", base: "main", head: A, number: 5}, + "novox/app#6": {repo: "novox/app", base: "main", head: X, number: 6}, + "novox/app#7": {repo: "novox/app", base: "main", head: A, number: 7}, + "novox/lib#9": {repo: "novox/lib", base: "main", head: B, number: 9, refuse: true}, + "novox/lib#10": {repo: "novox/lib", base: "main", head: B, number: 10}, + "novox/hq#11": {repo: "novox/hq", base: "main", head: H, number: 11}, + }} + // The forge holds the tools' account's token under its old fixed name, which the first mint replaces (H-A-430 (1)). + f.admin, f.nextID = "mesh-admin", 1 + f.tokens = map[string][]forgeToken{"mesh-tools": {{ID: 1, Name: "mesh-tools", sha1: strings.Repeat("0", 40)}}} + srv := httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(srv.Close) + + state := t.TempDir() + passwordFile := filepath.Join(state, "admin.secret") + if err := os.WriteFile(passwordFile, []byte(adminPassword+"\n"), 0o600); err != nil { + t.Fatal(err) + } + launch := `const sdk = await import("@novox/mesh-sdk/stdio"); await import("./dist/index.js"); await import("./dist/tools/index.js"); await sdk.serveRegisteredOverStdio("gitea");` + cmd := exec.Command("node", "--input-type=module", "-e", launch) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "MESH_SERVED_MODULE=gitea", "MESH_MODULE=gitea", "MESH_NODE=test", "MESH_GITEA_URL="+srv.URL, + "MESH_GITEA_ADMIN_USER=mesh-admin", "MESH_GITEA_ADMIN_PASSWORD_FILE="+passwordFile, "MESH_GITEA_STATE_DIR="+state, "MESH_GITEA_HOOK_PORT=0", "MESH_GITEA_CONFIG_FILE="+filepath.Join(state, "config.json")) + in, _ := cmd.StdinPipe() + out, _ := cmd.StdoutPipe() + cmd.Stderr = testLog{t} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = in.Close(); _ = cmd.Process.Kill(); _ = cmd.Wait() }) + rt := &runtime{t: t, in: in, js: js, kvs: kvs, wait: map[string]chan json.RawMessage{}, regs: []map[string]any{ + {"module": "app", "origin": "novox/app", "branches": []string{"main"}}, + {"module": "lib", "origin": "novox/lib", "branches": []string{"main"}}, + // A source-only registration (H2 §815): no module, one watched branch, its check a build seat's step. + {"origin": "novox/hq", "branches": []string{"main"}, "policy": map[string]any{"steps": map[string]any{"unit": "required"}}, + "check": map[string]any{"seat": "node-build-go", "step": "unit"}}}} + rt.vault, rt.puts = map[string]vaulted{}, map[string]openPut{} + go rt.read(out) + + // At the start the stopped call says one merge-called naming the two that landed (§766). + until(t, "the stopped call's merge-called at the start", func() bool { return said(t, js)["00000000000000cc"] != nil }) + if got := numbers(said(t, js)["00000000000000cc"]["members"]); fmt.Sprint(got) != "[1 2]" { + t.Fatalf("the stopped call names %v, not the two that landed", got) + } + until(t, "the stopped call kept said", func() bool { + e, err := kvs["calls"].Get(ctx, "call.00000000000000cc") + return err == nil && strings.Contains(string(e.Value()), `"said":true`) + }) + // The registrations are read, and the heads with them, before a merge is judged against them. + until(t, "the watched heads read after the registrations", func() bool { return f.asked("GET /api/v1/repos/novox/app/branches") }) + + // A failed required step at a head's fingerprint refuses that head (§735, test 114), heard on the module's consumer. + until(t, "the runner's step-ended followed", func() bool { return rt.subscribed("mesh-pipeline-runner.step-ended.*.*.*") }) + rt.ask("mesh/event", map[string]any{"envelope": map[string]any{"key": "mesh-pipeline-runner.step-ended.app.main." + X, "node": "test", + "body": map[string]any{"v": 1, "pipeline": "main.4", "module": "app", "branch": "main", "commit": X, "fingerprint": "fp-x", + "at": "2026-11-20T03:00:00Z", "result": map[string]any{"step": "unit", "status": "required", "outcome": "failed"}}}}) + refused := rt.mergePull(map[string]any{"repository": "novox/app", "number": 6, "head": X}) + members, _ := refused["members"].([]any) + if len(members) != 1 || members[0].(map[string]any)["state"] != "refused" || + !strings.Contains(fmt.Sprint(members[0].(map[string]any)["why"]), "the unit step of app failed in run main.4") { + t.Fatalf("a head at a failed required step's fingerprint answered %v", refused) + } + if got := f.merged(); len(got) != 0 { + t.Fatalf("merged %v", got) + } + + // An hq pull request whose Go checks fail is refused by merge-pull naming the failed step (H2 §815): the runner's + // step-ended of a source-only check names the registration's key as its module and the commit's root tree hash as its + // fingerprint (H-A-408), escaped as one part of its subject, judged as a module's. + rt.ask("mesh/event", map[string]any{"envelope": map[string]any{"key": "mesh-pipeline-runner.step-ended.source=2enovox=2ehq.main." + H, "node": "test", + "body": map[string]any{"v": 1, "pipeline": "main.5", "module": "source.novox.hq", "branch": "main", "commit": H, "fingerprint": strings.Repeat("7", 40), + "at": "2026-11-22T01:00:00Z", "result": map[string]any{"step": "unit", "status": "required", "outcome": "failed"}}}}) + hq := rt.mergePull(map[string]any{"repository": "novox/hq", "number": 11, "head": H}) + hqm, _ := hq["members"].([]any) + if len(hqm) != 1 || hqm[0].(map[string]any)["state"] != "refused" || + !strings.Contains(fmt.Sprint(hqm[0].(map[string]any)["why"]), "the unit step of source.novox.hq failed in run main.5") { + t.Fatalf("an hq head at a failed check answered %v", hq) + } + + // With the forge's store stopped, a merge call answers away, merging nothing (H2 §776); called again once the store is + // back, it lands (below). + f.mu.Lock() + f.away = true + f.mu.Unlock() + away := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B}) + if away["error-kind"] != "away" || away["part"] != "the forge's store" || len(f.merged()) != 0 { + t.Fatalf("a merge call with the forge's store stopped answered %v, merged %v", away, f.merged()) + } + f.mu.Lock() + f.away = false + f.mu.Unlock() + + // Two pull requests in two repositories merge, in order, and say one merge-called (§734, §736). + both := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B}) + call, _ := both["call"].(string) + until(t, "the merge-called of the two", func() bool { return said(t, js)[call] != nil }) + if got := numbers(said(t, js)[call]["members"]); fmt.Sprint(got) != "[7 10]" || fmt.Sprint(f.merged()) != "[novox/app#7 novox/lib#10]" { + t.Fatalf("the call of two said %v, merged %v", got, f.merged()) + } + + // The forge refuses the second merge: merge-called with the first and refused, merge-partial raised (§767, test 115). + partial := rt.mergePull(map[string]any{"repository": "novox/app", "number": 5, "head": A}, map[string]any{"repository": "novox/lib", "number": 9, "head": B}) + pc, _ := partial["call"].(string) + until(t, "the partial call's merge-called", func() bool { return said(t, js)[pc] != nil }) + body := said(t, js)[pc] + if fmt.Sprint(numbers(body["members"])) != "[5]" || fmt.Sprint(numbers(body["refused"])) != "[9]" { + t.Fatalf("the partial call said %v", body) + } + key := "delivery." + pc + ".merge-partial" + if e, err := kvs["findings"].Get(ctx, key); err != nil || !strings.Contains(string(e.Value()), `"severity":"urgent"`) { + t.Fatalf("merge-partial %s is not raised: %v", key, err) + } + // A later call landing the refused member clears it. + f.mu.Lock() + f.pulls["novox/lib#9"].refuse = false + f.mu.Unlock() + rt.mergePull(map[string]any{"repository": "novox/lib", "number": 9, "head": B}) + until(t, "merge-partial cleared by the later call", func() bool { + _, err := kvs["findings"].Get(ctx, key) + return errors.Is(err, jetstream.ErrKeyNotFound) + }) + + // No token was configured: the calls above ran on the token the bundle minted with the admin's login, wrote through + // the two-step sealed own-put and read through the sealed get; the forge holds one token for the account after, the + // one the vault keeps, and the old fixed-name token is gone (§808, H-A-430 (1)). + until(t, "the forge holds one token for the tools' account", func() bool { + names, _ := f.held("mesh-tools") + return len(names) == 1 + }) + names, values := f.held("mesh-tools") + rt.mu.Lock() + kept := rt.vault["module/gitea/mesh-tools"] + rt.mu.Unlock() + var opened struct { + Token string `json:"token"` + Scopes []string `json:"scopes"` + } + _ = json.Unmarshal([]byte(kept.value), &opened) + if fmt.Sprint(names) != "[mesh-tools-1]" || opened.Token != values[0] || kept.generation != 1 || len(opened.Scopes) == 0 { + t.Fatalf("the forge holds %v for the tools' account; the vault keeps generation %d of a token %t to it, scopes %v", + names, kept.generation, opened.Token == values[0], opened.Scopes) + } +} + +type testLog struct{ t *testing.T } + +func (w testLog) Write(p []byte) (int, error) { + defer func() { _ = recover() }() + w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n")) + return len(p), nil +} diff --git a/modules/gitea/kept.ts b/modules/gitea/kept.ts index 9288b8aa5..deba4f89d 100644 --- a/modules/gitea/kept.ts +++ b/modules/gitea/kept.ts @@ -6,11 +6,14 @@ // checks/readable every state another manifest reads to a readable announcement. export const KEPT: readonly { readonly name: string; readonly readable?: boolean }[] = [ { name: "announced" }, + { name: "calls" }, { name: "bound", readable: true }, { name: "findings", readable: true }, { name: "failed-steps" }, { name: "first-views" }, { name: "idle" }, + { name: "taken" }, + { name: "token-lease" }, { name: "transfers" }, ]; diff --git a/modules/gitea/mainrules.ts b/modules/gitea/mainrules.ts index e8ac249f7..7e51bcab8 100644 --- a/modules/gitea/mainrules.ts +++ b/modules/gitea/mainrules.ts @@ -3,8 +3,6 @@ // False, the default, leaves every repository's branch protection as people set it at the forge. import { readFileSync } from "node:fs"; -export const LEFT_AS_SET = "[gitea] main's rules are left as set at the forge (keep-main-rules is false)"; - /** The setting from the settings-merged config file the mesh delivers; absent, unreadable or not true is false. */ export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean { const file = env.MESH_GITEA_CONFIG_FILE; @@ -14,19 +12,3 @@ export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean { return v === true || v === "true"; } catch { return false; } } - -/** The 10-minute step: puts the rules right only when kept; else says once that they are left and writes nothing. */ -export function mainRulesStep(keep: boolean, put: () => Promise, say: (line: string) => void): () => Promise { - let said = false; - let touched = -1; - return async () => { - if (!keep) { - if (!said) say(LEFT_AS_SET); - said = true; - return; - } - const repos = await put(); - if (repos.length !== touched) say(`[gitea] main's rule is right in ${repos.length} repositories`); - touched = repos.length; - }; -} diff --git a/modules/gitea/mergecall.ts b/modules/gitea/mergecall.ts new file mode 100644 index 000000000..22326da15 --- /dev/null +++ b/modules/gitea/mergecall.ts @@ -0,0 +1,215 @@ +// **One merge call is a delivery's start and its group** (novox/hq design 47 H §734, §735; ADR 0682 §1, §2, §13; H-A-21, +// H-A-22, H-A-47): the seat git's `merge-pull` takes `pulls`, one or more members `{repository, number, head}`, and `by`, +// the caller as who@node, recorded beside the bus account the tool runner proved for the call. Every member is judged +// before any is merged: still the pull request's head, its base a watched branch, not merged already (refused +// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the +// module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged +// and the answer names every refused member and why; else the members are merged in the order the call names them. The +// verb answers once, at the call's end: `call` and each member's outcome. A member whose repository has no watched branch +// (no entry, or an empty set, in the registrations' watched branches) is the forge's business alone (H2 H-A-471 and its +// addendum): judged against nothing of the module graph, merged plainly in the order named, answered and kept merged with +// the note no delivery, and left out of merge-called, so it starts no delivery. A watched repository whose base is no +// watched branch stays refused. A member is merged plainly only from a view of the watched branches read since the last +// registration-changed heard (the second addendum): while the view is unread or stale, every member is refused, never +// merged with the note. + +import { randomBytes } from "node:crypto"; +import { UNPROVEN, callerOf } from "@novox/mesh-sdk/callers"; +import type { Call, MemberOutcome, MergePullAnswer } from "@novox/mesh-delivery-contracts-git"; +import type { GiteaClient } from "./client.js"; +import { Refused, checkName } from "./guard.js"; +import type { Judged } from "./failedsteps.js"; +import { keptMember, sayCall, type Calls, type Say } from "./calls.js"; +import type { Partials } from "./partials.js"; + +/** What a merge call reaches beside the forge's API. */ +export interface CallDeps { + /** Whether the first registrations were written: until then no merge is made (design 47 §95). */ + registered: () => boolean; + /** The watched branches the registrations name, by their origin repository `/`; null while they are not + * read since the last registration-changed heard (H-A-471, second addendum). */ + watched: () => ReadonlyMap> | null; + /** The failed `required` step that refuses a head, or null (failedsteps.ts). */ + judge: (head: string) => Promise; + /** A new call's id: 16 lowercase hex characters (H-A-24). */ + newCall?: () => string; + /** The state calls (calls.ts): the call is written before its first merge and as each member merges (§766). */ + calls?: Calls; + now?: () => Date; + /** Says a seat event on its subject under an id the bus keeps once (mesh-sdk runtime.seatPublish): merge-called (§736). */ + say?: Say; + /** The findings merge-partial (partials.ts; §767). */ + partials?: Partials; +} + +/** The forge's API a merge call uses. */ +export type CallForge = Pick; + +/** One member as the call names it, and as it was judged. */ +export interface Member { + repository: string; + owner: string; + repo: string; + number: number; + head: string; + /** The pull request's base, read at judging. */ + branch: string; + state: MemberOutcome["state"]; + commit?: string; + why?: string; + /** Set on a member merged plainly, its repository having no watched branch (H-A-471). */ + note?: string; + /** Its repository has no watched branch: judged against nothing of the module graph (H-A-471). */ + plain?: boolean; +} + +/** The note of a member merged plainly: it starts no delivery (H-A-471). */ +export const NO_DELIVERY = "no delivery: the repository has no watched branch"; + +/** Why every member is refused while the watched branches are unread or stale (H-A-471, second addendum). */ +export const NOT_READ = "the watched branches are not read yet"; + +const SHA = /^[0-9a-f]{40}$/; +export const CALL = /^[0-9a-f]{16}$/; + +/** A new call's id. */ +export const newCallId = (): string => randomBytes(8).toString("hex"); + +/** The members a call names, each checked, or the reason the call is refused whole. */ +export function membersOf(raw: unknown): Member[] { + if (!Array.isArray(raw) || raw.length === 0) throw new Refused("pulls names one or more members {repository, number, head}"); + const seen = new Set(); + return raw.map((p: any) => { + const parts = String(p?.repository ?? "").split("/"); + if (parts.length !== 2) throw new Refused(`repository ${JSON.stringify(p?.repository)} is not /`); + const owner = checkName("owner", parts[0]), repo = checkName("name", parts[1]); + const number = Number(p?.number); + if (!Number.isInteger(number) || number < 1) throw new Refused(`${JSON.stringify(p?.number)} is not a pull request's number`); + const head = String(p?.head ?? "").trim(); + if (!SHA.test(head)) throw new Refused("head is a commit's full 40-hex sha"); + const repository = `${owner}/${repo}`; + if (seen.has(`${repository}#${number}`)) throw new Refused(`${repository}#${number} is named twice`); + seen.add(`${repository}#${number}`); + return { repository, owner, repo, number, head, branch: "", state: "judged" as const }; + }); +} + +/** Why a member is refused at judging, or "" when it is judged. */ +async function judgeMember(forge: CallForge, deps: CallDeps, watched: ReadonlyMap>, m: Member): Promise { + const pull = await forge.getPullRequest(m.owner, m.repo, m.number); + m.branch = String(pull.base ?? ""); + if (pull.merged) { + if (pull.merge_commit_sha) m.commit = pull.merge_commit_sha; + return `already-merged: ${m.repository}#${m.number} was merged${pull.merge_commit_sha ? ` as ${pull.merge_commit_sha}` : ""}`; + } + if (pull.state !== "open") return `${m.repository}#${m.number} is closed`; + if (pull.head_sha !== m.head) { + return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`; + } + const branches = watched.get(m.repository); + // A repository of no module: no build-input fingerprint and no required step judge it (H-A-471). + if (!branches || branches.size === 0) { + m.plain = true; + return ""; + } + if (!branches.has(m.branch)) return `its base ${m.branch} is no watched branch`; + const failed = await deps.judge(m.head); + if (failed) { + return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`; + } + return ""; +} + +/** One member merged at its head, its merge commit read back; throws when the forge refused or did not name it. */ +async function mergeMember(forge: CallForge, m: Member): Promise { + await forge.mergePullRequest(m.owner, m.repo, m.number, "merge", true, m.head); + const merged = await forge.getPullRequest(m.owner, m.repo, m.number); + if (!merged.merge_commit_sha) throw new Error(`${m.repository}#${m.number} WAS merged, but the forge named no merge commit`); + // The merge is done once the forge named its commit: a read-back of its parents that fails is said, never a failed act. + try { + const parents = await forge.commitParents(m.owner, m.repo, merged.merge_commit_sha); + if (parents.length === 2 && parents[1] !== m.head) { + console.error(`[gitea] ${m.repository}#${m.number} WAS merged (${merged.merge_commit_sha}), but the forge merged ` + + `${parents[1].slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names (novox/hq issue 381)`); + } + } catch (err) { + console.error(`[gitea] ${m.repository}#${m.number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`); + } + return merged.merge_commit_sha; +} + +/** A member's outcome as the answer says it. */ +export const outcomeOf = (m: Member): MemberOutcome => ({ repository: m.repository, number: m.number, state: m.state, + ...(m.commit ? { commit: m.commit } : {}), ...(m.why ? { why: m.why } : {}), ...(m.note ? { note: m.note } : {}) }); + +/** merge-pull: one merge call (design 47 H §734, §735). */ +export async function mergeCall(forge: CallForge, args: Record, deps: CallDeps): Promise { + const by = String(args.by ?? "").trim(); + if (!/^[^\s@]+@[^\s@]+$/.test(by)) throw new Refused("by is the caller as who@node"); + const account = callerOf(args); + if (account === UNPROVEN) throw new Refused("the tool runner proved no caller account for this call, so nothing is merged"); + const members = membersOf(args.pulls); + // Until the first registrations are written no merge is made (design 47 §95). + if (!deps.registered()) throw new Refused("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written"); + const call = (deps.newCall ?? newCallId)(); + if (!CALL.test(call)) throw new Error(`the call's id ${JSON.stringify(call)} is not 16 lowercase hex characters`); + // One view judges the whole call; unread or stale, it judges no member (H-A-471, second addendum). + const watched = deps.watched(); + // Every member is judged before any is merged (§735). + let refused = false; + for (const m of members) { + const why = watched ? await judgeMember(forge, deps, watched, m) : NOT_READ; + if (why) { + m.state = "refused"; + m.why = why; + refused = true; + } + } + const now = deps.now ?? (() => new Date()); + // The call as kept (§766), its `at` the time of its write, then of its last merge (the event's `at`, §736). + let at = now().toISOString(); + const value = (said: boolean): Call => ({ by, account, at, members: members.map(keptMember), said }); + const keep = async (said: boolean) => { await deps.calls?.put(call, value(said), now()); }; + // A call refused at judging merged nothing and has nothing to say. + if (refused) { + await keep(true); + return { call, members: members.map(outcomeOf) }; + } + // Written before the first merge, and again as each member merges. + await keep(false); + // Then merged in the order the call names them; a member the forge refuses stops the call (§767). + for (const m of members) { + try { + m.commit = await mergeMember(forge, m); + m.state = "merged"; + if (m.plain) m.note = NO_DELIVERY; + at = now().toISOString(); + await keep(false); + } catch (err) { + m.state = "refused"; + m.why = `the forge refused the merge: ${err instanceof Error ? err.message : String(err)}`; + for (const rest of members.slice(members.indexOf(m) + 1)) { + rest.state = "refused"; + rest.why = `not merged: ${m.repository}#${m.number} before it was refused by the forge`; + } + await keep(false); + // Raised for the refused members, the landed ones delivered as any call's (§767). + await deps.partials?.raise({ ...value(false), call }); + break; + } + } + // Once its members are merged or refused, the call says merge-called, then is kept said (§736, §766). + if (deps.say) { + try { + await sayCall({ ...value(false), call }, deps.say); + await keep(true); + } catch (err) { + console.error(`[gitea] the merge call ${call} landed and its merge-called is not said yet; it is said at the next start — ${err instanceof Error ? err.message : err}`); + } + } + // A call that landed members clears every merge-partial whose refused members are now all landed (§767). + if (members.some((m) => m.state === "merged")) { + await deps.partials?.landed().catch((err) => console.error(`[gitea] the merge-partial findings could not be judged after the call ${call} — ${err instanceof Error ? err.message : err}`)); + } + return { call, members: members.map(outcomeOf) }; +} diff --git a/modules/gitea/module.json b/modules/gitea/module.json index 24da1123d..35d4a05f6 100644 --- a/modules/gitea/module.json +++ b/modules/gitea/module.json @@ -1,7 +1,11 @@ { "module": "gitea", "version": "0.1", + "class": "core", "moved": true, + "check-needs": [ + "node-build-node" + ], "requires": [ "postgres-database", "route", @@ -211,9 +215,16 @@ "trusted": true, "default": {} }, + "call-retention": { + "type": "number", + "description": "How many days the forge module keeps a merge call in its state calls (design 47 H §766): a call older than this is deleted when a new call is written, oldest first.", + "trusted": false, + "minimum": 1, + "default": 30 + }, "keep-main-rules": { "type": "boolean", - "description": "Whether the module keeps main's branch protection as the mesh wants it. True: every ten minutes, and at the start, main's rule in every repository of the organisation novox is put to no push and the tools' account alone merging, and each apply of the `repositories` value narrows the main rule of the repositories it lists, requiring no status. False (the default): the module changes no existing repository's branch protection, whoever set it at the forge, but takes away a required status it finds on a rule covering main, once (ADR 0534 §1); a repository listed in `repositories` that does not exist is still made, with its first protection.", + "description": "Whether the module keeps main's branch protection as the mesh wants it. True: when the tools' account's token is minted, main's rule in every repository of the organisation novox is put to no push and the tools' account alone merging, and each apply of the `repositories` value narrows the main rule of the repositories it lists, requiring no status. False (the default): the module changes no existing repository's branch protection, whoever set it at the forge, but takes away a required status it finds on a rule covering main, once (ADR 0534 §1); a repository listed in `repositories` that does not exist is still made, with its first protection.", "trusted": true, "default": false }, @@ -230,6 +241,27 @@ "default": [ "jschoubben" ] + }, + "ask-taken-bound": { + "type": "string", + "description": "How long the forge module keeps the id of an act of the seat git it took, as a duration such as 10m (design 47 H2 §775): an act given again with that id within it acts not again but answers what the forge holds of it. The largest caller's bound, the pipeline runner's ask-unanswered-bound, by default.", + "trusted": false, + "runtime": true, + "default": "10m" + }, + "token-ttl": { + "type": "string", + "description": "How old the forge module's token of an account may grow, as a duration such as 24h (design 47 H2 \u00a7808): a token the vault has kept longer than this, by its changed-at, is minted again, one process at a time, and the one it replaces is deleted at the forge.", + "trusted": false, + "runtime": true, + "default": "24h" + }, + "mint-lease": { + "type": "string", + "description": "How long one process of the forge module may hold the lease to mint a token, as a duration such as 60s (design 47 H2 \u00a7808): the lease key mint in the state token-lease lives this long, so a process that died holding it is replaced after it, and a process that finds it taken waits at most this long.", + "trusted": false, + "runtime": true, + "default": "60s" } }, "facts": { @@ -358,7 +390,8 @@ "takes-config": [ "url", "keep-main-rules", - "main-mergers" + "main-mergers", + "call-retention" ] }, { @@ -608,21 +641,51 @@ } ], "state": [ - "bound", - "announced", - "findings", + { + "name": "bound", + "max-mib": 8 + }, + { + "name": "announced", + "max-mib": 8 + }, + { + "name": "findings", + "max-mib": 8 + }, { "name": "first-views", - "history": 1 + "history": 1, + "max-mib": 8 + }, + { + "name": "transfers", + "max-mib": 8 }, - "transfers", { "name": "idle", - "key-ttl": true + "key-ttl": true, + "max-mib": 8 }, { "name": "failed-steps", - "history": 1 + "history": 1, + "max-mib": 8 + }, + { + "name": "calls", + "history": 1, + "max-mib": 8 + }, + { + "name": "taken", + "key-ttl": true, + "max-mib": 8 + }, + { + "name": "token-lease", + "key-ttl": true, + "max-mib": 1 } ], "reads": [ @@ -637,17 +700,20 @@ "seat:mesh-catalog.revision", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", - "seat:mesh-builds.reserved" + "seat:mesh-builds.reserved", + "seat:mesh-vault.own-put", + "seat:mesh-vault.get" ], "consumes": [ "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", - "mesh-pipeline-runner.step-ended", + "mesh-pipeline-runner.step-ended.*.*.*", "git.branch-moved", "git.pull-updated", "git.pull-closed", "git.pull-merged", - "mesh-conditions.findings-asked" + "mesh-conditions.findings-asked", + "mesh-vault.secret-changed" ], "streams": [ { @@ -658,7 +724,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } ], "objects": [ diff --git a/modules/gitea/package.json b/modules/gitea/package.json index 8ca41df32..85f0f46e9 100644 --- a/modules/gitea/package.json +++ b/modules/gitea/package.json @@ -16,6 +16,7 @@ }, "devDependencies": { "@types/node": "^22.0.0", + "tweetnacl": "1.0.3", "typescript": "^5.6.0" } } diff --git a/modules/gitea/packages-account.ts b/modules/gitea/packages-account.ts index ac0ec296b..bc264d44d 100644 --- a/modules/gitea/packages-account.ts +++ b/modules/gitea/packages-account.ts @@ -9,28 +9,25 @@ // makes `mesh-tools`; its password random, sent once and kept nowhere. // - **the team**: `mesh-packages` in the organisation that owns the registry, writing packages and nothing else: // no code, no issues, no pull requests, no administration. -// - **the token**: minted for the account by the administrator's login with the one scope `write:package`, kept at -// 0600 in the module's runtime state as `packages-token`, its scopes line beside it saying whose it is -// (MintedToken: one mint at a time across the bundle's processes, re-minted when the kept one is gone or other). +// - **the token**: minted for the account by the administrator's login with the one scope `write:package`, kept in +// the vault as the module's own `module/gitea/mesh-packages` (design 47 H2 §808, H-A-422, H-A-426; MintedToken: one +// mint at a time across the bundle's processes, a name per mint, re-minted when refused or older than token-ttl). // // The watcher mints it at its start (keepPackagesToken). No timer looks at it after that: the Go bundle mints nothing, // and when the forge refuses its write it raises the finding PACKAGES_TOKEN_REFUSED in the module's findings state; the // watcher, watching that key, looks again (a refused token is minted afresh) and clears the finding (renewOnRefusal). import { randomBytes } from "node:crypto"; -import { join } from "node:path"; -import { MintedToken } from "./token.js"; +import { adminFromEnv, MintedToken } from "./token.js"; import { TOOLS_ORG, type ToolsForge } from "./tools-account.js"; /** The account the package seats write as (internal/forgehttp PackagesAccount). */ export const PACKAGES_ACCOUNT = "mesh-packages"; -/** Its team in the registry's organisation, and the token's name in the account's list. */ +/** Its team in the registry's organisation, and the token's fixed name in the account's list before a name per mint. */ export const PACKAGES_TEAM = "mesh-packages"; export const PACKAGES_TOKEN_NAME = "mesh-packages"; /** The one scope the write side needs; reads go with the tools' token. */ export const PACKAGES_TOKEN_SCOPES: readonly string[] = ["write:package"]; -/** Where the token is kept in the module's runtime state (the manifest's MESH_GITEA_PACKAGES_TOKEN_FILE). */ -export const PACKAGES_TOKEN_FILE = "packages-token"; /** What the team grants: write on the organisation's packages, and no more. */ export const PACKAGES_TEAM_UNITS = { @@ -47,26 +44,19 @@ export async function setUpPackagesAccount(forge: ToolsForge, account = PACKAGES } /** The packages account's token, minted by the administrator's login from what the manifest hands the watcher. */ -export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env, log?: (line: string) => void): MintedToken { - const admin = env.MESH_GITEA_ADMIN_USER; - const passwordFile = env.MESH_GITEA_ADMIN_PASSWORD_FILE; - const stateDir = env.MESH_GITEA_STATE_DIR; - const missing = [ - admin ? null : "MESH_GITEA_ADMIN_USER", - passwordFile ? null : "MESH_GITEA_ADMIN_PASSWORD_FILE", - stateDir ? null : "MESH_GITEA_STATE_DIR", - ].filter((v): v is string => v !== null); - if (missing.length) throw new Error(`the package seats' write token cannot be minted: ${missing.join(", ")} not set by the manifest`); +export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env, log?: (line: string) => void, + over: Partial[0], "vault" | "lease" | "fetch" | "now">> = {}): MintedToken { + const { admin, passwordFile } = adminFromEnv(env, "the package seats' write token cannot be minted:"); const account = env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT; if (account === admin) throw new Error(`MESH_GITEA_PACKAGES_USER names the admin account "${admin}"; the package seats write as an account of their own`); + const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env); return new MintedToken({ - url, admin: admin!, passwordFile: passwordFile!, file: join(stateDir!, PACKAGES_TOKEN_FILE), account, - name: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log, + ...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log, setUp: async (password) => { const { GiteaAdmin } = await import("./client.js"); - await setUpPackagesAccount(new GiteaAdmin(url, admin!, password), account, () => randomBytes(24).toString("base64url")); + await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url")); }, - }); + } as ConstructorParameters[0]); } /** diff --git a/modules/gitea/partials.ts b/modules/gitea/partials.ts new file mode 100644 index 000000000..25d0ea0bd --- /dev/null +++ b/modules/gitea/partials.ts @@ -0,0 +1,78 @@ +// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; H-A-1, H-A-18, +// H-A-81): when the forge refuses a member after all were judged, the call stops merging and the forge module raises the +// finding `merge-partial`, scope `delivery`, id the call, naming each refused member, severity urgent, resolver operator, +// in its own state `findings`, which the condition keeper reads. It clears it when a later call lands every refused member +// (read from its own `calls`), or by its tool `forge_partial_clear` with `call` and `why`, written in the hand-act log. + +import type { State } from "@novox/mesh-sdk/state"; +import { findingKey } from "./catalog.js"; +import type { Calls, KeptCall } from "./calls.js"; + +export const MERGE_PARTIAL = "merge-partial"; +const SCOPE = "delivery"; + +/** The key of a call's merge-partial in the state findings. */ +export const partialKey = (call: string): string => findingKey(SCOPE, call, MERGE_PARTIAL); + +/** A member's name in a finding, `#`. */ +const named = (m: { repository: string; number: number }) => `${m.repository}#${m.number}`; + +/** The merge-partial of a call the forge refused a member of after judging, as the condition keeper reads it. */ +export function partialValue(c: KeptCall, observer = "gitea"): { key: string; value: Record } { + const key = partialKey(c.call); + const landed = c.members.filter((m) => m.state === "merged").map(named); + const refused = c.members.filter((m) => m.state === "refused"); + const summary = `the merge call ${c.call} by ${c.by} landed ${landed.length ? landed.join(", ") : "none"} and not ` + + refused.map((m) => `${named(m)} (${m.why ?? "refused"})`).join(", "); + return { key, value: { + v: 1, key, kind: MERGE_PARTIAL, subject: { scope: SCOPE, id: c.call }, severity: "urgent", resolver: "operator", summary, + headline: `A merge call landed in part: ${refused.map(named).join(", ")} not merged`, + explanation: `The forge refused ${refused.map(named).join(", ")} after every member of the merge call ${c.call} was judged, so ` + + `the repositories stand half-merged. A later merge call that lands them clears this, or forge_partial_clear with why.`, + resolved: "", evidence: [{ at: c.at, said: summary }], source: `${observer}.${MERGE_PARTIAL}`, observer, at: c.at, + } }; +} + +export class Partials { + constructor(private readonly findings: State, private readonly calls: Calls, + private readonly log: (line: string) => void = () => {}) {} + + /** Raises merge-partial for a call the forge refused a member of after judging. */ + async raise(c: KeptCall): Promise { + const f = partialValue(c); + await this.findings.put(f.key, f.value); + this.log(`merge-partial raised: ${String(f.value.summary)}`); + } + + /** The calls whose merge-partial is held, newest first. */ + async held(): Promise { + const out: KeptCall[] = []; + for (const c of await this.calls.all()) if ((await this.findings.get(partialKey(c.call)))?.value) out.push(c); + return out; + } + + /** After a call landed members: every held merge-partial whose refused members a later call landed, each, is cleared. + * Answers the calls cleared. */ + async landed(): Promise { + const all = await this.calls.all(); // newest first + const cleared: string[] = []; + for (const [i, c] of all.entries()) { + if (!(await this.findings.get(partialKey(c.call)))?.value) continue; + const later = new Set(all.slice(0, i).flatMap((x) => x.members.filter((m) => m.state === "merged").map(named))); + const refused = c.members.filter((m) => m.state === "refused").map(named); + if (refused.every((r) => later.has(r))) { + await this.findings.delete(partialKey(c.call)); + cleared.push(c.call); + this.log(`merge-partial of ${c.call} cleared: a later call landed ${refused.join(", ")}`); + } + } + return cleared; + } + + /** Clears one call's merge-partial by hand (forge_partial_clear); answers whether one was held. */ + async clear(call: string): Promise { + const held = !!(await this.findings.get(partialKey(call)))?.value; + if (held) await this.findings.delete(partialKey(call)); + return held; + } +} diff --git a/modules/gitea/pulls.ts b/modules/gitea/pulls.ts index 16a011834..364173ac8 100644 --- a/modules/gitea/pulls.ts +++ b/modules/gitea/pulls.ts @@ -1,15 +1,5 @@ -// A pull request's merge check (novox/hq to-be 45 §9): what the forge's announcer says when a pull -// request's head moves, and the status contexts the check is kept under. -// -// **Before merge, never after.** Each new head of an open pull request is announced as `pull.updated`, and the mesh -// checks it against every machine of its facts before it merges. The verdict is the checker's `mesh/check`, which this -// module writes from the checker's owed state (check.ts); the controller's `checked`, which once set the two older -// statuses, is no event any more (ADR 0571 clause 13). -// -// Pure functions here, so they are tested without a forge. - -import type { GiteaPull, GiteaRepo } from "./client.js"; -import { movedSince } from "./client.js"; +// The status contexts the forge's protections named for a merge check, read by the account's writes (writes.ts) to take +// them off a protection: no merge check is asked, weighed or written any more (design 47 H §764; H-A-28, H-A-100). /** The status context a merge check's gate is kept under: one per commit, the newest replacing the last. */ export const CHECK_CONTEXT = "mesh/merge-gate"; @@ -20,83 +10,3 @@ export const REPO_CHECK_CONTEXT = "mesh/repo-check"; /** The one status main requires (novox/hq ADR 0447 §1, issue 1301): the checker's verdict, written by this module from the * checker's owed state (check.ts, ADR 0521). Its line names the head and the trunk commit it judged: "pass on …". */ export const CHECK_STATUS = "mesh/check"; - -/** The statuses a branch's rule requires, from the rule the forge applies to it: none when it is unprotected or checks - * no status; undefined when the rule could not be read. */ -export function requiredOf(rule: { enable_status_check?: boolean; status_check_contexts?: string[] | null } | null | undefined): string[] | undefined { - if (rule === undefined) return undefined; - if (!rule || !rule.enable_status_check) return []; - return (rule.status_check_contexts ?? []).filter(Boolean); -} - -/** - * **The controller's statuses are written only where a base still requires them** (issue 1301; ADR 0503 §3, §5): of - * mesh/merge-gate and mesh/repo-check, those the base requires — hq's mesh/repo-check alone once the forge requires - * mesh/check everywhere else, so no mesh/merge-gate stands on a head that nothing will set. A base whose rule could not - * be read keeps both, as before: a status nothing requires blocks nothing, and one that is required is never left out. - */ -export function maintained(required: string[] | undefined): string[] { - const both = [CHECK_CONTEXT, REPO_CHECK_CONTEXT]; - return required === undefined ? both : both.filter((c) => required.includes(c)); -} - -/** Whether mesh/merge-gate is written on a head of this base (maintained). */ -export function writesGate(required: string[] | undefined): boolean { - return maintained(required).includes(CHECK_CONTEXT); -} - -/** - * The pending words a head's merge check is announced with (novox/hq issue 446): where the check is, and since when, - * in the time the operator reads. They stood as "the mesh is mapping this head onto its module graph" for the whole - * check — the few seconds the controller maps the head and then the queue wait and the build — and readers took the - * forge for lagging (issue 423). The controller maps and queues the check in seconds, so from the announcement it waits - * in the build queue; mesh-delivery says "building on since …" when a build machine takes it. - */ -export function pendingWords(announced: Date): string { - const two = (n: number) => String(n).padStart(2, "0"); - return `waiting in the build queue since ${two(announced.getHours())}:${two(announced.getMinutes())}`; -} - -/** The heads already announced, keyed by `headKey`, so a restart announces nothing twice. */ -export type Announced = Record; - -/** The key a pull request's announced head is kept under: `owner/repo#number@base`. The base is in it because a pull - * request retargeted keeps its head, and a head judged into one base is not judged into another (issue 1422, de-spiegel #6). */ -export function headKey(full: string, number: number, base?: string): string { - return `${full}#${number}@${base ?? ""}`; -} - -/** Which open pull requests have a head not yet announced. A pull request merged or closed is not - * open and is never asked about. */ -export function headsToAnnounce(full: string, pulls: GiteaPull[], announced: Announced): GiteaPull[] { - return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[headKey(full, p.number, p.base)] !== p.head_sha); -} - -/** A pull request the forge found updated, by its repository: what `searchOpenPulls` answers. */ -export interface PullSeen { - owner: string; - name: string; - updated_at?: string; -} - -/** **The repositories a pass looks at** (novox/hq issue 347): every one that moved since the floor, every one - * holding a pull request updated since the floor — opening, reopening or retargeting a pull request moves its own - * update time and not its repository's — and every one on a sweep or the first pass. */ -export function reposToLook(repos: GiteaRepo[], floor: string, pulls: PullSeen[], sweep: boolean): GiteaRepo[] { - if (sweep || !floor) return repos; - const moved = new Set(movedSince(repos, floor).map((r) => r.full_name)); - const at = Date.parse(floor); - for (const p of pulls) { - if (!p.updated_at || !(Date.parse(p.updated_at) < at)) moved.add(`${p.owner}/${p.name}`); - } - return repos.filter((r) => moved.has(r.full_name)); -} - -export function clipped(d: string): string { - d = d.replace(/\s+/g, " ").trim(); - return d.length > 140 ? d.slice(0, 139) + "…" : d; -} - -/** What a group member's gate says while the group's composed check is the one that judges it: the member's own check can say - * nothing more of it, so asking that check again brings no verdict that names a trunk (novox/hq issue 1106). */ -export const WAITS_FOR_COMPOSED = "waits for its group's composed check"; diff --git a/modules/gitea/registrations.ts b/modules/gitea/registrations.ts index 3d8f5828d..f3eb77346 100644 --- a/modules/gitea/registrations.ts +++ b/modules/gitea/registrations.ts @@ -4,11 +4,17 @@ // two ways, both through the seat `mesh-catalog`: its verb `registrations` asked at the start (a restart after the first // registrations were written), and its event `registration-changed` (the first being written, or heard again from the // seat's kept stream). Neither is the holder's state or a module named. +// +// **A plain merge needs a view read since the last change heard** (design 47 H2 H-A-471, second addendum): the holder keeps +// the time of its last read of the watched branches and of the last registration-changed it heard; the view is current only +// when a read asked after that change has answered. A read that fails is said and asked again with a growing wait until it +// answers, so an unread view is never taken as "no watched branch". import { seat as CATALOG, verbs as CATALOG_VERBS, events as CATALOG_EVENTS, type RegistrationChangedEvent, type RegistrationsAnswer, type RegistrationsInput, } from "@novox/mesh-delivery-contracts-mesh-catalog"; +import { bindWait } from "./bind.js"; /** The seat verb asked, as the manifest's `invokes` names it. */ export const REGISTRATIONS_VERB = `seat:${CATALOG}.${CATALOG_VERBS.registrations}`; @@ -18,8 +24,18 @@ export const REGISTRATION_CHANGED_EVENT = `${CATALOG}.${CATALOG_EVENTS.registrat export class Registrations { private first = false; private byRepository = new Map>(); + /** The registration-changed events heard; the count a read was asked at, once it answered (-1: never read). */ + private changes = 0; + private readAtChange = -1; + /** The reads asked, and the latest whose answer is the view (an older answer landing later is not taken). */ + private asked = 0; + private applied = 0; + private lastRead?: Date; + private lastChange?: Date; constructor(private readonly ask: (verb: string, input: RegistrationsInput) => Promise, - private readonly log: (line: string) => void = () => {}) {} + private readonly log: (line: string) => void = () => {}, + private readonly sleep: (ms: number) => Promise = (ms) => new Promise((r) => setTimeout(r, ms)), + private readonly now: () => Date = () => new Date()) {} /** Whether the first registrations are written: the one fact the merge switches on. */ get written(): boolean { @@ -31,6 +47,19 @@ export class Registrations { return this.byRepository; } + /** Whether the watched branches were read since the last registration-changed heard (H-A-471, second addendum). */ + get current(): boolean { + return this.readAtChange === this.changes; + } + + /** The time the last read that answered was asked, and of the last registration-changed heard. */ + get readAt(): Date | undefined { + return this.lastRead; + } + get changedAt(): Date | undefined { + return this.lastChange; + } + /** One `registration-changed`: the first registration written, however many were before this module started. */ hear(ev: RegistrationChangedEvent | undefined): void { if (!ev || typeof ev.module !== "string" || ev.module === "") { @@ -38,25 +67,40 @@ export class Registrations { } if (!this.first) this.log(`the first registration is written (${ev.module}); merge-pull merges from here`); this.first = true; + this.changes++; + this.lastChange = this.now(); } /** The start's first view, asked again after each `registration-changed`: any registration held is the first written, and its - * watched branches are read. A failed ask is said and left to the event. */ + * watched branches are read. A failed ask is said and asked again with a growing wait until it answers (H-A-471, second + * addendum); until then no member is merged plainly. */ async start(): Promise { - try { - let a: unknown = await this.ask(REGISTRATIONS_VERB, {}); - if (typeof a === "string") a = JSON.parse(a); - const r = (a as RegistrationsAnswer | undefined)?.registrations; - if (!Array.isArray(r)) throw new Error(`${REGISTRATIONS_VERB} answered no registrations: ${JSON.stringify(a ?? null).slice(0, 200)}`); - const by = new Map>(); - for (const x of r) for (const b of x.branches ?? []) (by.get(x.origin) ?? by.set(x.origin, new Set()).get(x.origin)!).add(b); - this.byRepository = by; - if (r.length > 0) { - this.first = true; - this.log(`${r.length} registrations are held; merge-pull merges`); + for (let attempt = 1; ; attempt++) { + const at = this.changes, seq = ++this.asked, askedAt = this.now(); + try { + let a: unknown = await this.ask(REGISTRATIONS_VERB, {}); + if (typeof a === "string") a = JSON.parse(a); + const r = (a as RegistrationsAnswer | undefined)?.registrations; + if (!Array.isArray(r)) throw new Error(`${REGISTRATIONS_VERB} answered no registrations: ${JSON.stringify(a ?? null).slice(0, 200)}`); + if (seq < this.applied) return; + const by = new Map>(); + for (const x of r) for (const b of x.branches ?? []) (by.get(x.origin) ?? by.set(x.origin, new Set()).get(x.origin)!).add(b); + this.byRepository = by; + this.applied = seq; + this.readAtChange = at; + this.lastRead = askedAt; + if (attempt > 1) this.log(`the registrations are read after ${attempt} attempts`); + if (r.length > 0) { + this.first = true; + this.log(`${r.length} registrations are held; merge-pull merges`); + } + return; + } catch (err) { + const wait = bindWait(attempt); + this.log(`the registrations could not be read: ${err instanceof Error ? err.message : String(err)}; ` + + `no member is merged plainly until they are, asked again in ${wait / 1000}s`); + await this.sleep(wait); } - } catch (err) { - this.log(`the registrations could not be read: ${err instanceof Error ? err.message : String(err)}; merge-pull waits for registration-changed`); } } } diff --git a/modules/gitea/seat.ts b/modules/gitea/seat.ts index 1c0c97124..5eef8308b 100644 --- a/modules/gitea/seat.ts +++ b/modules/gitea/seat.ts @@ -7,11 +7,12 @@ // // **A failed read answers an error, never an empty answer**: the forge's 404 is the kind `not-found`, its refusal (another // 4xx, or a refusal of this holder) the kind `refused`, a forge that failed or did not answer the kind `failed`; an empty list or an absent file is answered -// only when the forge said so. +// only when the forge said so. A 401, 502, 503 or connection fault whose version read fails, or names the forge's store +// unavailable, is the kind `away` (design 47 H2 §776; failureOf). // -// **The acts carry the caller's id** (status, comment, view, note, merge-pull): an id the pull request or the note already -// holds is answered `held` and nothing is done again; `merge-pull` merges the head the caller names, only into a base -// whose protection refuses a push, and refuses a head at whose fingerprint a run failed a `required` step (design 47 §39, §314). +// **The acts carry the caller's id** (status, comment, view, note): an id the pull request or the note already holds is +// answered `held` and nothing is done again. `merge-pull` is one merge call of one or more pull requests, every member +// judged before any is merged, no branch protection judged (mergecall.ts; design 47 H §734, §735; ADR 0682 §13). import type { ToolDefinition } from "@novox/mesh-sdk/tools"; import { @@ -21,11 +22,18 @@ import { type TagAnswer, type TagsAnswer, type TreesAnswer, type ViewAnswer, } from "@novox/mesh-delivery-contracts-git"; import type { CommitStatus, GiteaClient, GiteaComment, GiteaPull } from "./client.js"; -import { MAX_FILE_BYTES } from "./client.js"; +import { DirectoryNotInTree, MAX_FILE_BYTES } from "./client.js"; import { containedFrom, newestByContext } from "./checks.js"; import { Refused, checkName } from "./guard.js"; -import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js"; +import { AdminRefused } from "./token.js"; +import { awayAnswer } from "@novox/mesh-sdk/callers"; +import { appendNote, noteHolds, viewBody, viewComment, type Runner } from "./delivery.js"; import type { Judged } from "./failedsteps.js"; +import { mergeCall, membersOf } from "./mergecall.js"; +import type { Calls, Say } from "./calls.js"; +import type { Partials } from "./partials.js"; +import type { Once } from "./taken.js"; +import { askIdOf } from "@novox/mesh-sdk/callers"; /** The verbs of the seat, in its definition's order. */ export const VERBS: readonly string[] = Object.values(GIT_VERBS); @@ -37,22 +45,26 @@ export const TAGS_PAGE = 50; * is the manifest's container's; no variable names it (a MESH_* word nothing sets is refused, checks/environment). */ export const FORGE_CONTAINER = "gitea"; -/** The writer every status of a head takes its turn on (gate.ts): the seat's status lands after every write of the head - * already asked for, so a recheck's pending never lands over a later verdict (novox/hq issue 456). */ -export interface HeadStatuses { - status(owner: string, repo: string, sha: string, status: CommitStatus): Promise; -} - -/** What the holder reaches beside the forge's API: git in the forge's container (the note), the head's one writer of its - * statuses, and whether the first registrations are written. */ +/** What the holder reaches beside the forge's API: git in the forge's container (the note), and whether the first + * registrations are written. */ export interface SeatDeps { run: Runner; container: string; - statuses: HeadStatuses; /** Whether the first registrations were written (registrations.ts): until then merge-pull refuses every merge (design 47 §95). */ registered: () => boolean; /** The failed `required` step that refuses a head, judged from the module's own state `failed-steps` (failedsteps.ts), or null. */ judge: (head: string) => Promise; + /** The watched branches the registrations name, by their origin repository (registrations.ts): a member's base is one; + * null while they are not read since the last registration-changed heard (H-A-471, second addendum). */ + watched: () => ReadonlyMap> | null; + /** The state calls (calls.ts): each merge call written before its first merge (design 47 H §766). */ + calls?: Calls; + /** Says merge-called on the seat (mesh-sdk runtime.seatPublish; design 47 H §736). */ + say?: Say; + /** The findings merge-partial (partials.ts; design 47 H §767). */ + partials?: Partials; + /** Takes each act once by its ask id (taken.ts; design 47 H2 §775): absent, an act acts at every call. */ + once?: Once; } /** A failure as the contract says it: the forge's or this holder's refusal, or a forge that failed. */ @@ -60,10 +72,46 @@ export function failure(err: unknown): { error: string; "error-kind": ErrorKind const text = err instanceof Error ? err.message : String(err); // The forge's 404: what was asked about (a repository, a commit, a pull request, a branch, a tag) does not exist. if (/^Gitea API [^:]*: 404 /.test(text)) return { error: text, "error-kind": "not-found" }; + // A directory of `files` the commit does not hold (client.ts commitTrees): not-found, the error naming the directory, so the + // indexer reads the others alone and leaves the gone one out (novox/hq design 47 H H-A-232). + if (err instanceof DirectoryNotInTree) return { error: text, "error-kind": "not-found" }; const refused = err instanceof Refused || /^Gitea API [^:]*: 4\d\d /.test(text) || /^Gitea API: /.test(text); return { error: text, "error-kind": refused ? "refused" : "failed" }; } +/** The forge's own version read, which tells the forge away from its refusal (client.ts forgeVersion). */ +export type VersionRead = Pick; + +/** + * Which failure may mean the forge or its store is away (design 47 H2 §776): a 401 (or the admin account refused at the + * mint the 401 asked), a 502 or 503, or a connection fault (no answer, or an answer cut at its limit); else null. + */ +function awayCause(err: unknown): "unauthorized" | "unavailable" | null { + if (err instanceof AdminRefused) return "unauthorized"; + const text = err instanceof Error ? err.message : String(err); + if (/^Gitea [^:]*: 401 /.test(text)) return "unauthorized"; + if (/^Gitea [^:]*: 50[23] /.test(text)) return "unavailable"; + if (/^Gitea API [^:]*: no answer in /.test(text)) return "unavailable"; + if (err instanceof TypeError && /fetch failed/.test(text)) return "unavailable"; + return null; +} + +/** + * A failure as the contract says it, the forge's own version read deciding a 401, a 502, a 503 or a connection fault + * (design 47 H2 §776): the read failing, or naming the forge's store unavailable, answers `away`, which every caller reads + * as a transport fault; the read passing, a 401 is the forge refusing the mesh's admin account (the client minted a + * fresh token on the first 401 and was refused again, token.ts), never worded as an account to create; else as failure. + */ +export async function failureOf(forge: VersionRead, err: unknown): Promise<{ error: string; "error-kind": ErrorKind; part?: string; words?: string }> { + const cause = awayCause(err); + if (cause === null) return failure(err); + const text = err instanceof Error ? err.message : String(err); + const read = await forge.forgeVersion(); + if (read.ok === false) return awayAnswer(read.store ? "the forge's store" : "the forge", `${text}; ${read.words}`); + if (cause === "unauthorized") return { error: `the forge refuses the mesh's admin account: ${text}`, "error-kind": "refused" }; + return failure(err); +} + /** owner/name of a `repository` argument, each checked as a name (guard.ts). */ export function repositoryOf(raw: unknown): { owner: string; repo: string; full: string } { const parts = String(raw ?? "").split("/"); @@ -73,8 +121,10 @@ export function repositoryOf(raw: unknown): { owner: string; repo: string; full: } const SHA = /^[0-9a-f]{40}$/; -/** The git tag of a released Go version (design 51; design 47 §370). */ -const GO_TAG = /^go\/v\d+\.\d+\.\d+$/; +/** The git tag of a released version, /vMAJOR.MINOR.PATCH (design 47 H2 §796; design 47 §370). */ +const VERSION_TAG = /^(?:[A-Za-z0-9_][A-Za-z0-9._-]*\/)+v\d+\.\d+\.\d+$/; +/** The form of the seat git's values and answers this holder answers in (design 47 H2 §780, §796). */ +const GIT_FORM = 3; const STATES = new Set(["pending", "success", "failure", "error", "warning"]); function commitOf(name: string, raw: unknown): string { const sha = String(raw ?? "").trim(); @@ -126,18 +176,24 @@ async function mergingOf(gitea: GiteaClient, owner: string, repo: string, p: Git /** The seat's verbs as tools `git.`, each answering in the seat's contract. */ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] { - const verb = (name: string, description: string, act: (args: Record) => Promise): ToolDefinition => ({ + const answered = async (args: Record, act: (args: Record) => Promise): Promise => { + try { + return await act(args); + } catch (err) { + return failureOf(gitea, err); + } + }; + // An act given `standing`, what it did read afresh, is taken once by its ask id (§775, H-A-381, H-A-400). + const verb = (name: string, description: string, act: (args: Record) => Promise, + standing?: (args: Record) => Promise): ToolDefinition => ({ name: `${GIT}.${name}`, description, input: {}, - run: async (args: Record) => { - try { - return await act(args); - } catch (err) { - return failure(err); - } - }, + run: async (args: Record) => standing && deps.once + ? deps.once.run(askIdOf(args), () => answered(args, act), () => answered(args, standing)) + : answered(args, act), }); + const s = standingActs(gitea, deps); return [ verb(GIT_VERBS.pull, "The seat git's pull: one pull request by its repository and number or by its merge commit, and for an open one what the forge would merge now.", @@ -149,7 +205,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] const pull = pullOf(full, p); return pull.state === "open" ? { pull, merging: await mergingOf(gitea, owner, repo, p) } : { pull }; }), - verb(GIT_VERBS.branch, "The seat git's branch: a branch's head, and whether a protection rule refuses a direct push and admits only merges.", + verb(GIT_VERBS.branch, "The seat git's branch: a branch's head.", async (args): Promise => { const { owner, repo, full } = repositoryOf(args.repository); // No branch named is the repository's default branch, read from the forge, as the verb file reads it (A-399). @@ -158,7 +214,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] if (branch === "") throw new Error(`the forge names no default branch of ${full}`); // The head first: a branch the forge does not hold is its 404, the kind not-found, never an unprotected branch. const head = await gitea.branchHead(owner, repo, branch); - return { repository: full, branch, head, protected: pushRefused(await gitea.appliedProtection(owner, repo, branch)) }; + return { repository: full, branch, head }; }), verb(GIT_VERBS.openPulls, "The seat git's open-pulls: every open pull request of every repository, with the statuses its base requires and those its head has.", async (): Promise => { @@ -171,7 +227,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] })); return { pulls }; }), - verb(GIT_VERBS.tags, "The seat git's tags: a repository's tags, a page at a time, newest first; more when another page exists.", + verb(GIT_VERBS.tags, "The seat git's tags: a repository's tags, each with the commit it names, a page at a time, newest first; more when another page exists.", async (args): Promise => { const { owner, repo, full } = repositoryOf(args.repository); const page = args.page === undefined ? 1 : Number(args.page); @@ -179,8 +235,8 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] // One more than the page is asked, so whether another page exists is the forge's answer, not a guess. const got = await gitea.tags(owner, repo, page, TAGS_PAGE + 1); const more = got.length > TAGS_PAGE; - const tags = got.slice(0, TAGS_PAGE).filter((t) => t.startsWith(prefix)); - return { repository: full, page, bound: TAGS_PAGE, tags, ...(more ? { more } : {}) }; + const tags = got.slice(0, TAGS_PAGE).filter((t) => t.tag.startsWith(prefix)); + return { form: GIT_FORM, repository: full, page, bound: TAGS_PAGE, tags, ...(more ? { more } : {}) }; }), verb(GIT_VERBS.trees, "The seat git's trees: the trees of one commit, with files and paths when asked; a listing the forge cut is refused.", async (args): Promise => { @@ -218,17 +274,17 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] const combined = await gitea.combinedStatus(owner, repo, commit); return { commit, combined: combined.state, statuses: newestByContext(combined.statuses).map(statusOf) }; }), - verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set in its turn after every write of the head already asked for; the same id said again sets it again to the same.", + verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set on a commit; the same id said again sets it again to the same.", async (args): Promise => { const id = idOf(args.id); const { owner, repo } = repositoryOf(args.repository); const commit = commitOf("commit", args.commit); const state = String(args.state ?? ""); if (!STATES.has(state)) throw new Refused(`state ${JSON.stringify(state)} is none of ${[...STATES].join(", ")}`); - await deps.statuses.status(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""), + await gitea.setCommitStatus(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""), description: String(args.description ?? ""), ...(args.target ? { target_url: String(args.target) } : {}) }); return { id, performed: true }; - }), + }, s.status), verb(GIT_VERBS.comment, "The seat git's comment: an act of the forge bridge, a comment on a pull request carrying the act's id; an id it already holds is held.", async (args): Promise => { const id = idOf(args.id); @@ -237,7 +293,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] if (holds(await gitea.listComments(owner, repo, number), id)) return { id, held: true, performed: true }; await gitea.addComment(owner, repo, number, `${String(args.text ?? "")}\n\n${actMarker(id)}`); return { id, performed: true }; - }), + }, s.comment), verb(GIT_VERBS.view, "The seat git's view: an act of the forge bridge, the delivery's one view comment kept on a pull request; an id it already holds is held.", async (args): Promise => { const id = idOf(args.id); @@ -249,7 +305,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] if (existing) await gitea.editComment(owner, repo, existing.id, body); else await gitea.addComment(owner, repo, number, body); return { id, performed: true }; - }), + }, s.view), verb(GIT_VERBS.note, "The seat git's note: an act of the forge bridge, one line on a commit's note under refs/notes/mesh-plan carrying the act's id; an id it already holds is held.", async (args): Promise => { const id = idOf(args.id); @@ -257,86 +313,92 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[] const commit = commitOf("commit", args.commit); const said = await appendNote(deps.run, deps.container, owner, repo, commit, "mesh-plan", `${String(args.line ?? "")} [${id}]`, id); return said.added ? { id, performed: true } : { id, held: true, performed: true }; - }), - verb(GIT_VERBS.mergePull, "The seat git's merge-pull: an act of the forge bridge, a pull request merged at the head the caller names; it refuses a head at whose fingerprint a required step failed.", - async (args): Promise => mergePull(gitea, args, deps.registered, deps.judge)), - verb(GIT_VERBS.tag, "The seat git's tag: the git tag go/vMAJOR.MINOR.PATCH of a released version, written at the commit its build was made from; a tag that is at that commit is performed.", + }, s.note), + verb(GIT_VERBS.mergePull, "The seat git's merge-pull: one merge call, a delivery's start and its group: the pull requests named (pulls, each {repository, number, head}) and by (who@node); every member is judged before any is merged (still its head, its base a watched branch, no required step failed at its fingerprint), none merged when one is refused, then each merged in the order named; it answers the call and each member's outcome.", + async (args): Promise => mergeCall(gitea, args, deps), s.mergePull), + verb(GIT_VERBS.tag, "The seat git's tag: the git tag /vMAJOR.MINOR.PATCH of a released version, written at the commit its build was made from; a tag that is at that commit is performed.", async (args): Promise => { const { owner, repo } = repositoryOf(args.repository); const tag = String(args.tag ?? ""); - if (!GO_TAG.test(tag)) throw new Refused(`${JSON.stringify(tag)} is not go/vMAJOR.MINOR.PATCH`); + if (!VERSION_TAG.test(tag)) throw new Refused(`${JSON.stringify(tag)} is not /vMAJOR.MINOR.PATCH`); const commit = commitOf("commit", args.commit); const at = await gitea.tagCommit(owner, repo, tag); if (at === commit) return { tag, performed: true }; if (at !== null) throw new Refused(`${tag} is at ${at.slice(0, 12)} already, not at ${commit.slice(0, 12)}; a tag is never moved`); await gitea.createTag(owner, repo, tag, commit); return { tag, performed: true }; - }), + }, s.tag), ]; } -/** Whether a protection rule refuses a direct push and admits only merges: the rule exists and takes no push. */ -export function pushRefused(rule: { enable_push?: boolean } | null): boolean { - return !!rule && rule.enable_push === false; -} - function holds(comments: GiteaComment[], id: string): boolean { return comments.some((c) => String(c.body ?? "").includes(actMarker(id))); } -/** merge-pull (design 47 §314): only the head the caller names, only into a base that takes no push, no check judged. */ -export async function mergePull(gitea: GiteaClient, args: Record, registered: () => boolean, - judge: (head: string) => Promise): Promise { - const id = idOf(args.id); - const { owner, repo, full } = repositoryOf(args.repository); - const number = numberOf(args.number); - const head = commitOf("head", args.head); - const no = (why: string, kind: NonNullable): MergePullAnswer => - ({ id, refused: `${full}#${number} is not merged: ${why}`, "refused-kind": kind }); - // Until the first registrations are written no merge is made: the old assigner would write a want from the trunk with no - // pipeline (design 47 §95). It names what is missing. - if (!registered()) return no("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written", "no-registrations"); - const pull = await gitea.getPullRequest(owner, repo, number); - if (pull.merged) { - // Already merged at that head: performed (the act said again after its answer was lost); at another, refused. - return pull.head_sha === head ? { id, performed: true, held: true, ...(pull.merge_commit_sha ? { "merge-commit": pull.merge_commit_sha } : {}) } - : no(`it was merged at ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved"); - } - if (pull.state !== "open") return no("it is closed", "git-refused"); - if (pull.head_sha !== head) { - return no(`its head is ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved"); - } - const rule = await gitea.appliedProtection(owner, repo, String(pull.base ?? "")); - if (!pushRefused(rule)) { - return no(`its base ${pull.base} is guarded by no protection rule that refuses a push`, "unprotected"); - } - // The head's runs, judged from the module's own state (design 47 §39): a step that failed at its fingerprint in any run refuses it, - // naming the run, the module and the step; a head no run named merges, and the runner being down changes nothing. - const failed = await judge(head); - if (failed) { - return { id, refused: `${full}#${number} is not merged: the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`, - "refused-kind": "policy-failed", run: failed.run, module: failed.module, step: failed.step }; - } - try { - await gitea.mergePullRequest(owner, repo, number, "merge", true, head); - } catch (err) { - const f = failure(err); - if (f["error-kind"] === "refused") return no(`the forge refused the merge: ${f.error}`, "git-refused"); - throw err; - } - const merged = await gitea.getPullRequest(owner, repo, number); - if (!merged.merge_commit_sha) throw new Error(`${full}#${number} WAS merged, but the forge named no merge commit`); - // The merge is done once the forge named its commit: a read-back that fails is said, never answered as a failed act. - let parents: string[]; - try { - parents = await gitea.commitParents(owner, repo, merged.merge_commit_sha); - } catch (err) { - console.error(`[gitea] ${full}#${number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`); - return { id, performed: true, "merge-commit": merged.merge_commit_sha }; - } - if (parents.length === 2 && parents[1] !== head) { - throw new Error(`${full}#${number} WAS merged (${merged.merge_commit_sha}), but the forge merged ${parents[1].slice(0, 12)}, ` + - `not the ${head.slice(0, 12)} the caller names (novox/hq issue 381)`); - } - return { id, performed: true, "merge-commit": merged.merge_commit_sha }; +/** + * What each act did, read afresh from the forge, for an ask given again after its act ended (design 47 H2 §775; H-A-381 + * (1)): the act is never performed twice, and what the forge holds is what the act answers when done. A repeat for which + * the forge holds nothing of the act is a refusal naming it. + */ +function standingActs(gitea: GiteaClient, deps: SeatDeps) { + const never = (ask: string, what: string) => new Refused(`the ask ${ask} was taken and its act acted, but ${what}: answered as it stands, never acted again`); + const askOf = (args: Record) => askIdOf(args); + return { + status: async (args: Record): Promise => { + const id = idOf(args.id); + const { owner, repo } = repositoryOf(args.repository); + const commit = commitOf("commit", args.commit); + const context = String(args.context ?? ""), state = String(args.state ?? ""); + const now = newestByContext((await gitea.combinedStatus(owner, repo, commit)).statuses).find((x) => x.context === context); + if (!now || now.state !== state) throw never(askOf(args), `${commit.slice(0, 12)} carries no ${context} ${state}`); + return { id, held: true, performed: true }; + }, + comment: async (args: Record): Promise => { + const id = idOf(args.id); + const { owner, repo, full } = repositoryOf(args.repository); + const number = numberOf(args.number); + if (!holds(await gitea.listComments(owner, repo, number), id)) throw never(askOf(args), `${full}#${number} holds no comment of the act ${id}`); + return { id, held: true, performed: true }; + }, + view: async (args: Record): Promise => { + const id = idOf(args.id); + const { owner, repo, full } = repositoryOf(args.repository); + const number = numberOf(args.number); + const existing = viewComment(await gitea.listComments(owner, repo, number)); + if (!existing?.body.includes(actMarker(id))) throw never(askOf(args), `${full}#${number}'s view is not the act ${id}'s`); + return { id, held: true, performed: true }; + }, + note: async (args: Record): Promise => { + const id = idOf(args.id); + const { owner, repo } = repositoryOf(args.repository); + const commit = commitOf("commit", args.commit); + if (!(await noteHolds(deps.run, deps.container, owner, repo, commit, "mesh-plan", id))) { + throw never(askOf(args), `the note on ${commit.slice(0, 12)} holds no line of the act ${id}`); + } + return { id, held: true, performed: true }; + }, + mergePull: async (args: Record): Promise => { + // Each member as the forge holds it: merged, with its merge commit; the call that merged them, when one is kept. + const members = membersOf(args.pulls); + const out = await Promise.all(members.map(async (m) => { + const p = await gitea.getPullRequest(m.owner, m.repo, m.number); + return p.merged && p.merge_commit_sha + ? { repository: m.repository, number: m.number, state: "merged" as const, commit: p.merge_commit_sha } + : { repository: m.repository, number: m.number, state: "refused" as const, why: `not merged: the forge holds it ${p.state === "open" ? "open" : "closed"}` }; + })); + if (!out.some((m) => m.state === "merged")) throw never(askOf(args), "the forge merged none of its pull requests"); + const named = (c: { members: { repository: string; number: number; state: string }[] }) => + out.every((m) => m.state !== "merged" || c.members.some((k) => k.repository === m.repository && k.number === m.number && k.state === "merged")); + const kept = (await deps.calls?.all())?.find(named); + return { ...(kept ? { call: kept.call } : {}), members: out }; + }, + tag: async (args: Record): Promise => { + const { owner, repo } = repositoryOf(args.repository); + const tag = String(args.tag ?? ""); + const commit = commitOf("commit", args.commit); + const at = await gitea.tagCommit(owner, repo, tag); + if (at !== commit) throw never(askOf(args), at === null ? `the forge holds no tag ${tag}` : `${tag} is at ${at.slice(0, 12)}, not ${commit.slice(0, 12)}`); + return { tag, performed: true }; + }, + }; } diff --git a/modules/gitea/siblings.ts b/modules/gitea/siblings.ts deleted file mode 100644 index 5dcff478a..000000000 --- a/modules/gitea/siblings.ts +++ /dev/null @@ -1,298 +0,0 @@ -// **A delivery group's member is checked beside the other members' heads, and a sibling's move puts that verdict out of -// date** (novox/hq ADR 0382 §5, §6; issue 867). -// -// The controller's verdict (`checked`) names the siblings its check read: each as the sibling's repository, pull -// request, head, base branch and the base commit the sibling's head was merged onto. This module, the forge's holder, -// keeps them per open pull request, beside its other records, and: -// -// - on its own hearing of a sibling's new head, of its close unmerged, or of a move of its base, sets -// mesh/merge-gate and mesh/repo-check of every member whose verdict names that sibling back to pending, with the -// reason. Nothing is run for it. The one move that does not count is the sibling's own merge of the head that was -// read onto the base commit that was read (in either order of the two merges); -// - lets the merge tool refuse a verdict that read siblings unless mesh/delivery-group passed at the very heads it -// read, and every sibling head it read carries an approving review at that head (merge.ts). -// -// A verdict without siblings (a controller from before ADR 0382) is none of this: nothing is kept and nothing changes. -// Pure functions and one small file of the module's own state, so this is tested without a forge. - -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { dirname } from "node:path"; -import type { CommitStatus, GiteaPull, HeadCheck } from "./client.js"; -import { Refused } from "./guard.js"; -import { CHECK_CONTEXT, REPO_CHECK_CONTEXT, clipped } from "./pulls.js"; -import { sameCommit, twelve, type OutOfDateWriter } from "./trunk.js"; - -/** The status the delivery group's owner sets on each member's head (novox/hq ADR 0239). */ -export const GROUP_CONTEXT = "mesh/delivery-group"; - -/** One sibling a verdict read, as the controller names it (contract of ADR 0382 §4). */ -export interface SiblingNamed { - repository: string; - number: number; - head: string; - base: string; - base_commit: string; - /** Set here, never by the controller: the sibling merged its head onto its base commit read, so it is no sibling's - * move any more. */ - merged?: boolean; -} - -/** What is kept of one member's latest verdict that read siblings: the head it was of and the siblings it named. */ -export interface SiblingEntry { - head: string; - siblings: SiblingNamed[]; -} - -/** The records, by `owner/repo#number` of the member. */ -export type SiblingRecord = Record; - -/** The member's key. */ -export function memberKey(owner: string, repo: string, number: number): string { - return `${owner}/${repo}#${number}`.toLowerCase(); -} - -/** The siblings a verdict names, trimmed to what is kept; none when it names none or names one badly. */ -export function siblingsOf(named: unknown): SiblingNamed[] { - if (!Array.isArray(named)) return []; - const out: SiblingNamed[] = []; - for (const s of named) { - const r = s as Record; - const repository = String(r?.repository ?? ""), head = String(r?.head ?? ""), base = String(r?.base ?? ""); - const number = Number(r?.number); - if (!repository || !head || !base || !Number.isInteger(number) || number <= 0) continue; - out.push({ repository, number, head, base, base_commit: String(r?.base_commit ?? "") }); - } - return out; -} - -/** The siblings as a status names them: "mesh-host#114@abcdef123456, …". */ -export function siblingWords(siblings: SiblingNamed[]): string { - return siblings.map((s) => `${s.repository.split("/").pop()}#${s.number}@${twelve(s.head)}`).join(", "); -} - -/** What a status of a verdict that read siblings carries, after the commits it judged. */ -export function besideWords(siblings: SiblingNamed[]): string { - // Short, so that the verdict word and the start of its reason survive the forge's 140 characters: the first sibling - // by its pull request and 8 characters of its head, and how many more. The whole list is the holder's record and the comment's. - const first = siblings[0]; - const more = siblings.length > 1 ? ` +${siblings.length - 1} more` : ""; - return `beside ${first.repository.split("/").pop()}#${first.number}@${twelve(first.head).slice(0, 8)}${more}`; -} - -/** The mark a status carries when the siblings could not be learned (ADR 0382 §1): said, never silent. */ -export const UNKNOWN_MARK = "siblings unknown"; - -/** Whether a status names that its verdict read siblings (so that a record lost does not read as none). */ -export function namesSiblings(description: string | undefined): boolean { - return / beside [\w.-]+#\d+@[0-9a-f]{8}\b/.test(description ?? ""); -} - -/** Whether a status is a verdict put out of date by a sibling's move. */ -export function siblingOutOfDate(description: string | undefined): boolean { - return /^out of date: judged beside /.test(description ?? ""); -} - -// --- the record on disk ---------------------------------------------------------------------------------------- - -/** The file the holder keeps the siblings its verdicts name in, beside its other records. */ -export function siblingsFile(stateDir: string | undefined): string | null { - return stateDir ? `${stateDir.replace(/\/+$/, "")}/siblings-named.json` : null; -} - -export function readSiblings(file: string | null): SiblingRecord { - if (!file || !existsSync(file)) return {}; - try { - return (JSON.parse(readFileSync(file, "utf8")) as { members?: SiblingRecord }).members ?? {}; - } catch { - return {}; - } -} - -export function keepSiblings(file: string | null, record: SiblingRecord): void { - if (!file) return; - try { - mkdirSync(dirname(file), { recursive: true }); - writeFileSync(file + ".tmp", JSON.stringify({ members: record })); - renameSync(file + ".tmp", file); - } catch (err) { - console.error(`[gitea] the siblings a verdict named could not be kept — ${err instanceof Error ? err.message : err}`); - } -} - -// --- what a sibling's move is --------------------------------------------------------------------------------- - -/** What weighing a sibling reads of the forge. */ -export interface SiblingForge { - getPullRequest(owner: string, repo: string, index: number): Promise; - branchHead(owner: string, repo: string, branch: string): Promise; - commitParents(owner: string, repo: string, sha: string): Promise; -} - -/** The reason a verdict that named this sibling is out of date, from what the forge holds now, or nothing; and whether - * the sibling has merged its head read onto the base commit read, which ends it as a sibling. */ -export async function siblingMoved(forge: SiblingForge, s: SiblingNamed): Promise<{ reason?: string; merged?: boolean }> { - const [owner, repo] = s.repository.split("/"); - const who = `${repo}#${s.number}`; - const pull = await forge.getPullRequest(owner, repo, s.number); - if (pull.merged) { - // Its own merge of the head that was read onto the base commit that was read: the head the merge joined is the head - // read, and the commit it was made onto is the base commit read. Any other merge is a move of the base. - const parents = pull.merge_commit_sha ? await forge.commitParents(owner, repo, pull.merge_commit_sha).catch(() => []) : []; - const own = sameCommit(pull.head_sha, s.head) && parents.length >= 1 && sameCommit(parents[0], s.base_commit) && - (parents.length === 1 || sameCommit(parents[1], s.head)); - if (own) return { merged: true }; - return { reason: `${who} was merged otherwise than its head ${twelve(s.head)} onto ${twelve(s.base_commit)}` }; - } - if (pull.state !== "open") return { reason: `${who} was closed unmerged` }; - if (!sameCommit(pull.head_sha, s.head)) { - return { reason: `${who} at ${twelve(s.head)}, it is now at ${twelve(pull.head_sha)}` }; - } - const base = await forge.branchHead(owner, repo, s.base); - if (!sameCommit(base, s.base_commit)) { - return { reason: `${who} merged onto ${twelve(s.base_commit)}, its ${s.base} is now ${twelve(base)}` }; - } - return {}; -} - -/** A verdict out of date because a sibling moved, as its statuses say it (ADR 0382 §5; the wording of ADR 0323 §4). */ -export function siblingOutOfDateWords(reason: string): string { - return clipped(`out of date: judged beside ${reason}; judged again on a recheck or when it is merged`); -} - -/** The statuses a sibling's move puts back to pending on one member's head, from what the forge holds on it now: none - * when it has no merge check, or its gate is pending (a check on its way, or already out of date). */ -export function siblingStatuses(checks: Record, reason: string): CommitStatus[] { - const gate = checks[CHECK_CONTEXT]; - if (!gate || gate.state === "pending") return []; - const description = siblingOutOfDateWords(reason); - const out: CommitStatus[] = [{ state: "pending", context: CHECK_CONTEXT, description }]; - if (checks[REPO_CHECK_CONTEXT]) out.push({ state: "pending", context: REPO_CHECK_CONTEXT, description }); - return out; -} - -/** What weighing a sibling's move writes with, beside the forge's reads. */ -export interface SiblingWeighing extends SiblingForge {} - -/** - * A sibling moved (a new head, a close, a base move, a merge): every member whose latest verdict names it has its - * merge check put back to pending with the reason. `repository` and, when the event names one, `number` say which - * sibling. A member whose head is no longer the one its verdict was of is dropped from the record: its new head is - * checked afresh. Nothing is run. Answers whether the record changed. A read that fails leaves that member for the next - * move to weigh, and is said. - */ -export async function weighSiblings(forge: SiblingWeighing, gates: OutOfDateWriter, record: SiblingRecord, - repository: string, number?: number): Promise { - let changed = false; - const repo = repository.toLowerCase(); - for (const [key, entry] of Object.entries(record)) { - const [path] = key.split("#"); - const [owner, name] = path.split("/"); - const memberNumber = Number(key.split("#")[1]); - // A member that is merged or no longer open has no verdict to put out of date: its entry goes (the record must not - // grow without bound, and a merged head is never re-pended by a sibling's later push). Weighed when the event is the - // member's own, or names one of its siblings. - const own = path === repo && (number === undefined || number === memberNumber); - if (own || entry.siblings.some((s) => !s.merged && s.repository.toLowerCase() === repo && (number === undefined || s.number === number))) { - try { - const member = await forge.getPullRequest(owner, name, memberNumber); - if (member.merged || member.state !== "open") { - delete record[key]; - changed = true; - continue; - } - } catch (err) { - console.error(`[gitea] ${key}: whether it is still open could not be read — ${err instanceof Error ? err.message : err}`); - } - } - for (const s of entry.siblings) { - if (s.merged || s.repository.toLowerCase() !== repo || (number !== undefined && s.number !== number)) continue; - try { - const moved = await siblingMoved(forge, s); - if (moved.merged) { - s.merged = true; - changed = true; - continue; - } - if (!moved.reason) continue; - const member = await forge.getPullRequest(owner, name, memberNumber); - if (!sameCommit(member.head_sha, entry.head)) { - delete record[key]; - changed = true; - break; - } - const written = await gates.outOfDate(owner, name, entry.head, (checks) => siblingStatuses(checks, moved.reason!), - member.html_url || undefined); - if (written.length) { - console.log(`[gitea] ${key}: its verdict was judged beside ${moved.reason}: out of date, nothing run (novox/hq ADR 0382)`); - } - break; - } catch (err) { - console.error(`[gitea] ${key}: whether ${s.repository}#${s.number} moved could not be weighed, so it is weighed again ` + - `on its next move — ${err instanceof Error ? err.message : err}`); - } - } - } - return changed; -} - -// --- the merge tool's rule (ADR 0382 §6) ---------------------------------------------------------------------- - -/** What the rule reads beside the pull request being merged. */ -export interface GroupForge { - headChecks(owner: string, repo: string, sha: string): Promise>; -} - -/** The heads the operator's Approve covers (novox/hq ADR 0421 §9, issue 1022), as mesh-delivery hands them to the merge - * tool: `owner/repo@`, one per member, by repository. A malformed entry is refused, never skipped. */ -export function approvedHeadsOf(given: unknown): Map | undefined { - if (given === undefined || given === null) return undefined; - if (!Array.isArray(given)) throw new Refused("approved_heads must be a list of owner/repo@. Nothing was merged"); - const out = new Map(); - for (const entry of given) { - const m = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{40}|[0-9a-f]{64})$/i.exec(String(entry)); - if (!m) throw new Refused(`approved_heads holds ${JSON.stringify(entry)}, which is not owner/repo@. Nothing was merged`); - out.set(m[1].toLowerCase(), m[2].toLowerCase()); - } - return out; -} - -/** Why a pull request's head is not one the Approve covers, in words, or nothing: its repository is not named, or names - * another head. */ -export function notApproved(approved: Map, repository: string, number: number, head: string): string | undefined { - const covered = approved.get(repository.toLowerCase()); - const at = `${repository.split("/")[1]}#${number}@${twelve(head)}`; - if (covered === undefined) return `${at} is not among the heads the Approve covers`; - if (covered !== head.toLowerCase()) return `${at} is not the head the Approve covers (${twelve(covered)})`; - return undefined; -} - -/** - * What stops a pull request whose verdict read siblings from merging, in words, or nothing: mesh/delivery-group must be - * a success at its own head and at every sibling head the verdict read, and every head read must be one the operator's - * Approve covers (ADR 0421 §9: the Approve is the review; the merge tool takes the approved heads from mesh-delivery). - * Every missing thing is named. - */ -export async function groupRefusal(forge: GroupForge, self: { owner: string; repo: string; number: number; head: string }, - siblings: SiblingNamed[], approved: Map | undefined): Promise { - const missing: string[] = []; - const members = [{ repository: `${self.owner}/${self.repo}`, number: self.number, head: self.head }, - ...siblings.map((s) => ({ repository: s.repository, number: s.number, head: s.head }))]; - for (const m of members) { - const [owner, repo] = m.repository.split("/"); - const at = `${repo}#${m.number}@${twelve(m.head)}`; - let group: HeadCheck | undefined; - try { - group = (await forge.headChecks(owner, repo, m.head))[GROUP_CONTEXT]; - } catch (err) { - missing.push(`${GROUP_CONTEXT} at ${at} could not be read (${err instanceof Error ? err.message : err})`); - continue; - } - if (group?.state !== "success") missing.push(`${GROUP_CONTEXT} is ${group?.state ?? "missing"} at ${at}`); - if (!approved) missing.push(`${at} is covered by no Approve: the merge was handed no approved heads`); - else { - const why = notApproved(approved, m.repository, m.number, m.head); - if (why) missing.push(why); - } - } - return missing.length ? missing.join("; ") : undefined; -} diff --git a/modules/gitea/taken.ts b/modules/gitea/taken.ts new file mode 100644 index 000000000..90d73e676 --- /dev/null +++ b/modules/gitea/taken.ts @@ -0,0 +1,107 @@ +// **The forge module takes an act of the seat git once by its ask id** (novox/hq design 47 H2 §775; H-A-381, H-A-400): a +// kept call carries its ask id (the runtime names it in the call's `_meta`, mesh-sdk askIdOf), and the forge module keeps +// each id it took in its state `taken`, key `git.`, for `ask-taken-bound` (a setting, default 10 minutes, the +// largest caller's bound). An ask given again while its act runs joins that act and gets its answer; given again after +// the act ended, it answers the act's state as it stands, read afresh from the forge (a merge call answers each pull +// request as it is: merged, with its merge commit), and the act is never performed twice. No answer is kept in `taken`. +// The key is kept only for an act that acted: an answer that performed nothing (away, a transport fault, a refusal +// before any act) drops it, so the kept call's repeat under the same id acts (H-A-400 (1)). A repeat for which the +// forge's state says the act that acted never happened is a refusal naming it. + +import { takeOnce, takenKey, TAKEN_STATE, type State } from "@novox/mesh-sdk/state"; + +/** The seat the forge module takes asks of. */ +export const SEAT = "git"; + +/** ask-taken-bound's default (H-A-381 (2)). */ +export const ASK_TAKEN_BOUND_DEFAULT = "10m"; + +/** A duration as the mesh writes one ("10m", "1h30m", "45s", "500ms"), in milliseconds; null when it is none. */ +export function durationMs(text: string): number | null { + const s = text.trim(); + if (!/^(\d+(\.\d+)?(ms|h|m|s))+$/.test(s)) return null; + let ms = 0; + for (const [, n, , unit] of s.matchAll(/(\d+(\.\d+)?)(ms|h|m|s)/g)) { + ms += Number(n) * ({ ms: 1, s: 1_000, m: 60_000, h: 3_600_000 } as Record)[unit]; + } + return ms > 0 ? ms : null; +} + +/** ask-taken-bound in milliseconds, from the word the node-engine composes for it (H-A-370, H-A-400 (2)); the default when + * it is unset. A value that is no duration is said and the default taken. */ +export function askTakenBoundMs(env: NodeJS.ProcessEnv = process.env, log: (line: string) => void = () => {}): number { + const raw = env.MESH_CONFIG_ASK_TAKEN_BOUND; + const fallback = durationMs(ASK_TAKEN_BOUND_DEFAULT)!; + if (raw === undefined || raw.trim() === "") return fallback; + const ms = durationMs(raw); + if (ms === null) { + log(`the setting ask-taken-bound is ${JSON.stringify(raw)}, no duration: the default ${ASK_TAKEN_BOUND_DEFAULT} holds`); + return fallback; + } + return ms; +} + +/** The state taken, as the forge module reaches it: take an ask once, drop a key whose act performed nothing. */ +export interface Taken { + /** Whether this holder takes the ask now (mesh-sdk takeOnce: created, refused when the key exists). */ + take(ask: string): Promise; + /** Drops the key of an ask whose act performed nothing, so its repeat acts. */ + drop(ask: string): Promise; +} + +/** The module's state taken over the runtime, its keys living ask-taken-bound. */ +export function takenState(st: Pick, "delete">, boundMs: number): Taken { + return { + take: (ask) => takeOnce(SEAT, ask, boundMs, TAKEN_STATE), + drop: (ask) => st.delete(takenKey(SEAT, ask)), + }; +} + +/** Whether an act's answer performed nothing: an error answer, or a merge call that merged no member. */ +export function performedNothing(answer: object): boolean { + const a = answer as Record; + if (a["error-kind"] !== undefined) return true; + if (Array.isArray(a.members)) return !a.members.some((m: any) => m?.state === "merged"); + return false; +} + +/** + * Takes an act once by its ask id: `act` runs for an ask this holder takes now; an ask given while its act runs joins it; + * an ask taken before whose act ended answers `standing`, the act's state read afresh. An act with no ask id acts as + * before. The taken key is dropped when the act performed nothing. + */ +export class Once { + private readonly running = new Map>(); + + constructor(private readonly taken: Taken, private readonly log: (line: string) => void = () => {}) {} + + async run(ask: string, act: () => Promise, standing: () => Promise): Promise { + if (!ask) return act(); + const joined = this.running.get(ask); + if (joined) return joined; + if (!(await this.taken.take(ask))) { + // Taken before, and its act ended (or another process runs it): what it did, read afresh, never done again. + return this.running.get(ask) ?? standing(); + } + const acting = (async () => { + let answer: object; + try { + answer = await act(); + } catch (err) { + await this.taken.drop(ask).catch(() => {}); + throw err; + } + if (performedNothing(answer)) { + await this.taken.drop(ask).catch((err) => + this.log(`the ask ${ask} performed nothing and its taken key could not be dropped, so its repeat is answered as it stands — ${err instanceof Error ? err.message : err}`)); + } + return answer; + })(); + this.running.set(ask, acting); + try { + return await acting; + } finally { + this.running.delete(ask); + } + } +} diff --git a/modules/gitea/test/announcing.test.ts b/modules/gitea/test/announcing.test.ts index 375124d71..d47881a12 100644 --- a/modules/gitea/test/announcing.test.ts +++ b/modules/gitea/test/announcing.test.ts @@ -12,22 +12,6 @@ const repo = (full: string, updated: string) => { return { full_name: full, owner, name, private: false, html_url: "", updated_at: updated }; }; -test("a pull request opened after the margin is looked at, by its own update time", async () => { - const { reposToLook } = await import("../pulls.ts"); - const pushed = "2026-10-09T10:00:00Z"; // the branch pushed: the repository's update time - // The pull request opened two minutes later; the last pass was at 10:02:30, so the floor is 10:01:30. - const floor = "2026-10-09T10:01:30Z"; - const repos = [repo("novox/mesh-sdk", pushed), repo("novox/hq", "2026-10-09T09:00:00Z")]; - const opened = [{ owner: "novox", name: "mesh-sdk", updated_at: "2026-10-09T10:02:00Z" }]; - assert.deepEqual(reposToLook(repos, floor, opened, false).map((r) => r.full_name), ["novox/mesh-sdk"], - "the repository of a pull request updated since the floor, though the repository itself did not move"); - assert.deepEqual(reposToLook(repos, floor, [], false).map((r) => r.full_name), [], - "without the pull request's own time nothing is looked at — the fault"); - assert.deepEqual(reposToLook(repos, floor, [], true).map((r) => r.full_name).sort(), ["novox/hq", "novox/mesh-sdk"], - "a sweep looks at every repository"); - assert.deepEqual(reposToLook(repos, "", [], false).length, 2, "the first pass looks at every repository"); -}); - test("every open pull request is read with what its base requires and what its head has (gitea_open_pulls)", async () => { const { GiteaClient } = await import("../client.ts"); const asked: string[] = []; diff --git a/modules/gitea/test/calls.test.ts b/modules/gitea/test/calls.test.ts new file mode 100644 index 000000000..08da5871b --- /dev/null +++ b/modules/gitea/test/calls.test.ts @@ -0,0 +1,152 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { memory } from "./memstate.ts"; + +// **The call is written before its first merge** (novox/hq design 47 H §766; H-A-18, H-A-47, H-A-71): the key +// call. of the state calls holds by, the proved account, at, each member with its base and its state (judged before +// the first merge, merged with its commit as it merges) and said; a call past call-retention is deleted on a new call's +// write, oldest first. + +const A = "a".repeat(40), B = "b".repeat(40); + +test("a merge call is kept before its first merge, each member judged, then merged with its commit", async () => { + const { mergeCall } = await import("../dist/mergecall.js"); + const { Calls } = await import("../dist/calls.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const { kv, st } = memory(); + const calls = new Calls(st as any); + const seenAtMerge: any[] = []; + const pulls: Record = { 5: { head: A, merged: false }, 9: { head: B, merged: false } }; + const forge = { + getPullRequest: async (_o: string, r: string, n: number) => ({ number: n, state: "open", merged: pulls[n].merged, base: "main", + head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }), + mergePullRequest: async (_o: string, _r: string, n: number) => { + seenAtMerge.push(structuredClone(kv.get("call.0123456789abcdef"))); + pulls[n].merged = true; + }, + commitParents: async () => [], + }; + const args = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/app", number: 9, head: B }] }; + const at = new Date("2026-11-20T03:00:00Z"); + await runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, { registered: () => true, + watched: () => new Map([["novox/app", new Set(["main"])]]), judge: async () => null, newCall: () => "0123456789abcdef", + calls, now: () => at } as any)); + const first = seenAtMerge[0]; + assert.deepEqual([first.by, first.account, first.at, first.said], ["lead@shanks", "shanks.claude-code", at.toISOString(), false]); + assert.deepEqual(first.members.map((m: any) => [m.number, m.branch, m.head, m.state]), [[5, "main", A, "judged"], [9, "main", B, "judged"]]); + assert.deepEqual(seenAtMerge[1].members.map((m: any) => [m.state, m.commit]), [["merged", "5".repeat(40)], ["judged", undefined]]); + const kept = await calls.get("0123456789abcdef"); + assert.deepEqual(kept?.members.map((m: any) => m.state), ["merged", "merged"]); +}); + +test("a call past call-retention is deleted on a new call's write, oldest first; a younger one is kept", async () => { + const { Calls } = await import("../dist/calls.js"); + const { kv, st } = memory(); + const calls = new Calls(st as any, () => 30); + const call = (at: string) => ({ by: "a@b", account: "x", at, members: [], said: true }); + await calls.put("1111111111111111", call("2026-09-01T00:00:00Z"), new Date("2026-09-01T00:00:00Z")); + await calls.put("2222222222222222", call("2026-10-25T00:00:00Z"), new Date("2026-10-25T00:00:00Z")); + await calls.put("3333333333333333", call("2026-11-20T00:00:00Z"), new Date("2026-11-20T00:00:00Z")); + assert.deepEqual([...kv.keys()].sort(), ["call.2222222222222222", "call.3333333333333333"]); + assert.deepEqual((await calls.all()).map((c) => c.call), ["3333333333333333", "2222222222222222"], "newest first"); +}); + +// **The merge call says one event** (design 47 H §736, §766; test 111's stop case): merge-called on merge-called. with +// the landed members, each with its base and merge commit; a call that landed none says none; at the start a call whose +// event is not said (a stop after the second of three merges) says one naming the two that landed, and is kept said. +test("a call says one merge-called of what landed; none for a call that landed none; the start says an unsaid one", async () => { + const { mergeCall } = await import("../dist/mergecall.js"); + const { Calls, sayUnsaid } = await import("../dist/calls.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const said: { subject: string; body: any; id?: string }[] = []; + const say = async (subject: string, body: unknown, id?: string) => { said.push({ subject, body, id }); }; + const { st } = memory(); + const calls = new Calls(st as any); + const pulls: Record = { 5: { head: A, merged: false, state: "open" }, 9: { head: B, merged: false, state: "closed" } }; + const forge = { + getPullRequest: async (_o: string, _r: string, n: number) => ({ number: n, state: pulls[n].state, merged: pulls[n].merged, base: "main", + head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }), + mergePullRequest: async (_o: string, _r: string, n: number) => { pulls[n].merged = true; }, + commitParents: async () => [], + }; + const deps = (call: string) => ({ registered: () => true, watched: () => new Map([["novox/app", new Set(["main"])]]), + judge: async () => null, newCall: () => call, calls, say, now: () => new Date("2026-11-20T03:00:00Z") }); + const run = (call: string, numbers: number[]) => { + const args = { by: "lead@shanks", pulls: numbers.map((n) => ({ repository: "novox/app", number: n, head: pulls[n].head })) }; + return runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, deps(call) as any)); + }; + await run("00000000000000aa", [5, 9]); // refused at judging: no event + assert.deepEqual(said, []); + await run("00000000000000bb", [5]); + assert.equal(said.length, 1); + assert.deepEqual([said[0].subject, said[0].id], ["mesh.seat.git.event.merge-called.00000000000000bb", "merge-called.00000000000000bb"]); + assert.deepEqual(said[0].body, { call: "00000000000000bb", by: "lead@shanks", account: "shanks.claude-code", at: "2026-11-20T03:00:00.000Z", + members: [{ repository: "novox/app", number: 5, branch: "main", head: A, commit: "5".repeat(40) }] }); + assert.equal((await calls.get("00000000000000bb"))?.said, true); + // A stop after the second of three merges: kept, not said. + const m = (n: number, state: string) => ({ repository: "novox/app", number: n, branch: "main", head: A, state, ...(state === "merged" ? { commit: String(n).repeat(40) } : {}) }); + await calls.put("00000000000000cc", { by: "lead@shanks", account: "x", at: "2026-11-20T03:01:00Z", members: [m(1, "merged"), m(2, "merged"), m(3, "judged")], said: false } as any); + said.length = 0; + assert.deepEqual(await sayUnsaid(calls, say), ["00000000000000cc"]); + assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[1, 2]]); + assert.equal(said[0].body.refused, undefined, "a member not merged after a stop is no refused member"); + assert.deepEqual(await sayUnsaid(calls, say), [], "said once"); + // A member merged plainly, its repository having no watched branch, starts no delivery: the start's re-say leaves it + // out by the kept note (design 47 H2 H-A-471 addendum (2)), and a call of such members alone says none. + const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: the repository has no watched branch" }; + await calls.put("00000000000000dd", { by: "lead@shanks", account: "x", at: "2026-11-20T03:02:00Z", members: [noted, m(5, "merged")], said: false } as any); + await calls.put("00000000000000ee", { by: "lead@shanks", account: "x", at: "2026-11-20T03:03:00Z", members: [noted], said: false } as any); + said.length = 0; + assert.deepEqual(await sayUnsaid(calls, say), ["00000000000000dd"]); + assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[5]]); + assert.equal((await calls.get("00000000000000ee"))?.said, true, "kept said, with nothing to say"); +}); + +// The merge calls' tools (design 47 H §766): forge_calls answers the calls newest first with each member's state, and +// forge_call_say_again says a call's merge-called again once the hand-act log took it. +test("forge_calls reads the calls newest first; forge_call_say_again says one again after the hand-act log", async () => { + const { Calls } = await import("../dist/calls.js"); + const { Partials } = await import("../dist/partials.js"); + const { callTools } = await import("../dist/tools/calls.js"); + const { st } = memory(); + const calls = new Calls(st as any); + const m = (n: number, state: string) => ({ repository: "novox/app", number: n, branch: "main", head: A, state, ...(state === "merged" ? { commit: String(n).repeat(40) } : {}) }); + await calls.put("00000000000000aa", { by: "a@b", account: "x", at: "2026-11-20T01:00:00Z", members: [m(1, "merged")], said: true } as any); + await calls.put("00000000000000bb", { by: "a@b", account: "x", at: "2026-11-20T02:00:00Z", members: [m(2, "refused")], said: true } as any); + const said: any[] = [], acts: any[] = []; + const tools = callTools(calls, new Partials(memory().st as any, calls), async (subject: string, body: unknown) => { said.push([subject, body]); }, + async (a) => { acts.push(a); }); + const tool = (name: string) => tools.find((t) => t.name === name)!; + const read: any = await tool("forge_calls").run({}); + assert.deepEqual(read.calls.map((c: any) => [c.call, c.members[0].state]), [["00000000000000bb", "refused"], ["00000000000000aa", "merged"]]); + await assert.rejects(tool("forge_call_say_again").run({ call: "00000000000000aa" }), /names the call .* and why/); + await assert.rejects(tool("forge_call_say_again").run({ call: "00000000000000ff", why: "x" }), /keeps no merge call/); + const again: any = await tool("forge_call_say_again").run({ call: "00000000000000aa", why: "the gate missed it" }); + assert.deepEqual([again.said, acts[0].verb, said[0][0]], [true, "forge_call_say_again", "mesh.seat.git.event.merge-called.00000000000000aa"]); + const none: any = await tool("forge_call_say_again").run({ call: "00000000000000bb", why: "x" }); + assert.equal(none.said, false, "a call that landed none says none"); +}); + +// 47 H2 §812, §811, H-A-402: forge_merged lists a repository's merged pull requests by number, from..to, each with its merge +// commit, when, and the merge call that made it; a number the forge does not hold or one not merged is left out; capped at +// 768 KB with the next number as the cursor. +test("forge_merged lists merged pull requests by number with the merge call that made each", async () => { + const { mergedTool, ANSWER_CAP_BYTES } = await import("../dist/tools/calls.js"); + const sha = (n: number) => String(n % 10).repeat(40); + const forge = { getPullRequest: async (_o: string, _r: string, n: number) => { + if (n === 3) throw new Error("Gitea API /repos/novox/app/pulls/3: 404 Not Found"); + return n === 4 ? { number: n, state: "open", merged: false } : { number: n, state: "closed", merged: true, merge_commit_sha: sha(n), merged_at: `2026-11-2${n}T10:00:00Z` }; + } }; + const calls = { all: async () => [{ call: "00000000000000aa", members: [{ repository: "novox/app", number: 2, state: "merged" }, { repository: "novox/lib", number: 1, state: "merged" }] }] }; + const got: any = await mergedTool(forge as any, calls as any).run({ repository: "novox/app", from: 1, to: 5 }); + assert.deepEqual(got, { repository: "novox/app", from: 1, to: 5, total: 5, merged: [ + { number: 1, "merge-commit": sha(1), "merged-at": "2026-11-21T10:00:00Z" }, + { number: 2, "merge-commit": sha(2), "merged-at": "2026-11-22T10:00:00Z", call: "00000000000000aa" }, + { number: 5, "merge-commit": sha(5), "merged-at": "2026-11-25T10:00:00Z" }] }); + await assert.rejects(mergedTool(forge as any, calls as any).run({ repository: "novox/app", from: 5, to: 4 }), /to not below from/); + // Past 768 KB it is capped, the cursor the next number to read from. + const many: any = await mergedTool(forge as any, { all: async () => [] } as any).run({ repository: "novox/app", from: 5, to: 20_000 }); + assert.equal(many.capped, true); + assert.ok(JSON.stringify(many.merged).length <= ANSWER_CAP_BYTES); + assert.equal(many.cursor, many.merged.at(-1).number + 1); +}); diff --git a/modules/gitea/test/commit-trees.test.ts b/modules/gitea/test/commit-trees.test.ts index 2be41705a..2ce6b6dc0 100644 --- a/modules/gitea/test/commit-trees.test.ts +++ b/modules/gitea/test/commit-trees.test.ts @@ -50,8 +50,9 @@ async function serve(pages: any[]) { res.end(JSON.stringify(pages[page - 1] ?? { sha: COMMIT, tree: [], truncated: false, page, total_count: 0 })); }); await new Promise((r) => server.listen(0, r)); - const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t"); - return { client, server, asked }; + const url = `http://127.0.0.1:${(server.address() as any).port}`; + const client = new GiteaClient(url, "t"); + return { client, server, asked, url }; } test("a commit's trees: the root and the tree of each directory holding a module.json", async () => { @@ -238,12 +239,19 @@ test("files: every blob under each asked directory, recursively, as its path rel }); test("a directory of files the commit lacks, or spelled badly, or a listing the forge cut, fails and answers nothing", async () => { - const { client, server } = await serve([{ sha: COMMIT, url: "u", tree: LISTING, truncated: false, page: 1, total_count: LISTING.length }]); + const { client, server, url } = await serve([{ sha: COMMIT, url: "u", tree: LISTING, truncated: false, page: 1, total_count: LISTING.length }]); try { - await assert.rejects(client.commitTrees("novox", "hq", COMMIT, undefined, ["modules/a", "modules/gone"]), (err: Error) => { - assert.match(err.message, /modules\/gone/); + // The seat answers it with the kind not-found naming the directory (novox/hq design 47 H H-A-232), never failed: the + // holder's own client and failure, as the module runs them. + const { failure } = await import("../dist/seat.js"); + const { GiteaClient } = await import("../dist/client.js"); + await assert.rejects(new GiteaClient(url, "t").commitTrees("novox", "hq", COMMIT, undefined, ["modules/a", "modules/gone"]), (err: Error) => { + const said = failure(err); + assert.equal(said["error-kind"], "not-found", JSON.stringify(said)); + assert.match(said.error, /the directory modules\/gone is not in novox\/hq/); return true; }); + await assert.rejects(client.commitTrees("novox", "hq", COMMIT, undefined, ["modules/a", "modules/gone"]), /modules\/gone/); await assert.rejects(client.commitTrees("novox", "hq", COMMIT, undefined, ["README.md"]), /README\.md/, "a file is no directory"); for (const bad of ["../x", "/abs", "a//b", "modules/a/", "."]) { await assert.rejects(client.commitTrees("novox", "hq", COMMIT, undefined, [bad]), /files/, bad); diff --git a/modules/gitea/test/failedsteps.test.ts b/modules/gitea/test/failedsteps.test.ts index 07e8f32dc..35347cb0c 100644 --- a/modules/gitea/test/failedsteps.test.ts +++ b/modules/gitea/test/failedsteps.test.ts @@ -20,7 +20,7 @@ function memory() { } const ended = (commit: string, outcome: string, extra: Record = {}, over: Record = {}) => ({ v: 1, pipeline: `main.7.nats-${commit.slice(0, 2)}`, module: "nats", branch: "main", commit, at: "2026-11-11T12:00:00Z", - result: { step: "unit", status: "required", outcome, fingerprint: "fp-1", ...extra }, ...over }) as any; + fingerprint: "fp-1", result: { step: "unit", status: "required", outcome, ...extra }, ...over }) as any; test("a head is refused by a required step that failed at its fingerprint in any run, until a rerun passes it", async () => { const { kv, st } = memory(); @@ -45,12 +45,13 @@ test("a head is refused by a required step that failed at its fingerprint in any // A later commit at the fingerprint is refused too, and a failed optional step refuses nothing. await f.stepEnded(ended(C3, "passed")); await judged("a later commit of the same content", C3, "run-on-request nats unit"); - await f.stepEnded(ended(C3, "failed", { step: "lint", status: "optional", fingerprint: "fp-2" })); + await f.stepEnded(ended(C3, "failed", { step: "lint", status: "optional" }, { fingerprint: "fp-2" })); await judged("a failed optional step", C3, "run-on-request nats unit"); assert.equal(kv.has(failedStepKey("nats", "fp-2", "lint")), false); - // A result that names no fingerprint is kept at the one the seat's step event carries (`fingerprint`). - await f.stepEnded(ended(C3, "failed", { step: "lint", fingerprint: undefined }, { fingerprint: "fp-3" })); + // The fingerprint is the body's alone, never the result's (G §585, H-A-93). + await f.stepEnded(ended(C3, "failed", { step: "lint", fingerprint: "fp-x" }, { fingerprint: "fp-3" })); assert.ok(kv.has(failedStepKey("nats", "fp-3", "lint")), "the event's fingerprint is kept"); + assert.equal(kv.has(failedStepKey("nats", "fp-x", "lint")), false, "the result's is never read"); // A plain pass clears nothing; a rerun that passes clears it. await f.stepEnded(ended(C2, "passed")); await judged("a plain pass", C2, "run-on-request nats unit"); @@ -109,7 +110,8 @@ test("a seen key past 30 days is deleted at the next step-ended, a younger one k const now = new Date("2026-11-11T12:00:00Z"); const old = (n: number) => new Date(Date.parse("2026-10-01T00:00:00Z") - n * 60000).toISOString(); await st.put(seenKey(C1, "old"), { v: 1, commit: C1, module: "old", fingerprints: ["x"], at: old(0) }); - await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: "2026-10-20T00:00:00Z" }); + // Younger than 30 days both before the step-ended and before the tool's own clock, today's: kept by both. + await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: new Date(Date.now() - 86_400_000).toISOString() }); await f.stepEnded(ended(C3, "passed")); assert.equal(kv.has(seenKey(C1, "old")), false, "past 30 days: deleted at the next step-ended"); assert.equal(kv.has(seenKey(C2, "young")), true, "younger: kept"); @@ -121,3 +123,21 @@ test("a seen key past 30 days is deleted at the next step-ended, a younger one k const done: any = await runAs({ "mesh/caller": "operator" }, {}, () => tool.run({ why: "stale" })); assert.deepEqual([done.deleted.length, acts[0].verb], [1, "git_seen_expire"]); }); + +// step-unread (G §585, H-A-93): a step-ended of a pipeline's commit without the body's fingerprint records nothing and writes +// the finding, scope module, its subject the step's module, keyed .., warning, resolver operator; a later +// step-ended of that step with its fingerprint clears it. +test("a step-ended without its fingerprint writes step-unread, cleared by the step's later step-ended with it", async () => { + const { stepUnreadFinding } = await import("../failedsteps.js"); + const { kv, st } = memory(); + const findings = memory(); + const f = new FailedSteps(st as any, () => {}, () => true, async () => ({ bytes: 0, keys: 0, max_bytes: 0 }), findings.st as any); + await f.stepEnded(ended(C1, "failed", { fingerprint: "fp-in-result" }, { fingerprint: undefined })); + const { key } = stepUnreadFinding("main.7.nats-" + C1.slice(0, 2), "nats", "unit", ""); + const raised: any = findings.kv.get(key); + assert.deepEqual([raised?.kind, raised?.subject, raised?.severity, raised?.resolver], ["step-unread", { scope: "module", id: "nats" }, "warning", "operator"]); + assert.match(raised.summary, /unit of nats in run main\.7\.nats-/); + assert.equal([...kv.keys()].some((k) => !k.startsWith("seen.")), false, "no failure recorded"); + await f.stepEnded(ended(C1, "failed")); + assert.equal(findings.kv.has(key), false, "cleared by the step's step-ended with its fingerprint"); +}); diff --git a/modules/gitea/test/fakebus.ts b/modules/gitea/test/fakebus.ts new file mode 100644 index 000000000..3c218e648 --- /dev/null +++ b/modules/gitea/test/fakebus.ts @@ -0,0 +1,96 @@ +// The bus as the forge module's token needs it, in memory (design 47 H2 §808, §822): the vault seat's `own-put` in its +// two sealed steps and its `get` sealed to the asker's key, and the runtime's state with a create-only key that lives +// its TTL, as the runtime that launched the bundle answers them. `order` records each own-put and each forge delete a +// test also writes into it, so the delete's place after the own-put can be read. + +import nacl from "tweetnacl"; +import blakejs from "blakejs"; +import { seal } from "@novox/mesh-sdk/seal"; +import { useBroker, type Broker } from "@novox/mesh-sdk/messaging"; +import { useRuntime } from "@novox/mesh-sdk/runtime"; +import { useStateChannel, type StateChange } from "@novox/mesh-sdk/state"; + +export interface Held { value: string; generation: number; changedAt: string } + +export function fakeBus(now: () => Date = () => new Date(), order: string[] = []) { + const vault = new Map(); + const calls = new Map(); + const kv = new Map(); + const watchers: { state: string; key: string; deliver: (c: StateChange) => Promise }[] = []; + let revision = 0; + const keyOf = (state: string, key: string) => `${state}/${key}`; + const live = (k: string) => { + const e = kv.get(k); + if (e && e.until !== null && e.until <= now().getTime()) kv.delete(k); + return kv.get(k); + }; + const tell = async (state: string, key: string, op: "put" | "delete", value?: unknown) => { + revision++; + for (const w of watchers) if (w.state === state && (w.key === "" || w.key === key)) await w.deliver({ state, key, op, value, revision, current: false }); + }; + const broker: Broker = { + async request(key: string, body: Req): Promise { + const b = body as Record; + if (key === "seat:mesh-vault.own-put" && b.call === undefined) { + const keys = nacl.box.keyPair(); + const call = `call-${calls.size + 1}`; + calls.set(call, { name: `module/gitea/${b.name}`, secretKey: keys.secretKey }); + return { call, seal_to: Buffer.from(keys.publicKey).toString("base64"), secret: `module/gitea/${b.name}` } as Res; + } + if (key === "seat:mesh-vault.own-put") { + const c = calls.get(b.call); + if (!c) throw new Error(`no own-put call ${b.call}`); + calls.delete(b.call); + const boxed = new Uint8Array(Buffer.from(b.sealed, "base64")); + const eph = boxed.subarray(0, 32); + const pub = nacl.box.keyPair.fromSecretKey(c.secretKey).publicKey; + const nonce = blakejs.blake2b(Buffer.concat([eph, pub]), undefined, 24); + const opened = nacl.box.open(boxed.subarray(32), nonce, eph, c.secretKey); + if (!opened) throw new Error("the sealed value does not open"); + const generation = (vault.get(c.name)?.generation ?? 0) + 1; + vault.set(c.name, { value: Buffer.from(opened).toString("utf8"), generation, changedAt: now().toISOString() }); + order.push(`own-put ${c.name} ${generation}`); + return { name: c.name, generation } as Res; + } + if (key === "seat:mesh-vault.get") { + const held = vault.get(b.name); + if (!held) throw new Error(`the vault holds no secret named ${b.name}`); + return { name: b.name, generation: held.generation, "changed-at": held.changedAt, sealed: seal(held.value, b.public_key) } as Res; + } + throw new Error(`not played here: ${key}`); + }, + handle: async () => () => {}, + publish: async () => {}, + subscribe: async () => () => {}, + close: async () => {}, + }; + const ask = async (method: string, params: unknown): Promise => { + const p = params as { state: string; key: string; value?: unknown; ttl_seconds?: number }; + const k = keyOf(p.state, p.key); + switch (method) { + case "mesh/state.create": + if (live(k)) throw Object.assign(new Error("the key has a value"), { code: -32010 }); + kv.set(k, { value: p.value, until: p.ttl_seconds ? now().getTime() + p.ttl_seconds * 1000 : null }); + await tell(p.state, p.key, "put", p.value); + return { revision }; + case "mesh/state.get": { + const e = live(k); + return e ? { key: p.key, value: e.value, revision } : null; + } + case "mesh/state.put": + kv.set(k, { value: p.value, until: null }); + await tell(p.state, p.key, "put", p.value); + return { revision }; + case "mesh/state.delete": + kv.delete(k); + await tell(p.state, p.key, "delete"); + return null; + default: + throw new Error(`not played here: ${method}`); + } + }; + useBroker(() => broker); + useRuntime(ask); + useStateChannel({ ask, watch: async (params, deliver) => { const w = params as { state: string; key: string }; watchers.push({ ...w, deliver }); } }); + return { vault, kv, order, ask }; +} diff --git a/modules/gitea/test/gate.test.ts b/modules/gitea/test/gate.test.ts deleted file mode 100644 index 404452c84..000000000 --- a/modules/gitea/test/gate.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; - -// **One writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words, a recheck's pending and -// a trunk's move, each write of a head in the order it was asked. - -const SHA = "a6b08de8507c1703528277e5cefc80548dbc9bb3"; - -/** A forge that keeps the newest status per context, as gitea does, and whose writes take as long as a test says. */ -function aForge() { - const kept: Record = {}; - const written: string[] = []; - let failNext = 0; - let hold: Promise | null = null; - let release = () => {}; - return { - kept, written, - /** The next writes fail: a request the forge did not take. */ - failWrites(n = 1) { - failNext = n; - }, - /** The next writes wait until released: a request in flight. */ - holdWrites() { - hold = new Promise((r) => (release = r)); - }, - release() { - hold = null; - release(); - }, - async headChecks() { - return {}; - }, - async setCommitStatus(_o: string, _r: string, _sha: string, s: { state: string; context: string; description: string }) { - if (hold) await hold; - if (failNext > 0) { - failNext--; - throw new Error("the forge answered 502"); - } - kept[s.context] = { state: s.state, description: s.description, updated_at: new Date().toISOString() }; - written.push(`${s.state} ${s.description}`); - }, - }; -} - -// **A recheck's pending goes through the one writer** (novox/hq issue 456). - -const recheckAt = new Date("2026-10-11T01:30:00Z"); -const checkingAgain = { state: "pending" as const, context: "mesh/merge-gate", description: "checking again: main moved on" }; -const gateOf = (forge: ReturnType) => - `${forge.kept["mesh/merge-gate"].state} ${forge.kept["mesh/merge-gate"].description}`; - -test("a repository as the mesh clones it is told from another", async () => { - const { clonedAs } = await import("../gate.ts"); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/hq.git", "novox", "hq"), true); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-hq.git", "novox", "hq"), false); - assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-controller.git", "novox", "hq"), false); -}); - -test("a recheck the forge does not take fails its caller, and the next write still takes its turn", async () => { - const { GateWriter } = await import("../gate.ts"); - const forge = aForge(); - const gates = new GateWriter(forge, () => recheckAt); - await gates.pending("novox", "hq", SHA); - forge.failWrites(); - await assert.rejects(gates.status("novox", "hq", SHA, checkingAgain)); - await gates.status("novox", "hq", SHA, checkingAgain); - assert.equal(gateOf(forge), "pending checking again: main moved on"); -}); - diff --git a/modules/gitea/test/guard.test.ts b/modules/gitea/test/guard.test.ts index de835a654..e544a1ef8 100644 --- a/modules/gitea/test/guard.test.ts +++ b/modules/gitea/test/guard.test.ts @@ -431,70 +431,20 @@ test("the two new tools are named for what mesh_search is asked, and gitea_api s assert.ok("refused" in judgeApiCall("PATCH", "/repos/a/b/pulls/7", { base: "x" })); }); -// **merge-pull judges the head it is asked at and no check** (design 47 *The seat git*, §314): merge-pull merges the -// head it is named into a base that takes no push, whatever its statuses say, and an id said again after the merge is -// answered performed. -test("merge-pull merges the head the caller names, and refuses one at whose fingerprint a required step failed", async () => { +// The seat git's pull and status (design 47 *The seat git*): an open pull request answers what the forge would merge now, +// and two writes of one head's status land in order. merge-pull is the merge call's (merge-call.test.ts). +test("the seat's pull answers what the forge would merge now, and its status is set on the commit", async () => { const { seatTools } = await import("../dist/seat.js"); const { runAs } = await import("@novox/mesh-sdk/callers"); const bridge = "ace.mesh-delivery-forge-bridge"; - let registered = true; - let failedStep: { run: string; module: string; step: string; fingerprint: string } | null = null; - // The head's one writer of its statuses (gate.ts), over a forge whose first write is still in flight when the next is asked. - const { GateWriter } = await import("../dist/gate.js"); + // The seat's status is set through the forge's client directly (design 47 H §764; H-A-100): no chain of a head's writes. const landed: string[] = []; - let inFlight: Promise | null = null, land = () => {}; - const slow = { - headChecks: async () => ({}), - setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => { - if (inFlight) { const w = inFlight; inFlight = null; await w; } - landed.push(`${s.state} ${s.description}`); - }, - }; - const gates = new GateWriter(slow); - const seat = seatTools(Object.assign(Object.create(client), { setCommitStatus: slow.setCommitStatus }), - { run: async () => ({ stdout: "", code: 0 }), container: "gitea", statuses: gates, registered: () => registered, judge: async () => failedStep }); + const seat = seatTools(Object.assign(Object.create(client), { + setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => { landed.push(`${s.state} ${s.description}`); }, + }), { run: async () => ({ stdout: "", code: 0 }), container: "gitea", registered: () => true, judge: async () => null, + watched: () => new Map() }); const call = (verb: string, args: Record, caller = bridge) => runAs({ "mesh/caller": caller }, args, () => seat.find((t: any) => t.name === `git.${verb}`)!.run(args)) as Promise; - const merge = (extra: Record = {}, caller?: string) => - call("merge-pull", { id: "act-1", repository: "novox/mesh-catalog", number: 7, head: REVIEWED, ...extra }, caller); - const rows: { name: string; set: () => void; caller?: string; extra?: Record; want: RegExp | "merged" | "held"; loud?: boolean; kind?: string }[] = [ - { name: "no registration written yet", set: () => { registered = false; }, want: /no module is registered yet/, kind: "no-registrations" }, - { name: "a head that moved", set: () => { state.head = MOVED; }, want: /its head is 3c4d5e6f7a8b, not the abc1234def56/, kind: "head-moved" }, - { name: "a base no rule guards", set: () => { state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" }, - { name: "a base whose protection was removed after the last branch-moved", set: () => { state.rules = [protectedMain()]; state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" }, - { name: "a base that takes a push", set: () => { state.rules = [{ rule_name: "main", enable_push: true }]; }, want: /guarded by no protection rule/, kind: "unprotected" }, - { name: "a required step failed at the head's fingerprint", set: () => { failedStep = { run: "main.7.nats", module: "nats", step: "unit", fingerprint: "fp-1" }; }, - want: /the unit step of nats failed in run main\.7\.nats/, kind: "policy-failed" }, - { name: "a failed check", set: () => { state.statuses = [{ context: "mesh/check", state: "failure", description: "fail" }]; }, want: "merged" }, - { name: "no status at all", set: () => { state.statuses = []; }, want: "merged" }, - { name: "a check of another trunk", set: () => { state.statuses = judgedAt(MOVED); }, want: "merged" }, - { name: "the id said again after the merge", set: () => { state.merged = true; }, want: "held" }, - { name: "a pull request merged at another head", set: () => { state.merged = true; state.head = MOVED; }, want: /merged at 3c4d5e6f7a8b, not the abc1234def56/ }, - { name: "a closed pull request", set: () => { state.prState = "closed"; }, want: /it is closed/, kind: "git-refused" }, - { name: "a fast-forward", set: () => { state.parents = [REVIEWED]; }, want: "merged" }, - { name: "the merge read back fails", set: () => { state.commitsFail = 502; }, want: "merged" }, - { name: "the forge merged another head", set: () => { state.landed = MOVED; }, want: /WAS merged .*the forge merged 3c4d5e6f7a8b, not the abc1234def56/, loud: true }, - ]; - for (const r of rows) { - registered = true; failedStep = null; state.merged = false; state.head = REVIEWED; state.statuses = judgedAt(TRUNK); state.sent = []; - state.rules = [protectedMain()]; state.prState = "open"; state.parents = null; state.commitsFail = 0; state.landed = ""; - r.set(); - const got = await merge(r.extra, r.caller); - if (r.want === "merged") { - assert.equal(got.performed, true, `${r.name}: ${JSON.stringify(got)}`); - assert.equal(got["merge-commit"], state.mergeCommit, r.name); - assert.equal(state.sent.find((s) => s.path.endsWith("/pulls/7/merge"))?.body.head_commit_id, REVIEWED, r.name); - } else if (r.want === "held") { - assert.deepEqual([got.performed, got.held], [true, true], r.name); - assert.deepEqual(writes(), [], `${r.name}: nothing merged again`); - } else { - assert.match(String(got.refused ?? got.error), r.want, r.name); - if (r.kind) assert.equal(got["refused-kind"], r.kind, r.name); - if (r.kind === "policy-failed") assert.deepEqual([got.run, got.module, got.step], ["main.7.nats", "nats", "unit"], r.name); - assert.deepEqual(writes(), r.loud ? ["POST /repos/novox/mesh-catalog/pulls/7/merge"] : [], `${r.name}: what was merged`); - } - } // A read: an open pull request answers what the forge would merge now; a forge that fails is the kind failed. state.merged = false; state.head = REVIEWED; state.rules = [protectedMain()]; const pull = await call("pull", { repository: "novox/mesh-catalog", number: 7 }); @@ -507,17 +457,9 @@ test("merge-pull merges the head the caller names, and refuses one at whose fing assert.deepEqual([open.pull?.head, open.pull?.state, open.merging?.protected, open.merging?.required], [REVIEWED, "open", true, ["mesh/merge-gate", "mesh/repo-check"]], JSON.stringify(open)); assert.equal("body" in (open.pull ?? {}), false, "never its description"); - // Two writes of one head out of order (issue 456): a recheck's pending still in flight when the verdict is set through the - // seat; the verdict takes its turn after it and is what the head carries. - inFlight = new Promise((r) => (land = r)); - const recheck = gates.pending("novox", "mesh-catalog", REVIEWED); - const verdict = call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success", - context: "mesh/merge-gate", description: "passed" }); - await new Promise((r) => setImmediate(r)); - land(); - await recheck; - assert.equal((await verdict).performed, true); - assert.equal(landed.at(-1), "success passed", `the verdict lands last: ${JSON.stringify(landed)}`); + const verdict = await call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success", + context: "mesh/check", description: "passed" }); + assert.deepEqual([verdict.performed, landed], [true, ["success passed"]]); // A pull request the forge does not have is the kind not-found, so a caller never reads it out of the words. const gone = await call("pull", { repository: "novox/mesh-catalog", number: 404 }); assert.deepEqual([gone.pull, gone["error-kind"]], [undefined, "not-found"], JSON.stringify(gone)); @@ -532,6 +474,7 @@ test("every read and act of the seat git answers its contract, and an error is a const SHA = "a".repeat(40), OTHER = "b".repeat(40); const gone = () => { throw new Error("Gitea API GET /repos/novox/app/pulls/9: 404 Not Found"); }; const down = () => { throw new Error("Gitea API GET /repos/novox/app/x: 502 Bad Gateway"); }; + const unauthorized = () => { throw new Error("Gitea API /repos/novox/app/pulls/9: 401 Unauthorized"); }; const pr = { number: 9, title: "t", state: "open", merged: false, head: "feat/x", head_sha: SHA, base: "main", user: "jochen", html_url: "http://f/9", mergeable: true }; const tagged: string[] = []; let comments: { id: number; body: string }[] = [], noteShown = "", added = 0, noteWritten = 0; @@ -541,7 +484,8 @@ test("every read and act of the seat git answers its contract, and an error is a appliedProtection: async () => ({ rule_name: "main", enable_status_check: true, status_check_contexts: ["mesh/check"] }), getRepo: async () => ({ writes: true }), openPulls: async () => [{ owner: "novox", repo: "app", number: 9, base: "main", head: "feat/x", head_sha: SHA, required: ["mesh/check"], checks: {} }], - tags: async () => ["go/v0.1.1", "go/v0.1.0", "v1"], + forgeVersion: async () => ({ ok: true, version: "1.27.3" }), + tags: async () => [{ tag: "go/v0.1.1", commit: SHA }, { tag: "go/v0.1.0", commit: OTHER }, { tag: "v1", commit: SHA }], commitTrees: async () => ({ root: SHA, trees: { "": SHA } }), getFile: async (_o: string, _r: string, path: string) => (path === "gone" ? (() => { throw new Error("Gitea API GET /repos/novox/app/contents/gone: 404 Not Found"); })() : path === "down" ? down() : { path, sha: OTHER, size: 3, content: "abc" }), compare: async () => ({ total_commits: 2, commits: [{ sha: OTHER }, { sha: SHA }] }), @@ -552,10 +496,10 @@ test("every read and act of the seat git answers its contract, and an error is a }; const run = async (_f: string, args: string[]) => args.includes("show") || args.includes("--ref") && !args.includes("append") ? { stdout: noteShown, code: noteShown ? 0 : 1 } : (noteWritten++, { stdout: "", code: 0 }); - const seat = seatTools(forge as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null }); + const seat = seatTools(forge as any, { run: run as any, container: "gitea", registered: () => true, judge: async () => null, watched: () => new Map() }); const call = (verb: string, args: Record, over: Record = {}) => { const t = seat.find((x: any) => x.name === `git.${verb}`)!; - const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null }); + const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", registered: () => true, judge: async () => null, watched: () => new Map() }); return runAs({ "mesh/caller": "ace.x" }, args, () => wrapped.find((x: any) => x.name === t.name)!.run(args)) as Promise; }; const rows: [string, string, Record, Record, (a: any) => unknown, unknown][] = [ @@ -563,13 +507,18 @@ test("every read and act of the seat git answers its contract, and an error is a ["pull", "by merge commit", { repository: "novox/app", "merge-commit": OTHER }, {}, (a) => [a.pull.state, a.pull["merge-commit"], a.merging], ["merged", OTHER, undefined]], ["pull", "unknown", { repository: "novox/app", number: 404 }, {}, (a) => [a.pull, a["error-kind"]], [undefined, "not-found"]], ["pull", "forge down", { repository: "novox/app", number: 9 }, { getPullRequest: down }, (a) => [a.pull, a["error-kind"]], [undefined, "failed"]], - ["branch", "a branch a rule guards", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: false }) }, (a) => [a.head, a.protected], [SHA, true]], - ["branch", "a branch no rule guards", { repository: "novox/app", branch: "scratch" }, { branchHead: async () => SHA, appliedProtection: async () => null }, (a) => [a.head, a.protected], [SHA, false]], - ["branch", "a rule that takes a push", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: true }) }, (a) => [a.protected], [false]], + // 47 H2 §776: a 401, 502, 503 or connection fault is away when the forge's version read fails or names its store + // unavailable; with the read passing a 401 (the fresh token refused too) is the forge refusing the mesh's admin account. + ["pull", "502 and the version read failing is away", { repository: "novox/app", number: 9 }, { getPullRequest: down, forgeVersion: async () => ({ ok: false, words: "no answer", store: false }) }, (a) => [a.pull, a["error-kind"], a.part], [undefined, "away", "the forge"]], + ["pull", "401 and the store named unavailable is away", { repository: "novox/app", number: 9 }, { getPullRequest: unauthorized, forgeVersion: async () => ({ ok: false, words: "database is down", store: true }) }, (a) => [a["error-kind"], a.part, /401/.test(a.words)], ["away", "the forge's store", true]], + ["pull", "a connection fault and the version read failing is away", { repository: "novox/app", number: 9 }, { getPullRequest: async () => { throw new TypeError("fetch failed"); }, forgeVersion: async () => ({ ok: false, words: "fetch failed", store: false }) }, (a) => [a["error-kind"]], ["away"]], + ["pull", "401 with the version read passing is refused", { repository: "novox/app", number: 9 }, { getPullRequest: unauthorized }, (a) => [a["error-kind"], /refuses the mesh's admin account/.test(a.error), /[Cc]reate/.test(a.error)], ["refused", true, false]], + ["branch", "a branch's head, no protection read (ADR 0682 §13)", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => { throw new Error("read"); } }, (a) => [a.head, a.protected, a.error], [SHA, undefined, undefined]], ["branch", "no such branch", { repository: "novox/app", branch: "nope" }, { branchHead: gone }, (a) => [a.head, a["error-kind"]], [undefined, "not-found"]], ["open-pulls", "one", {}, {}, (a) => [a.pulls.length, a.pulls[0].required], [1, ["mesh/check"]]], ["open-pulls", "forge down", {}, { openPulls: down }, (a) => [a.pulls, a["error-kind"]], [undefined, "failed"]], - ["tags", "a page", { repository: "novox/app", prefix: "go/" }, {}, (a) => [a.tags, a.page, a.bound, a.more], [["go/v0.1.1", "go/v0.1.0"], 1, 50, undefined]], + // 47 H2 §796: each tag names its commit, at the seat's form 3 (raised by H-A-471's note). + ["tags", "a page, each tag with its commit", { repository: "novox/app", prefix: "go/" }, {}, (a) => [a.tags, a.page, a.bound, a.more, a.form], [[{ tag: "go/v0.1.1", commit: SHA }, { tag: "go/v0.1.0", commit: OTHER }], 1, 50, undefined, 3]], ["tags", "forge down", { repository: "novox/app" }, { tags: down }, (a) => [a.tags, a["error-kind"]], [undefined, "failed"]], ["trees", "root", { repository: "novox/app", commit: SHA }, {}, (a) => [a.commit, a.root], [SHA, SHA]], ["trees", "forge down", { repository: "novox/app", commit: SHA }, { commitTrees: down }, (a) => [a.root, a["error-kind"]], [undefined, "failed"]], @@ -583,6 +532,9 @@ test("every read and act of the seat git answers its contract, and an error is a ["tag", "written", { repository: "novox/app", tag: "go/v1.2.3", commit: SHA }, { tagCommit: async () => null, createTag: async (_o: string, _r: string, tag: string, c: string) => { tagged.push(`${tag}@${c}`); } }, (a) => [a.performed, tagged.splice(0)], [true, [`go/v1.2.3@${SHA}`]]], ["tag", "already at that commit", { repository: "novox/app", tag: "go/v1.2.3", commit: SHA }, { tagCommit: async () => SHA, createTag: async () => { throw new Error("written again"); } }, (a) => [a.performed, a.error], [true, undefined]], ["tag", "at another commit is never moved", { repository: "novox/app", tag: "go/v1.2.3", commit: SHA }, { tagCommit: async () => OTHER }, (a) => [a.performed, a["error-kind"]], [undefined, "refused"]], + // 47 H2 §796: a Go package's tag is /v. + ["tag", "a package directory's version", { repository: "novox/app", tag: "modules/x/go/v1.2.3", commit: SHA }, { tagCommit: async () => null, createTag: async (_o: string, _r: string, tag: string, c: string) => { tagged.push(`${tag}@${c}`); } }, (a) => [a.performed, tagged.splice(0)], [true, [`modules/x/go/v1.2.3@${SHA}`]]], + ["tag", "no directory", { repository: "novox/app", tag: "v1.2.3", commit: SHA }, {}, (a) => [a.performed, a["error-kind"]], [undefined, "refused"]], ["tag", "no Go version", { repository: "novox/app", tag: "v1", commit: SHA }, {}, (a) => [a.performed, a["error-kind"]], [undefined, "refused"]], ["status", "refused state", { id: "s1", repository: "novox/app", commit: SHA, context: "c", state: "bogus" }, {}, (a) => [a.performed, a["error-kind"]], [undefined, "refused"]], ["comment", "first time", { id: "c1", repository: "novox/app", number: 9, text: "hi" }, {}, (a) => [a.performed, a.held, added], [true, undefined, 1]], @@ -618,7 +570,10 @@ test("the first registrations are learned from the seat mesh-catalog's verb at t const held = reg(JSON.stringify({ registrations: [{ module: "mesh-sdk" }] })); await held.start(); assert.equal(held.written, true, "a registration held at the start"); - const down = reg(new Error("no responders")); + // A failed first view is said and asked again (H-A-471, second addendum): the test's wait answers it with none. + let downAnswer: unknown = new Error("no responders"); + const down = new Registrations(async () => { if (downAnswer instanceof Error) throw downAnswer; return downAnswer; }, (l) => said.push(l), + async () => { downAnswer = { registrations: [] }; }); await down.start(); assert.equal(down.written, false); assert.match(said.join("\n"), /could not be read: no responders/, "a failed first view is said, never taken as none silently"); diff --git a/modules/gitea/test/kept.test.ts b/modules/gitea/test/kept.test.ts index b39114667..5595321c0 100644 --- a/modules/gitea/test/kept.test.ts +++ b/modules/gitea/test/kept.test.ts @@ -16,8 +16,8 @@ test("the states the module announces are the states its manifest declares", asy test("the announcement has the layout mesh-sdk's go/announce reads: version 1, the module, the node, the states sorted by name", async () => { const { statesAnnouncement } = await import("../kept.ts"); - assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] }); - assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] }); + assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); + assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); }); test("index.ts says the announcement as the event `states` before the tools are served", () => { diff --git a/modules/gitea/test/mainrules.test.ts b/modules/gitea/test/mainrules.test.ts index 37916cd70..1d26b745c 100644 --- a/modules/gitea/test/mainrules.test.ts +++ b/modules/gitea/test/mainrules.test.ts @@ -2,11 +2,11 @@ // writes nothing at the forge, true puts main's rule right as before. import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { keepMainRules, mainRulesStep, LEFT_AS_SET } from "../dist/mainrules.js"; +import { keepMainRules } from "../dist/mainrules.js"; function env(body?: string): NodeJS.ProcessEnv { if (body === undefined) return {}; @@ -15,6 +15,14 @@ function env(body?: string): NodeJS.ProcessEnv { return { MESH_GITEA_CONFIG_FILE: f }; } +// No timer keeps main's rules (design 47 H §764, H-A-100): the setting's description says when it acts, and names none. +test("the setting's description names no timer", () => { + const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8")); + const said: string = manifest.config["keep-main-rules"].description; + assert.match(said, /token is minted/); + assert.doesNotMatch(said, /every ten minutes|every \w+ minutes/); +}); + test("the setting is false unless the config says true", () => { assert.equal(keepMainRules(env()), false); assert.equal(keepMainRules(env("{}")), false); @@ -23,25 +31,6 @@ test("the setting is false unless the config says true", () => { assert.equal(keepMainRules(env('{"keep-main-rules":true}')), true); }); -test("false: the step never writes and says once that the rules are left", async () => { - let writes = 0; - const said: string[] = []; - const step = mainRulesStep(false, async () => { writes++; return ["a"]; }, (l) => said.push(l)); - await step(); await step(); await step(); - assert.equal(writes, 0); - assert.deepEqual(said, [LEFT_AS_SET]); - assert.match(LEFT_AS_SET, /main's rules are left as set at the forge \(keep-main-rules is false\)/); -}); - -test("true: every step puts the rules right", async () => { - let writes = 0; - const said: string[] = []; - const step = mainRulesStep(true, async () => { writes++; return ["a", "b"]; }, (l) => said.push(l)); - await step(); await step(); - assert.equal(writes, 2); - assert.deepEqual(said, ["[gitea] main's rule is right in 2 repositories"]); -}); - test("a token mint's account setup writes no protection while keep-main-rules is false, and does when true", async () => { const { setUpToolsAccount } = await import("../dist/tools-account.js"); for (const [keep, want] of [[false, 0], [true, 1]] as const) { diff --git a/modules/gitea/test/memstate.ts b/modules/gitea/test/memstate.ts new file mode 100644 index 000000000..afddeed9c --- /dev/null +++ b/modules/gitea/test/memstate.ts @@ -0,0 +1,11 @@ +// A state of the runtime in memory, for the tests of the merge calls (calls.ts, partials.ts). +export function memory() { + const kv = new Map(); + return { kv, st: { + get: async (k: string) => (kv.has(k) ? { key: k, value: structuredClone(kv.get(k)), revision: 1 } : null), + put: async (k: string, v: unknown) => { kv.set(k, structuredClone(v)); return 1; }, + delete: async (k: string) => { kv.delete(k); }, + keys: async () => [...kv.keys()].sort(), + watch: async () => {}, + } }; +} diff --git a/modules/gitea/test/merge-call.test.ts b/modules/gitea/test/merge-call.test.ts new file mode 100644 index 000000000..e44d0c27f --- /dev/null +++ b/modules/gitea/test/merge-call.test.ts @@ -0,0 +1,196 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +// **One merge call, every member judged before any is merged** (novox/hq design 47 H §734, §735; ADR 0682 §13; H-A-21, +// H-A-22, H-A-47): the seat git's merge-pull takes pulls and by, judges each member (its head, its base a watched branch, +// not merged already, no required step failed at its fingerprint) and no branch protection, merges none when one is +// refused, else merges them in the order named, and answers the call and each member's outcome once. + +const A = "a".repeat(40), B = "b".repeat(40), MOVED = "c".repeat(40); +const CALL = "0123456789abcdef"; + +interface FakePull { base: string; head: string; state: string; merged: boolean; merge?: string; refuse?: string } + +/** A forge of pull requests by `#`, recording each merge asked. It has no protection API: a call that + * read a branch's protection would throw. */ +function forge(pulls: Record) { + const merges: string[] = []; + const key = (o: string, r: string, n: number) => `${o}/${r}#${n}`; + return { + merges, + getPullRequest: async (o: string, r: string, n: number) => { + const p = pulls[key(o, r, n)]; + if (!p) throw new Error(`Gitea API GET /repos/${o}/${r}/pulls/${n}: 404 {}`); + return { number: n, title: "", state: p.state, merged: p.merged, base: p.base, head: "b", head_sha: p.head, + ...(p.merged ? { merge_commit_sha: p.merge ?? "m".repeat(40) } : {}) } as any; + }, + mergePullRequest: async (o: string, r: string, n: number, _m: string, _d: boolean, head: string) => { + const p = pulls[key(o, r, n)]; + merges.push(key(o, r, n)); + if (p.refuse) throw new Error(`Gitea API POST /repos/${o}/${r}/pulls/${n}/merge: 409 ${p.refuse}`); + assert.equal(head, p.head); + p.merged = true; + p.merge = `${n}`.repeat(40).slice(0, 40); + }, + commitParents: async (_o: string, _r: string, sha: string) => [sha, "x"], + }; +} + +const watched = new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]); + +async function call(f: ReturnType, args: Record, over: Record = {}, caller = "person.jochen") { + const { mergeCall } = await import("../dist/mergecall.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const deps = { registered: () => true, watched: () => watched, judge: async () => null, newCall: () => CALL, ...over }; + return runAs({ "mesh/caller": caller }, args, () => mergeCall(f as any, args, deps as any)) as Promise; +} + +const two = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/lib", number: 9, head: B }] }; +const open = (): Record => ({ "novox/app#5": { base: "main", head: A, state: "open", merged: false }, + "novox/lib#9": { base: "main", head: B, state: "open", merged: false } }); + +test("a merge call merges its members in the order named and answers each with its merge commit; one pull request is a list of one", async () => { + const f = forge(open()); + const got = await call(f, two); + assert.equal(got.call, CALL); + assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"]); + assert.deepEqual(got.members.map((m: any) => [m.repository, m.number, m.state, m.commit]), + [["novox/app", 5, "merged", "5".repeat(40)], ["novox/lib", 9, "merged", "9".repeat(40)]]); + const one = forge(open()); + const single = await call(one, { by: "lead@shanks", pulls: [two.pulls[0]] }); + assert.deepEqual([one.merges, single.members.length, single.members[0].state], [["novox/app#5"], 1, "merged"]); +}); + +test("a member refused at judging merges none and names every refused member and why", async () => { + const rows: { name: string; set: (p: Record) => void; over?: Record; why: RegExp }[] = [ + { name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ }, + { name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ }, + { name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ }, + { name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ }, + { name: "a required step failed at its head's fingerprint", + set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) }, + why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ }, + ]; + for (const r of rows) { + const pulls = open(); + r.set(pulls); + const f = forge(pulls); + const got = await call(f, two, r.over); + assert.deepEqual(f.merges, [], `${r.name}: nothing merged`); + assert.equal(got.members[0].state, "judged", r.name); + assert.equal(got.members[1].state, "refused", r.name); + assert.match(got.members[1].why, r.why, r.name); + } +}); + +// **A repository of no module is merged plainly** (design 47 H2 H-A-471 and its addendum): a member whose repository has +// no watched branch (no entry, or an empty set, in the registrations' watched branches) is judged against nothing of the +// module graph (no failed required step), merged in the order named, answered merged with the note no delivery, and left +// out of merge-called; the watched members of the same call are judged and delivered as any call's. A watched +// repository whose base is unwatched stays refused (the row above). +test("a member of a repository with no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => { + const NOTE = "no delivery: the repository has no watched branch"; + const rows: { name: string; watched: Map> }[] = [ + { name: "no entry", watched: new Map([["novox/app", new Set(["main"])]]) }, + { name: "an empty set", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set()]]) }, + ]; + for (const r of rows) { + const pulls = open(); + pulls["novox/hq#799"] = { base: "main", head: B, state: "open", merged: false }; + const f = forge(pulls); + const judged: string[] = []; + const said: any[] = []; + const mixed = { by: "lead@shanks", pulls: [{ repository: "novox/hq", number: 799, head: B }, two.pulls[0]] }; + const got = await call(f, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); }, + judge: async (h: string) => { judged.push(h); return { run: "main.7", module: "hq", step: "unit", fingerprint: "fp" }; } }); + assert.deepEqual(f.merges, [], `${r.name}: a refused watched member merges none`); + assert.deepEqual(judged, [A], `${r.name}: the unwatched member is judged against nothing of the module graph`); + // The watched member's failed required step refuses the call whole, the unwatched one judged plainly beside it. + assert.equal(got.members[0].state, "judged", r.name); + assert.equal(got.members[1].state, "refused", r.name); + // Without the failed step the call lands both: the unwatched noted, merge-called naming only the watched. + const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: "main", head: B, state: "open", merged: false } })); + said.length = 0; + const landed = await call(f2, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } }); + assert.deepEqual(f2.merges, ["novox/hq#799", "novox/app#5"], `${r.name}: merged in the order named`); + assert.deepEqual(landed.members.map((m: any) => [m.repository, m.state, m.note, m.why]), + [["novox/hq", "merged", NOTE, undefined], ["novox/app", "merged", undefined, undefined]], r.name); + assert.deepEqual(said.map((b) => b.members.map((m: any) => m.repository)), [["novox/app"]], `${r.name}: merge-called leaves it out`); + // A call of unwatched members alone merges and starts no delivery: no merge-called. + const f3 = forge({ "novox/hq#799": { base: "main", head: B, state: "open", merged: false } }); + said.length = 0; + const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched, + say: async (_s: string, body: unknown) => { said.push(body); } }); + assert.deepEqual([f3.merges, alone.members[0].state, alone.members[0].note, said], [["novox/hq#799"], "merged", NOTE, []], r.name); + } +}); + +// **A plain merge needs a view read since the last change heard** (design 47 H2 H-A-471, second addendum): while the +// watched branches are unread, or were read before a later registration-changed, every member is refused ("the watched +// branches are not read yet"), never merged with the note; a view read after the change merges the unwatched member +// plainly. A read that fails is said and asked again until it answers. +test("a member is merged plainly only from a watched-branches view read since the last registration-changed", async () => { + const { Registrations } = await import("../dist/registrations.js"); + const NOT_READ = "the watched branches are not read yet"; + const said: string[] = []; + const waits: number[] = []; + let answer: unknown = new Error("no responders"); + const reg = new Registrations(async () => { if (answer instanceof Error) throw answer; return answer; }, (l) => said.push(l), + async (ms) => { waits.push(ms); answer = { registrations: [{ module: "app", origin: "novox/app", branches: ["main"] }] }; }); + const hq = { by: "lead@shanks", pulls: [{ repository: "novox/hq", number: 799, head: B }, two.pulls[0]] }; + const pulls = () => Object.assign(open(), { "novox/hq#799": { base: "main", head: B, state: "open", merged: false } }); + const view = () => (reg.current ? reg.watched : null); + reg.hear({ module: "app", moved: ["watch"], version: 1, warrant: "q-1" }); + // Unread: every member refused, nothing merged. + const f1 = forge(pulls()); + const unread = await call(f1, hq, { watched: view }); + assert.deepEqual([f1.merges, unread.members.map((m: any) => [m.state, m.why, m.note])], + [[], [["refused", NOT_READ, undefined], ["refused", NOT_READ, undefined]]], "an unread view refuses every member"); + // A failed read is said and asked again until it answers; read, the view is current. + await reg.start(); + assert.deepEqual([waits, reg.current], [[2_000], true]); + assert.match(said.join("\n"), /could not be read: no responders; no member is merged plainly until they are, asked again in 2s/); + assert.ok(reg.readAt && reg.changedAt && reg.readAt >= reg.changedAt, "the times of the last read and the last change are kept"); + // A registration-changed heard after the read: stale, every member refused again. + reg.hear({ module: "app", moved: ["watch"], version: 2, warrant: "q-2" }); + const f2 = forge(pulls()); + const stale = await call(f2, hq, { watched: view }); + assert.deepEqual([f2.merges, stale.members.map((m: any) => m.why)], [[], [NOT_READ, NOT_READ]], "a view read before a later change refuses"); + // A change heard while a read is asked leaves the view stale. + let release!: () => void; + answer = { registrations: [{ module: "app", origin: "novox/app", branches: ["main"] }] }; + const slow = new Registrations(() => new Promise((r) => { release = () => r(answer); })); + const asking = slow.start(); + slow.hear({ module: "app", moved: ["watch"], version: 3, warrant: "q-3" }); + release(); + await asking; + assert.equal(slow.current, false, "a read asked before the change heard is not since it"); + // Read again after the change: the unwatched member merges plainly with the note, the watched one as any call's. + await reg.start(); + const f3 = forge(pulls()); + const landed = await call(f3, hq, { watched: view }); + assert.deepEqual([f3.merges, landed.members.map((m: any) => [m.state, m.note])], + [["novox/hq#799", "novox/app#5"], [["merged", "no delivery: the repository has no watched branch"], ["merged", undefined]]]); +}); + +test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => { + const f = forge(open()); + await assert.rejects(call(f, two, {}, ""), /proved no caller account/); + await assert.rejects(call(f, { pulls: two.pulls }), /by is the caller as who@node/); + await assert.rejects(call(f, two, { registered: () => false }), /no module is registered yet/); + await assert.rejects(call(f, { by: "lead@shanks", pulls: [] }), /one or more members/); + await assert.rejects(call(f, { by: "lead@shanks", pulls: [two.pulls[0], two.pulls[0]] }), /named twice/); + assert.deepEqual(f.merges, []); +}); + +test("the forge refusing a member after every member was judged stops the call: the landed member merged, the rest refused", async () => { + const pulls = open(); + pulls["novox/lib#9"].refuse = "merge conflict"; + const three = { by: "lead@shanks", pulls: [...two.pulls, { repository: "novox/app", number: 6, head: A }] }; + pulls["novox/app#6"] = { base: "main", head: A, state: "open", merged: false }; + const f = forge(pulls); + const got = await call(f, three); + assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"], "the third is never asked"); + assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused", "refused"]); + assert.match(got.members[1].why, /the forge refused the merge: .*merge conflict/); +}); diff --git a/modules/gitea/test/merge-partial.test.ts b/modules/gitea/test/merge-partial.test.ts new file mode 100644 index 000000000..12d6a5b7d --- /dev/null +++ b/modules/gitea/test/merge-partial.test.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { memory } from "./memstate.ts"; + +// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; acceptance test 115; +// H-A-81): a forge that refuses the second merge gives one merge-called with the first member and `refused`, and +// merge-partial (scope delivery, id the call, urgent, resolver operator) raised; a later call landing the refused member +// clears it, and forge_partial_clear clears one by hand after the hand-act log took it. + +const A = "a".repeat(40), B = "b".repeat(40); + +test("the forge refusing the second merge says what landed, raises merge-partial, and a later call landing it clears it", async () => { + const { mergeCall } = await import("../dist/mergecall.js"); + const { Calls } = await import("../dist/calls.js"); + const { Partials, partialKey } = await import("../dist/partials.js"); + const { callTools } = await import("../dist/tools/calls.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const { st } = memory(); + const findings = memory(); + const calls = new Calls(st as any); + const partials = new Partials(findings.st as any, calls); + const said: any[] = []; + const pulls: Record = { 5: { head: A, merged: false, refuse: false }, 9: { head: B, merged: false, refuse: true } }; + const forge = { + getPullRequest: async (_o: string, _r: string, n: number) => ({ number: n, state: "open", merged: pulls[n].merged, base: "main", + head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }), + mergePullRequest: async (_o: string, r: string, n: number) => { + if (pulls[n].refuse) throw new Error(`Gitea API POST /repos/novox/${r}/pulls/${n}/merge: 409 merge conflict`); + pulls[n].merged = true; + }, + commitParents: async () => [], + }; + let clock = Date.parse("2026-11-20T03:00:00Z"); + const run = (call: string, numbers: number[]) => { + const args = { by: "lead@shanks", pulls: numbers.map((n) => ({ repository: n === 5 ? "novox/app" : "novox/lib", number: n, head: pulls[n].head })) }; + return runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, { registered: () => true, + watched: () => new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]), judge: async () => null, + newCall: () => call, calls, partials, say: async (_s: string, body: unknown) => { said.push(body); }, + now: () => new Date((clock += 1000)) } as any)) as Promise; + }; + const got = await run("00000000000000aa", [5, 9]); + assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused"]); + assert.equal(said.length, 1); + assert.deepEqual(said[0].members.map((m: any) => m.number), [5]); + assert.deepEqual(said[0].refused.map((m: any) => [m.repository, m.number]), [["novox/lib", 9]]); + assert.match(said[0].refused[0].why, /merge conflict/); + const raised: any = findings.kv.get(partialKey("00000000000000aa")); + assert.deepEqual([raised?.kind, raised?.subject, raised?.severity, raised?.resolver], ["merge-partial", { scope: "delivery", id: "00000000000000aa" }, "urgent", "operator"]); + assert.match(raised.summary, /landed novox\/app#5 and not novox\/lib#9/); + // A later call landing the refused member clears it. + pulls[9].refuse = false; + await run("00000000000000bb", [9]); + assert.equal(findings.kv.has(partialKey("00000000000000aa")), false, "cleared by the later call"); + // By hand: written in the hand-act log first, then cleared. + pulls[9] = { head: B, merged: false, refuse: true }; + pulls[5] = { head: A, merged: false, refuse: false }; + await run("00000000000000cc", [5, 9]); + assert.equal(findings.kv.has(partialKey("00000000000000cc")), true); + const acts: any[] = []; + const tool = callTools(calls, partials, async () => {}, async (a) => { acts.push(a); }).find((t) => t.name === "forge_partial_clear")!; + await assert.rejects(tool.run({ call: "00000000000000cc" }), /names the call .* and why/); + const failing = callTools(calls, partials, async () => {}, async () => { throw new Error("down"); }).find((t) => t.name === "forge_partial_clear")!; + await assert.rejects(failing.run({ call: "00000000000000cc", why: "dropped" }), /not recorded, so nothing was cleared/); + assert.equal(findings.kv.has(partialKey("00000000000000cc")), true); + const done: any = await runAs({ "mesh/caller": "person.jochen" }, {}, () => tool.run({ call: "00000000000000cc", why: "the lib change is dropped" })); + assert.deepEqual([done.cleared, acts[0].verb, findings.kv.has(partialKey("00000000000000cc"))], [true, "forge_partial_clear", false]); +}); diff --git a/modules/gitea/test/paging.test.ts b/modules/gitea/test/paging.test.ts index aefda7dee..f5d3010c4 100644 --- a/modules/gitea/test/paging.test.ts +++ b/modules/gitea/test/paging.test.ts @@ -41,33 +41,6 @@ async function serve(count: number, heads: Record) { return { client, ...f }; } -test("a new head beyond the newest 20 open pull requests is announced, exactly once", async () => { - const { headsToAnnounce } = await import("../pulls.ts"); - // 25 open, every head announced before; #3 — the 23rd most recently updated — got a new head. - const announced: Record = {}; - for (let n = 1; n <= 25; n++) announced[`novox/hq#${n}@main`] = sha(n, "a"); - const { client, server, asked } = await serve(25, { 3: sha(3, "b") }); - try { - // The fault: the newest 20 alone do not hold it. - const newest = await client.listPullRequests("novox", "hq", { state: "open", sort: "recentupdate", limit: "20" }); - assert.deepEqual(headsToAnnounce("novox/hq", newest, announced), [], "the newest 20 miss #3's new head"); - asked.length = 0; - const said: string[] = []; - for (let pass = 0; pass < 2; pass++) { - // The sweep, as index.ts's pollPulls asks: no floor, every page. - const open = await client.listOpenPullsSince("novox", "hq", ""); - for (const p of headsToAnnounce("novox/hq", open, announced)) { - said.push(`#${p.number}@${p.head_sha}`); - announced[`novox/hq#${p.number}@${p.base}`] = String(p.head_sha); - } - } - assert.deepEqual(said, [`#3@${sha(3, "b")}`], "the new head past the newest 20, announced once over two passes"); - assert.ok(asked.every((q) => q.get("state") === "open" && q.get("sort") === "recentupdate"), "asked newest first"); - } finally { - server.close(); - } -}); - test("a pass pages until it reaches back past its floor, and no further", async () => { // 130 open pull requests, #n updated n hours after T0: page 1 holds #130–#81, page 2 #80–#31, page 3 #30–#1. const { client, server, asked } = await serve(130, {}); @@ -135,3 +108,48 @@ test("a file over 512 KiB is refused from its directory listing, and its body is await new Promise((r) => server.close(() => r())); } }); + +// 47 H2 §796: a tag names its commit; a tag the forge names no commit for is an error, never a tag without one. +test("the forge's tags are read with the commit each names", async () => { + const { GiteaClient } = await import("../client.ts"); + let body: unknown[] = []; + const server = createServer((_req, res) => res.end(JSON.stringify(body))); + await new Promise((r) => server.listen(0, r)); + try { + const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t"); + body = [{ name: "go/v0.1.1", commit: { sha: "a".repeat(40) } }, { name: "go/v0.1.0", commit: { sha: "b".repeat(40) } }]; + assert.deepEqual(await client.tags("novox", "hq", 1, 51), [{ tag: "go/v0.1.1", commit: "a".repeat(40) }, { tag: "go/v0.1.0", commit: "b".repeat(40) }]); + body = [{ name: "go/v0.1.2" }]; + await assert.rejects(client.tags("novox", "hq", 1, 51), /named no commit for novox\/hq's tag go\/v0.1.2/); + } finally { + server.close(); + } +}); + +// 47 H2 §776: the forge's own version read, unauthenticated, tells the forge away from its refusal. +test("the forge's version read says whether the forge answers and whether its store is away", async () => { + const { GiteaClient } = await import("../client.ts"); + let status = 200, body = `{"version":"1.27.3"}`; + const auth: (string | undefined)[] = []; + const server = createServer((req, res) => { auth.push(req.headers.authorization); res.statusCode = status; res.end(body); }); + await new Promise((r) => server.listen(0, r)); + const port = (server.address() as any).port; + try { + const client = new GiteaClient(`http://127.0.0.1:${port}`, "t"); + const rows: [number, string, unknown][] = [ + [200, `{"version":"1.27.3"}`, { ok: true, version: "1.27.3" }], + [500, "database is locked", { ok: false, store: true }], + [503, "Service Unavailable", { ok: false, store: false }], + ]; + for (const [s, b, want] of rows) { + status = s; body = b; + const got: any = await client.forgeVersion(); + assert.deepEqual(got.ok ? got : { ok: got.ok, store: got.store }, want, `${s} ${b}`); + } + assert.deepEqual(auth.filter(Boolean), [], "the version read is unauthenticated"); + } finally { + server.close(); + } + const gone: any = await new GiteaClient(`http://127.0.0.1:${port}`, "t").forgeVersion(); + assert.deepEqual([gone.ok, gone.store], [false, false]); +}); diff --git a/modules/gitea/test/pulls.test.ts b/modules/gitea/test/pulls.test.ts index bbc0daf13..3e62b2581 100644 --- a/modules/gitea/test/pulls.test.ts +++ b/modules/gitea/test/pulls.test.ts @@ -2,32 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { createServer } from "node:http"; -// A pull request's merge check (novox/hq to-be 45 §9): each new head announced once, and the verdict set -// where the pull request shows it — an error never as a success. - -test("each open pull request's new head is announced once, and nothing closed or merged", async () => { - const { headsToAnnounce } = await import("../pulls.ts"); - const pulls = [ - { number: 1, title: "a", state: "open", merged: false, head_sha: "aaa", base: "main", html_url: "" }, - { number: 2, title: "b", state: "open", merged: false, head_sha: "bbb", html_url: "" }, - { number: 3, title: "c", state: "closed", merged: true, head_sha: "ccc", html_url: "" }, - { number: 4, title: "d", state: "open", merged: false, html_url: "" }, - ]; - const announced = { "novox/mesh-catalog#1@main": "aaa", "novox/mesh-catalog#2@": "old" }; - assert.deepEqual(headsToAnnounce("novox/mesh-catalog", pulls, announced).map((p) => p.number), [2], - "only a head not announced, of a pull request that is open"); -}); - -test("a pull request retargeted keeps its head and is announced again, into its new base (de-spiegel #6)", async () => { - const { headsToAnnounce, headKey } = await import("../pulls.ts"); - const was = { number: 6, title: "a", state: "open", merged: false, head_sha: "aaa", base: "old-trunk", html_url: "" }; - const announced: Record = { [headKey("novox/de-spiegel", 6, "old-trunk")]: "aaa" }; - assert.deepEqual(headsToAnnounce("novox/de-spiegel", [was], announced), [], "the same head into the same base is announced once"); - const retargeted = { ...was, base: "main" }; - assert.deepEqual(headsToAnnounce("novox/de-spiegel", [retargeted], announced).map((p) => p.number), [6], - "the same head into a new base is judged afresh"); - assert.notEqual(headKey("novox/de-spiegel", 6, "main"), headKey("novox/de-spiegel", 6, "old-trunk")); -}); +// A commit status, set where the pull request shows it (the seat git's status). test("a commit status is set on the commit, under the merge check's context", async () => { const { GiteaClient } = await import("../client.ts"); @@ -53,35 +28,3 @@ test("a commit status is set on the commit, under the merge check's context", as assert.equal(seen!.body.state, "failure"); assert.equal(seen!.body.context, "mesh/merge-gate"); }); - -// **A pending check says where it is** (novox/hq issue 446): announced, it waits in the build queue, since the time the -// operator reads — not "mapping this head onto its module graph" for the ten minutes of a controller check. -test("a head announced is pending in the build queue, since the local time it was announced", async () => { - const { pendingWords } = await import("../pulls.ts"); - assert.equal(pendingWords(new Date(2026, 9, 11, 3, 8, 50)), "waiting in the build queue since 03:08"); - assert.equal(pendingWords(new Date(2026, 9, 11, 14, 0, 0)), "waiting in the build queue since 14:00"); -}); - -// Issue 1301 (ADR 0503 §3, §5): gitea writes the controller's statuses only where the base still requires them. hq's main -// requires mesh/repo-check alone, so no mesh/merge-gate is written on its heads. -test("a base's required statuses decide which of the controller's statuses are written", async () => { - const { maintained, writesGate, CHECK_STATUS } = await import("../pulls.ts"); - assert.equal(CHECK_STATUS, "mesh/check"); - assert.deepEqual(maintained(undefined), ["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before"); - assert.deepEqual(maintained(["mesh/repo-check"]), ["mesh/repo-check"]); - assert.deepEqual(maintained(["mesh/check", "other/x"]), []); - assert.deepEqual(maintained([]), []); - assert.equal(writesGate(undefined), true); - assert.equal(writesGate(["mesh/repo-check"]), false); - assert.equal(writesGate(["mesh/check"]), false); - assert.equal(writesGate(["mesh/merge-gate", "mesh/repo-check"]), true); -}); - -test("a rule the forge gives with no contexts (null) requires nothing, and an unread rule is unknown", async () => { - const { requiredOf } = await import("../pulls.ts"); - // The forge's BranchProtection says status_check_contexts may be null (protection.ts); requiredOf takes it as it comes. - assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: null }), []); - assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: ["mesh/check", ""] }), ["mesh/check"]); - assert.deepEqual(requiredOf(null), []); - assert.equal(requiredOf(undefined), undefined); -}); diff --git a/modules/gitea/test/siblings.test.ts b/modules/gitea/test/siblings.test.ts deleted file mode 100644 index 0562b6351..000000000 --- a/modules/gitea/test/siblings.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -// **A delivery group's member is judged beside its siblings, and a sibling's move puts that verdict out of date** -// (novox/hq ADR 0382 §4-§6, issue 867): the holder keeps the siblings each verdict names; a sibling's new head, close -// unmerged or base move (other than its own merge of the head that was read) sets both statuses of every member whose -// verdict names it back to pending, and runs nothing; a member merges only with its group passed and every sibling head -// read approved. - -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { mkdtempSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; - -import { approvedHeadsOf, besideWords, groupRefusal, keepSiblings, namesSiblings, readSiblings, siblingOutOfDate, siblingsFile, - siblingsOf, siblingStatuses, weighSiblings, type SiblingRecord } from "../dist/siblings.js"; -import { weighTrunks } from "../dist/trunk.js"; - -const h = (c: string) => c.repeat(40); -const MEMBER_HEAD = h("a"), HOST_HEAD = h("b"), HOST_BASE = h("c"), HOST_NEW = h("d"), HOST_MOVED = h("e"), MERGE = h("f"); -const sibling = { repository: "novox/mesh-host", number: 114, head: HOST_HEAD, base: "main", base_commit: HOST_BASE }; -const verdict = { owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, verdict: "pass", summary: "x", id: "build-1", - trunk: h("1").slice(0, 12), siblings: [sibling], judge_from: "sibling novox/mesh-controller#346 merge 123456789abc", - gate: { verdict: "pass", summary: "every machine composes ".repeat(10) }, "repo-check": { verdict: "pass", summary: "ok" } }; - -test("the siblings a verdict names are kept per member, and read back from where the holder keeps its state", () => { - const file = siblingsFile(mkdtempSync(join(tmpdir(), "gitea-siblings-"))); - const record: SiblingRecord = { "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }; - keepSiblings(file, record); - assert.deepEqual(readSiblings(file), record, "kept where the holder keeps its state"); - assert.deepEqual(readSiblings(null), {}); -}); - -// --- a sibling's move ----------------------------------------------------------------------------------------- - -interface World { - host: { merged: boolean; state: string; head_sha: string; merge_commit_sha?: string }; - hostBase: string; - parents: string[]; - member: { head_sha: string; state: string; merged: boolean }; - checks: Record; - written: { sha: string; context: string; state: string; description: string }[]; - reads: string[]; -} -const world = (): World => ({ host: { merged: false, state: "open", head_sha: HOST_HEAD }, hostBase: HOST_BASE, parents: [], - member: { head_sha: MEMBER_HEAD, state: "open", merged: false }, - checks: { "mesh/merge-gate": { state: "success", description: "head aaaaaaaaaaaa merged into trunk 111111111111 beside mesh-host#114@bbbbbbbb — pass: x" }, - "mesh/repo-check": { state: "success", description: "pass: y" } }, - written: [], reads: [] }); -const forgeOf = (w: World) => ({ - async getPullRequest(owner: string, repo: string, n: number) { - w.reads.push(`${owner}/${repo}#${n}`); - return repo === "mesh-host" ? { number: n, title: "", html_url: "", ...w.host } : { number: n, title: "", html_url: "", merged: false, ...w.member }; - }, - async branchHead(_o: string, _r: string, _b: string) { return w.hostBase; }, - async commitParents() { return w.parents; }, -}); -const gatesOf = (w: World) => ({ - async outOfDate(_o: string, _r: string, sha: string, decide: (c: any) => any[] | Promise) { - const put = await decide(w.checks); - for (const s of put) { w.written.push({ sha, ...s }); w.checks[s.context] = { state: s.state, description: s.description }; } - return put; - }, -}); -const recordOf = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }); -const weigh = (w: World, record: SiblingRecord, repository = "novox/mesh-host", number?: number) => - weighSiblings(forgeOf(w) as any, gatesOf(w) as any, record, repository, number); - -test("a sibling's new head puts both statuses of the member back to pending, with the reason, and runs nothing", async () => { - const w = world(); - w.host.head_sha = HOST_NEW; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.deepEqual(w.written.map((s) => [s.sha, s.context, s.state]), - [[MEMBER_HEAD, "mesh/merge-gate", "pending"], [MEMBER_HEAD, "mesh/repo-check", "pending"]]); - assert.equal(w.written[0].description, - "out of date: judged beside mesh-host#114 at bbbbbbbbbbbb, it is now at dddddddddddd; judged again on a recheck or when it is merged"); - assert.ok(siblingOutOfDate(w.written[0].description)); - // Already pending (out of date, or a check on its way): not written again. - w.written.length = 0; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.deepEqual(w.written, []); -}); - -test("a sibling closed unmerged puts the member's verdict out of date", async () => { - const w = world(); - w.host.state = "closed"; - await weigh(w, recordOf(), "novox/mesh-host", 114); - assert.equal(w.written.length, 2); - assert.match(w.written[0].description, /^out of date: judged beside mesh-host#114 was closed unmerged/); -}); - -test("a move of the sibling's base puts it out of date, naming both commits", async () => { - const w = world(); - w.hostBase = HOST_MOVED; - await weigh(w, recordOf()); - assert.equal(w.written.length, 2); - assert.match(w.written[0].description, /mesh-host#114 merged onto cccccccccccc, its main is now eeeeeeeeeeee/); -}); - -test("the sibling's own merge of the head read onto the base read does not, in either order of the two merges", async () => { - // The sibling merges first (a merge commit of the base commit read and the head read). - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - w.hostBase = MERGE; - w.parents = [HOST_BASE, HOST_HEAD]; - const record = recordOf(); - assert.equal(await weigh(w, record), true, "the record changes: the sibling is marked merged"); - assert.deepEqual(w.written, []); - assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true); - // A move of that base afterwards is no sibling's move: the sibling is merged. - w.hostBase = HOST_MOVED; - await weigh(w, record); - assert.deepEqual(w.written, []); - - // The member merges first: its own repository moves, which no member's verdict names as a sibling. - const m = world(); - m.member.merged = true; - await weigh(m, recordOf(), "novox/mesh-controller"); - assert.deepEqual(m.written, []); - // And the sibling then merges: still not a move. - Object.assign(m.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - m.parents = [HOST_BASE, HOST_HEAD]; - await weigh(m, recordOf()); - assert.deepEqual(m.written, []); - - // A squash is one parent: the base commit read. - const q = world(); - Object.assign(q.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - q.parents = [HOST_BASE]; - await weigh(q, recordOf()); - assert.deepEqual(q.written, []); -}); - -test("a merge of another head, or onto another base, is a move", async () => { - const other = world(); - Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - other.parents = [HOST_BASE, HOST_NEW]; - await weigh(other, recordOf()); - assert.equal(other.written.length, 2); - const onto = world(); - Object.assign(onto.host, { merged: true, state: "closed", merge_commit_sha: MERGE }); - onto.parents = [HOST_MOVED, HOST_HEAD]; - await weigh(onto, recordOf()); - assert.equal(onto.written.length, 2); -}); - -test("only the members whose verdict names the sibling are touched, and a member that moved on is dropped", async () => { - // Another sibling's move, or another repository's: nothing read, nothing written. - const w = world(); - w.host.head_sha = HOST_NEW; - await weigh(w, recordOf(), "novox/mesh-lab"); - await weigh(w, recordOf(), "novox/mesh-host", 999); - assert.deepEqual(w.written, []); - // A verdict that is none (a gate not yet judged) is left alone. - const none = world(); - none.host.head_sha = HOST_NEW; - none.checks = {}; - await weigh(none, recordOf()); - assert.deepEqual(none.written, []); - // The member has a new head: its old verdict is no verdict; the record is dropped, nothing written to the old head. - const moved = world(); - moved.host.head_sha = HOST_NEW; - moved.member.head_sha = h("9"); - const record = recordOf(); - assert.equal(await weigh(moved, record), true); - assert.deepEqual(moved.written, []); - assert.deepEqual(record, {}); - // A repository without a repo-check gets no pending one a verdict would never set. - assert.deepEqual(siblingStatuses({ "mesh/merge-gate": { state: "success" } }, "x").map((s) => s.context), ["mesh/merge-gate"]); -}); - -test("a trunk that moved tells the siblings' weighing; one first seen does not", async () => { - const told: string[] = []; - const forge = { listOpenPulls: async () => [{ number: 1, title: "", state: "open", merged: false, head_sha: h("2"), base: "main", html_url: "" }], - branchHead: async () => h("3") }; - const gates = { outOfDate: async () => [] }; - const trunks: Record = {}; - await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); }); - assert.deepEqual(told, [], "first seen"); - trunks["novox/mesh-host:main"] = h("4"); - await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); }); - assert.deepEqual(told, ["main"]); -}); - -// --- the merge rule ------------------------------------------------------------------------------------------- - -test("the group rule names every missing thing: the group status at each head read, and each head the Approve does not cover", async () => { - const self = { owner: "novox", repo: "mesh-controller", number: 346, head: MEMBER_HEAD }; - const statuses: Record = {}; - const forge = { - headChecks: async (_o: string, r: string, sha: string) => (statuses[`${r}@${sha}`] ? { "mesh/delivery-group": { state: statuses[`${r}@${sha}`] } } : {}), - }; - const siblings = siblingsOf([sibling]); - const none = await groupRefusal(forge, self, siblings, undefined); - assert.match(none!, /mesh\/delivery-group is missing at mesh-controller#346@aaaaaaaaaaaa; mesh-controller#346@aaaaaaaaaaaa is covered by no Approve: the merge was handed no approved heads; mesh\/delivery-group is missing at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is covered by no Approve/); - statuses[`mesh-controller@${MEMBER_HEAD}`] = "success"; - statuses[`mesh-host@${HOST_HEAD}`] = "pending"; - const approved = approvedHeadsOf([`novox/mesh-controller@${MEMBER_HEAD}`])!; - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh\/delivery-group is pending at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/); - statuses[`mesh-host@${HOST_HEAD}`] = "success"; - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/); - approved.set("novox/mesh-host", "c".repeat(40)); - assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not the head the Approve covers \(cccccccccccc\)$/); - approved.set("novox/mesh-host", HOST_HEAD.toLowerCase()); - assert.equal(await groupRefusal(forge, self, siblings, approved), undefined); - // A read that fails is named, never read as a pass. - const broken = { headChecks: async () => { throw new Error("the forge is away"); } }; - assert.match((await groupRefusal(broken, self, siblings, approved))!, /could not be read \(the forge is away\)/); - assert.equal(besideWords(siblings), "beside mesh-host#114@bbbbbbbb"); -}); - -test("a merged or closed member's entry is dropped, so a sibling's later push never re-pends its merged head", async () => { - // mesh-host#114 judged beside mesh-controller#346; #114 then merged; a push to #346 follows. - const w = world(); - w.host.merged = true; // the member (mesh-host#114) is merged - w.member.head_sha = h("9"); // the sibling (mesh-controller#346) has a new head - const record: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: siblingsOf([ - { repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: h("2") }]) } }; - assert.equal(await weigh(w, record, "novox/mesh-controller", 346), true); - assert.deepEqual(w.written, [], "the merged head is not put back to pending"); - assert.deepEqual(record, {}, "and its entry is gone"); - // On its own close or merge the member's entry goes too, whatever the siblings do. - const own = world(); - own.host.state = "closed"; - const kept = recordOf(); - const mine: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: kept["novox/mesh-controller#346"].siblings } }; - assert.equal(await weigh(own, mine, "novox/mesh-host", 114), true); - assert.deepEqual(mine, {}); - assert.deepEqual(own.written, []); -}); - -// --- the composed verdict names the siblings of each member (issue 1049) -------------------------------------- - -// Issue 1049: the 2026-10-17 23:48 group (mesh-controller #375 beside mesh-catalog #353). #375's own verdict named #353 -// at its old head; #353 then got a new head, and the group's composed verdict passed for both new heads. The record still -// held the old head, so #353's own merge of the NEW head read as "merged otherwise than its head" and put #375's gate back -// to pending, and the group merged in two passes. -const composedMembers = () => [ - { owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, trunk: "111111111111", base: "main" }, - { owner: "novox", repo: "mesh-host", number: 114, commit: HOST_NEW, trunk: HOST_BASE.slice(0, 12), base: "main" }, -]; -/** The record a group's composed verdict once left: for each member, the other members at the heads and base commits it composed. */ -const composedRecord = (members: ReturnType): SiblingRecord => Object.fromEntries(members.map((m) => [ - `${m.owner}/${m.repo}#${m.number}`.toLowerCase(), { head: m.commit, siblings: members.filter((o) => o !== m).map((o) => ({ - repository: `${o.owner}/${o.repo}`, number: o.number, head: o.commit, base: o.base, base_commit: o.trunk })) }])); -const staleRecord = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } }); - -test("without the composed verdict's siblings, a sibling's own merge of its new head is a move (the pin of issue 1049)", async () => { - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - w.parents = [HOST_BASE, HOST_NEW]; - await weigh(w, staleRecord()); - assert.equal(w.written.length, 2, "the record names the old head: the merge reads as another head's"); -}); - -test("a composed verdict names the siblings of each member at the heads and base commits it composed, so a sibling's own merge of its new head is no move (issue 1049)", async () => { - const record = composedRecord(composedMembers()); - assert.deepEqual(record["novox/mesh-controller#346"], { head: MEMBER_HEAD, - siblings: [{ repository: "novox/mesh-host", number: 114, head: HOST_NEW, base: "main", base_commit: HOST_BASE.slice(0, 12) }] }); - assert.deepEqual(record["novox/mesh-host#114"], { head: HOST_NEW, - siblings: [{ repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: "111111111111" }] }); - const w = world(); - Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - w.parents = [HOST_BASE, HOST_NEW]; - await weigh(w, record); - assert.deepEqual(w.written, [], "its own merge of the head the composed check judged leaves the member's gate alone"); - assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true); - // A merge of any other head, or onto any other base, is still a move. - const other = world(); - const again = composedRecord(composedMembers()); - Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW }); - other.parents = [HOST_MOVED, HOST_NEW]; - await weigh(other, again); - assert.equal(other.written.length, 2); -}); diff --git a/modules/gitea/test/taken.test.ts b/modules/gitea/test/taken.test.ts new file mode 100644 index 000000000..c053ae422 --- /dev/null +++ b/modules/gitea/test/taken.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +// 47 H2 §775, H-A-381, H-A-400: the forge module takes an act of the seat git once by its ask id. Given the same ask id +// twice it acts once: a repeat while the act runs joins it, a repeat after it ended answers what the forge holds of the +// act; an act that performed nothing (away, a refusal before any merge) drops its key, so the repeat acts. +test("an act of the seat git given the same ask id twice acts once", async () => { + const { seatTools } = await import("../dist/seat.js"); + const { Once, durationMs, askTakenBoundMs } = await import("../dist/taken.js"); + const { runAs } = await import("@novox/mesh-sdk/callers"); + const SHA = "a".repeat(40), MERGE = "c".repeat(40); + const keys = new Set(); + const taken = { take: async (ask: string) => (keys.has(ask) ? false : (keys.add(ask), true)), drop: async (ask: string) => { keys.delete(ask); } }; + let merges = 0, comments: { id: number; body: string }[] = [], added = 0, away = false; + const pr = () => ({ number: 9, state: merges ? "closed" : "open", merged: merges > 0, head: "feat/x", head_sha: SHA, base: "main", ...(merges ? { merge_commit_sha: MERGE } : {}) }); + let release: () => void = () => {}, entered: () => void = () => {}; + const merging = new Promise((r) => { entered = r; }); + const forge: Record = { + forgeVersion: async () => (away ? { ok: false, words: "no answer", store: true } : { ok: true, version: "1.27.3" }), + getPullRequest: async () => { if (away) throw new Error("Gitea API /repos/novox/app/pulls/9: 503 Service Unavailable"); return pr(); }, + mergePullRequest: async () => { const held = new Promise((r) => { release = r; }); entered(); await held; merges++; }, + commitParents: async () => [SHA, SHA], + listComments: async () => comments, + addComment: async (_o: string, _r: string, _n: number, body: string) => { added++; comments.push({ id: added, body }); }, + }; + const seat = seatTools(forge as any, { run: (async () => ({ stdout: "", code: 1 })) as any, container: "gitea", registered: () => true, + judge: async () => null, watched: () => new Map([["novox/app", new Set(["main"])]]), once: new Once(taken) }); + const call = (verb: string, ask: string, args: Record) => + runAs({ "mesh/caller": "ace.x", "mesh/ask": ask }, args, () => seat.find((x: any) => x.name === `git.${verb}`)!.run(args)) as Promise; + const merge = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 9, head: SHA }] }; + + // Away first: nothing performed, the key dropped, so the kept call's repeat under the same id acts (H-A-400 (1)). + away = true; + assert.equal((await call("merge-pull", "ask1", merge))["error-kind"], "away"); + assert.equal(keys.has("ask1"), false, "an act that performed nothing keeps no taken key"); + away = false; + + // The repeat while the first runs joins it: one merge, both answered the same. + const first = call("merge-pull", "ask1", merge); + await merging; + const joined = call("merge-pull", "ask1", merge); + release(); + const [a, b] = await Promise.all([first, joined]); + assert.equal(merges, 1, "a repeat while the act runs joins it"); + assert.deepEqual(b, a); + assert.equal(a.members[0].state, "merged"); + + // After it ended, the repeat answers the pull request as the forge holds it, merged with its merge commit, and merges nothing. + const again = await call("merge-pull", "ask1", merge); + assert.deepEqual([merges, again.members], [1, [{ repository: "novox/app", number: 9, state: "merged", commit: MERGE }]]); + + // A comment given its ask again is not written twice; a repeat whose comment the forge does not hold is refused, naming it. + const comment = { id: "c1", repository: "novox/app", number: 9, text: "hi" }; + assert.equal((await call("comment", "ask2", comment)).performed, true); + assert.deepEqual([(await call("comment", "ask2", comment)).held, added], [true, 1]); + comments = []; + const gone = await call("comment", "ask2", comment); + assert.deepEqual([gone["error-kind"], /ask2 was taken/.test(gone.error), added], ["refused", true, 1]); + + // ask-taken-bound is read from the word the node-engine composes (H-A-400 (2)), 10 minutes by default. + assert.deepEqual([askTakenBoundMs({}), askTakenBoundMs({ MESH_CONFIG_ASK_TAKEN_BOUND: "90s" }), askTakenBoundMs({ MESH_CONFIG_ASK_TAKEN_BOUND: "soon" }), durationMs("1h30m")], + [600_000, 90_000, 600_000, 5_400_000]); +}); diff --git a/modules/gitea/test/token.test.ts b/modules/gitea/test/token.test.ts index a33477b82..0bd3e0008 100644 --- a/modules/gitea/test/token.test.ts +++ b/modules/gitea/test/token.test.ts @@ -10,15 +10,19 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { mkdtemp, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { collectTools } from "@novox/mesh-sdk/tools"; -import { AdminRefused, MintedToken, TOKEN_SCOPES } from "../dist/token.js"; +import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js"; +import { tokenLeaseTool } from "../dist/tools/tokenlease.js"; +import { fakeBus } from "./fakebus.ts"; import { GiteaClient } from "../dist/client.js"; import { getGiteaTools } from "../dist/tools/index.js"; +/** What the vault and the forge were asked, in order: each own-put and each token deleted (design 47 H2 §808). */ +const ORDER: string[] = []; const ADMIN = "mesh-admin"; const PASSWORD = "the-vault-minted-this"; @@ -126,6 +130,7 @@ function fakeForge(): Promise { if (matches.length > 1) return json(res, 422, { message: `multiple matches for token name '${key}'` }); const t = matches[0]; forge.deletedBy.push(byId ? "id" : "name"); + ORDER.push(`delete ${t.name}`); const twin = forge.twins.findIndex((w) => w.id === t.id); if (twin >= 0) forge.twins.splice(twin, 1); else forge.tokens.delete(t.name); @@ -253,58 +258,62 @@ function fakeForge(): Promise { // ---- What the runtime's environment gives the module. ---- -async function delivered(forge: Forge): Promise<{ env: NodeJS.ProcessEnv; file: string; logs: string[] }> { +async function delivered(forge: Forge, now: () => Date = () => new Date()) { const dir = await mkdtemp(join(tmpdir(), "gitea-")); const passwordFile = join(dir, "admin.secret"); await writeFile(passwordFile, PASSWORD + "\n", { mode: 0o600 }); - const state = join(dir, "state"); + ORDER.length = 0; return { env: { MESH_GITEA_URL: forge.url, MESH_GITEA_ADMIN_USER: ADMIN, MESH_GITEA_ADMIN_PASSWORD_FILE: passwordFile, - MESH_GITEA_STATE_DIR: state, - }, - file: join(state, "token"), - logs: [], + MESH_GITEA_STATE_DIR: join(dir, "state"), + } as NodeJS.ProcessEnv, + bus: fakeBus(now, ORDER), + logs: [] as string[], }; } -/** A client as a fresh process would build it: a new source over the kept file, its log captured. */ -function minted(env: NodeJS.ProcessEnv, logs: string[]): GiteaClient { - const source = new MintedToken({ - url: env.MESH_GITEA_URL!, - admin: env.MESH_GITEA_ADMIN_USER!, - passwordFile: env.MESH_GITEA_ADMIN_PASSWORD_FILE!, - file: join(env.MESH_GITEA_STATE_DIR!, "token"), - log: (l) => logs.push(l), - }); - return new GiteaClient(env.MESH_GITEA_URL!, source); +/** A client as a fresh process would build it: a new source over the vault and the lease on the bus, its log captured. */ +function minted(env: NodeJS.ProcessEnv, logs: string[], extra: Partial = {}): GiteaClient { + return new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, extra)); } +function source(env: NodeJS.ProcessEnv, logs: string[], extra: Partial = {}): MintedToken { + return new MintedToken({ + url: env.MESH_GITEA_URL!, admin: env.MESH_GITEA_ADMIN_USER!, passwordFile: env.MESH_GITEA_ADMIN_PASSWORD_FILE!, + account: "mesh-tools", oldName: TOKEN_NAME, vault: vaultOverBus(), lease: leaseOverState(), log: (l) => logs.push(l), ...extra, + }); +} + +const VAULT = "module/gitea/mesh-tools"; +/** The token the vault keeps for the tools' account, out of the value that holds it with its scopes (H-A-439). */ +const vaulted = (bus: ReturnType) => openValue(bus.vault.get(VAULT)?.value ?? "").token; const forge = await fakeForge(); after(() => forge.close()); -test("first start: mints with the admin account, keeps the token at 0600, asks for the tools' scopes only", async () => { - const { env, file, logs } = await delivered(forge); +test("first start: mints mesh-tools-1 with the admin account, writes it through own-put, asks for the tools' scopes only", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); const repos = await minted(env, logs).listRepos(); assert.equal(repos[0]?.full_name, "novox/hq"); - assert.equal(forge.mints, 1); // Never write:admin (novox/hq ADR 0266): the forge's administration is the operator's, not a tool's. assert.deepEqual(forge.lastScopes, ["write:repository", "write:issue", "read:user", "read:package"]); assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); - const token = forge.tokens.get("mesh-tools")!; - assert.equal(await readFile(file, "utf8"), token + "\n"); - assert.equal(await readFile(file + ".scopes", "utf8"), "read:package,read:user,write:issue,write:repository\n"); - assert.equal((await stat(file)).mode & 0o777, 0o600); - // Said that it minted, and where it keeps it — never what it is. - assert.ok(logs.some((l) => l.startsWith("minted a token")), logs.join("\n")); + // Design 47 H2 §808, H-A-422 (2), H-A-426: named per mint, kept as the module's own secret, never a file. + const token = forge.tokens.get("mesh-tools-1")!; + assert.ok(token); + assert.deepEqual([vaulted(bus), bus.vault.get(VAULT)?.generation], [token, 1]); + assert.deepEqual(openValue(bus.vault.get(VAULT)!.value).scopes, [...TOKEN_SCOPES], "kept with the scopes it was minted with (H-A-439)"); + await assert.rejects(stat(join(env.MESH_GITEA_STATE_DIR!, "token")), /ENOENT/); + assert.ok(logs.some((l) => l.startsWith("minted mesh-tools-1")), logs.join("\n")); assert.ok(logs.every((l) => !l.includes(token) && !l.includes(PASSWORD)), logs.join("\n")); }); -test("second start: reuses the kept token, mints nothing", async () => { +test("second start: reuses the vault's token, mints nothing", async () => { const { env, logs } = await delivered(forge); await minted(env, logs).listRepos(); const before = forge.mints; @@ -313,54 +322,83 @@ test("second start: reuses the kept token, mints nothing", async () => { await minted(env, again).listRepos(); assert.equal(forge.mints, before); - assert.ok(again.some((l) => l.startsWith("reusing the token kept at")), again.join("\n")); - assert.ok(again.every((l) => !l.includes(forge.tokens.get("mesh-tools")!)), again.join("\n")); + assert.ok(again.some((l) => l.startsWith(`reusing the token the vault keeps as ${VAULT}`)), again.join("\n")); }); -test("the forge rejects the kept token (its data was restored): minted afresh, once, and the call goes through", async () => { - const { env, file, logs } = await delivered(forge); +test("the forge rejects the vault's token: mesh-tools-2 is minted once, written through own-put, and only then is mesh-tools-1 deleted by its id", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); const client = minted(env, logs); await client.listRepos(); const before = forge.mints; + ORDER.length = 0; + forge.deletedBy.length = 0; - forge.tokens.clear(); // the forge no longer knows any token — a restore from the predecessor + forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); // the forge no longer takes the vault's token const repos = await client.listRepos(); assert.equal(repos.length, 1); assert.equal(forge.mints, before + 1); - assert.equal(await readFile(file, "utf8"), forge.tokens.get("mesh-tools") + "\n"); - assert.ok(logs.some((l) => l.startsWith("the forge rejected the kept token")), logs.join("\n")); + assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2")); + // H-A-422 (2): the own-put first, the replaced token's delete after, by id; the forge holds one tools' token after. + assert.deepEqual(ORDER, [`own-put ${VAULT} 2`, "delete mesh-tools-1"]); + assert.deepEqual(forge.deletedBy, ["id"]); + assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]); + assert.ok(logs.some((l) => l.startsWith("the forge rejected the vault's token")), logs.join("\n")); }); -test("a token kept with write:admin by an earlier build is minted again without it at the next start, and the forge drops the old one", async () => { - const { env, file, logs } = await delivered(forge); - await minted(env, logs).listRepos(); - const old = forge.tokens.get("mesh-tools")!; - forge.scopesOf.set(old, ["write:repository", "write:issue", "read:user", "write:admin"]); - await rm(file + ".scopes"); // an earlier build kept no scopes beside it +test("an own-put that fails leaves the old token standing, and the next mint replaces the unused one it left", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); + const client = minted(env, logs); + await client.listRepos(); + const old = forge.tokens.get("mesh-tools-1")!; + forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); + ORDER.length = 0; + let failPut = true; + const failing = minted(env, logs, { vault: { get: vaultOverBus().get, put: async (a, t, scopes) => { + if (failPut) { failPut = false; throw new Error("the vault is away"); } + return vaultOverBus().put(a, t, scopes); + } } }); + + await assert.rejects(failing.listRepos(), /the vault is away/); + assert.deepEqual(ORDER, [], "nothing deleted while the vault holds the old token"); + assert.equal(bus.vault.get(VAULT)?.generation, 1); + assert.ok(forge.tokens.has("mesh-tools-2"), "the unused token of the failed mint stands"); + + assert.equal((await failing.listRepos()).length, 1); + assert.deepEqual(ORDER, ["delete mesh-tools-2", `own-put ${VAULT} 2`, "delete mesh-tools-1"]); + assert.notEqual(vaulted(bus), old); +}); + +test("a token older than token-ttl is minted again, and the one it replaces deleted", async () => { + let clock = Date.parse("2026-11-22T00:00:00Z"); + const now = () => new Date(clock); + const { env, bus, logs } = await delivered(forge, now); + forge.tokens.clear(); + const client = minted(env, logs, { now, ttlMs: 24 * 3600_000 }); + await client.listRepos(); const before = forge.mints; - const again: string[] = []; - await minted(env, again).listRepos(); + clock += 23 * 3600_000; + await client.listRepos(); + assert.equal(forge.mints, before, "a token within token-ttl is used"); + clock += 2 * 3600_000; + await client.listRepos(); assert.equal(forge.mints, before + 1); - assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); - assert.ok(!forge.lastScopes!.includes("write:admin")); - assert.notEqual(forge.tokens.get("mesh-tools"), old); - assert.ok(![...forge.tokens.values()].includes(old), "the old token still stands on the forge"); - assert.ok(again.some((l) => l.includes("minted with other scopes")), again.join("\n")); - // An admin route through the escape hatch is refused before it is sent. - const tool = getGiteaTools(minted(env, again)).find((t) => t.name === "gitea_api")!; - await assert.rejects(tool.run({ path: "/admin/users/mesh_novox_builder", method: "PATCH", body: { admin: true } }), - /not a write gitea_api makes/); + assert.equal(bus.vault.get(VAULT)?.generation, 2); + assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]); + assert.ok(logs.some((l) => l.includes("older than token-ttl")), logs.join("\n")); }); -test("a kept token lacking a scope the tools need: the forge refuses the call for the scope, the token is re-minted with the whole list, and the call goes through", async () => { - const { env, file, logs } = await delivered(forge); +test("a token lacking a scope the tools need: the forge refuses the call for the scope, the token is re-minted with the whole list, and the call goes through", async (t) => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); const client = minted(env, logs); await client.listRepos(); const before = forge.mints; - const old = forge.tokens.get("mesh-tools")!; + const old = forge.tokens.get("mesh-tools-1")!; forge.scopesOf.set(old, ["write:repository", "write:issue"]); // minted before read:user was added const repos = await client.api("/user/repos"); @@ -368,37 +406,37 @@ test("a kept token lacking a scope the tools need: the forge refuses the call fo assert.equal(repos.length, 1); assert.equal(forge.mints, before + 1); assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); - assert.notEqual(forge.tokens.get("mesh-tools"), old); - assert.equal(await readFile(file, "utf8"), forge.tokens.get("mesh-tools") + "\n"); - assert.ok(logs.some((l) => l.startsWith("the forge rejected the kept token")), logs.join("\n")); + assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2")); + + // Design 47 H2 §808, H-A-439: the vault keeps the scopes beside the token, so one carrying a scope beyond the tools' + // is minted again unasked, as when they were kept in a file beside it. + await t.test("a token kept with write:admin is minted again without it at the next start, and the forge drops the old one", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); + await minted(env, logs).listRepos(); + const old = forge.tokens.get("mesh-tools-1")!; + // An earlier mint asked write:admin too, and the vault keeps what it asked. + bus.vault.get(VAULT)!.value = vaultValue(old, [...TOKEN_SCOPES, "write:admin"]); + forge.scopesOf.set(old, [...TOKEN_SCOPES, "write:admin"]); + const before = forge.mints; + + const again: string[] = []; + await minted(env, again).listRepos(); + + assert.equal(forge.mints, before + 1); + assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); + assert.ok(![...forge.tokens.values()].includes(old), "the old token still stands on the forge"); + assert.deepEqual(openValue(bus.vault.get(VAULT)!.value), { token: forge.tokens.get("mesh-tools-2"), scopes: [...TOKEN_SCOPES] }); + assert.ok(again.some((l) => l.includes("minted with other scopes")), again.join("\n")); + // An admin route through the escape hatch is refused before it is sent. + const tool = getGiteaTools(minted(env, again)).find((x) => x.name === "gitea_api")!; + await assert.rejects(tool.run({ path: "/admin/users/mesh_novox_builder", method: "PATCH", body: { admin: true } }, undefined as never), + /not a write gitea_api makes/); + }); }); -test("the kept file is gone but the forge still holds a token by that name: replaced, not refused", async () => { - const { env, file, logs } = await delivered(forge); - await minted(env, logs).listRepos(); - const before = forge.mints; - await rm(file); - - const repos = await minted(env, logs).listRepos(); - - assert.equal(repos.length, 1); - assert.equal(forge.mints, before + 1); - assert.equal([...forge.tokens.keys()].filter((n) => n === "mesh-tools").length, 1); - assert.ok(logs.some((l) => l.includes('already holds a token named "mesh-tools"')), logs.join("\n")); -}); - -test("concurrent first calls share one mint", async () => { +test("the first mint deletes by id every token under the old fixed name, two raced ones too, and keeps the account's others", async () => { const { env, logs } = await delivered(forge); - const client = minted(env, logs); - const before = forge.mints; - - await Promise.all([client.listRepos(), client.listRepos(), client.listRepos()]); - - assert.equal(forge.mints, before + 1); -}); - -test("two tokens hold the name (two mints raced): both are deleted by their id, and one fresh token is minted", async () => { - const { env, file, logs } = await delivered(forge); forge.tokens.clear(); forge.twins.length = 0; for (const other of ["laptop", "backup", "ci"]) forge.plant(other); // the account's other tokens: kept @@ -411,44 +449,68 @@ test("two tokens hold the name (two mints raced): both are deleted by their id, assert.equal(repos.length, 1); assert.equal(forge.mints, before + 1); + // H-A-430 (1): the tokens the module kept before under the old fixed name are the ones the first mint replaces. assert.deepEqual(forge.deletedBy, ["id", "id"]); + assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, "delete mesh-tools", "delete mesh-tools"]); assert.equal(forge.twins.length, 0); - assert.deepEqual([...forge.tokens.keys()].sort(), ["backup", "ci", "laptop", "mesh-tools"]); - assert.equal(await readFile(file, "utf8"), forge.tokens.get("mesh-tools") + "\n"); - assert.ok(logs.some((l) => l.includes('holds 2 tokens named "mesh-tools"')), logs.join("\n")); + assert.deepEqual([...forge.tokens.keys()].sort(), ["backup", "ci", "laptop", "mesh-tools-1"]); }); -test("two processes on one kept file, both without a token, mint once: the second waits for the first and reuses it", async () => { +test("concurrent first calls share one mint", async () => { const { env, logs } = await delivered(forge); forge.tokens.clear(); - forge.twins.length = 0; + const client = minted(env, logs); const before = forge.mints; - // Two sources over one state directory, as the tools bundle and the watcher are two processes. - const first = minted(env, logs); - const second = minted(env, logs); - await Promise.all([first.listRepos(), second.listRepos()]); + await Promise.all([client.listRepos(), client.listRepos(), client.listRepos()]); assert.equal(forge.mints, before + 1); - assert.equal(forge.twins.length, 0); - assert.ok(logs.some((l) => l.includes("another process minted it")), logs.join("\n")); }); -test("a lock left by a process that died mid-mint is taken over, not waited on for ever", async () => { - const { env, file, logs } = await delivered(forge); +test("two processes, one holding the old token, both refused, mint one token in all: the second waits for the lease and uses the vault's newer token", async () => { + const { env, bus, logs } = await delivered(forge); forge.tokens.clear(); forge.twins.length = 0; - await mkdir(join(env.MESH_GITEA_STATE_DIR!), { recursive: true }); - await writeFile(`${file}.lock`, `2147483646 ${Date.now()} gone\n`); // a pid no process holds + const first = minted(env, logs); + await first.listRepos(); + const second = minted(env, logs); + await second.listRepos(); // both hold mesh-tools-1 const before = forge.mints; - assert.equal((await minted(env, logs).listRepos()).length, 1); + forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); + await Promise.all([first.listRepos(), second.listRepos()]); + + // Design 47 H2 §808: one mint in all, and the forge holds one token for the account after. assert.equal(forge.mints, before + 1); - await assert.rejects(stat(`${file}.lock`), /ENOENT/); + assert.deepEqual([...forge.tokens.keys()].filter((n) => n.startsWith("mesh-tools")), ["mesh-tools-2"]); + assert.equal(bus.vault.get(VAULT)?.generation, 2); + assert.ok(logs.some((l) => l.includes("another process holds the mint lease")), logs.join("\n")); + assert.equal(bus.kv.size, 0, "the lease is deleted after the mint"); +}); + +test("a minter killed while holding the lease is replaced after mint-lease: the waiter creates the lease itself and mints", async () => { + let clock = Date.parse("2026-11-22T00:00:00Z"); + const now = () => new Date(clock); + const { env, bus, logs } = await delivered(forge, now); + forge.tokens.clear(); + // A process that took the lease and died: its key lives mint-lease (60 s) and nobody deletes it. + await bus.ask("mesh/state.create", { state: "token-lease", key: "mint", value: { holder: "ace/4242", since: now().toISOString() }, ttl_seconds: 60 }); + const waited: number[] = []; + const lease = leaseOverState(); + // Waiting for the key to change: nothing changes, so the wait lasts its bound, the clock moving on by it. + const before = forge.mints; + + const repos = await minted(env, logs, { lease: { ...lease, changed: async (ms) => { waited.push(ms); clock += ms; } } }).listRepos(); + + assert.equal(repos.length, 1); + assert.deepEqual(waited, [60_000], "the waiter waited mint-lease once"); + assert.equal(forge.mints, before + 1); + assert.ok(logs.some((l) => l.includes("another process holds the mint lease (ace/4242 since")), logs.join("\n")); }); test("the admin account is refused: said plainly, nothing kept, and the next call fails the same way rather than crashing", async () => { - const { env, file, logs } = await delivered(forge); + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); forge.admins.delete(ADMIN); // the forge's data came from a predecessor; mesh-admin was never created there try { const client = minted(env, logs); @@ -456,15 +518,15 @@ test("the admin account is refused: said plainly, nothing kept, and the next cal await assert.rejects(client.listRepos(), (err: unknown) => { assert.ok(err instanceof AdminRefused, String(err)); - assert.match(err.message, /refused the admin account "mesh-admin" \(401\)/); - assert.match(err.message, /admin-bootstrap step creates it/); - assert.match(err.message, /came from a predecessor/); + // 47 H2 §776: the forge's refusal, never worded as an account to create. + assert.match(err.message, /the forge refuses the mesh's admin account "mesh-admin" \(401\)/); + assert.doesNotMatch(err.message, /[Cc]reate/); assert.ok(!err.message.includes(PASSWORD)); return true; }); await assert.rejects(client.listRepos(), AdminRefused); assert.equal(forge.mints, before); - await assert.rejects(stat(file), /ENOENT/); + assert.equal(bus.vault.size, 0); // The account appears (the operator created it): the very next call mints and works. forge.admins.set(ADMIN, PASSWORD); @@ -475,25 +537,47 @@ test("the admin account is refused: said plainly, nothing kept, and the next cal } }); -test("one process shares one source per kept file — the watcher and the tools never renew against each other", async () => { +test("one process shares one source per account — the watcher and the tools never renew against each other", async () => { const { env } = await delivered(forge); assert.equal(MintedToken.fromEnv(env.MESH_GITEA_URL!, env), MintedToken.fromEnv(env.MESH_GITEA_URL!, env)); }); -test("a second process finds the token the first renewed, and reuses it instead of minting over it", async () => { +test("a second process finds the token the first renewed in the vault, and reuses it instead of minting over it", async () => { const { env, logs } = await delivered(forge); + forge.tokens.clear(); const first = minted(env, logs); const second = minted(env, logs); await first.listRepos(); - await second.listRepos(); // both hold the same kept token + await second.listRepos(); // both hold the same token const before = forge.mints; - forge.tokens.clear(); + forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); await first.listRepos(); // renews: one mint - await second.listRepos(); // rejected too — but the kept file already carries the renewed one + await second.listRepos(); // rejected too — but the vault already holds the renewed one assert.equal(forge.mints, before + 1); - assert.ok(logs.some((l) => l.includes("is newer — reusing it")), logs.join("\n")); + assert.ok(logs.some((l) => l.includes("is newer (generation 2) — reusing it")), logs.join("\n")); +}); + +test("forge_token_lease says the lease's holder and since when, and each token's age from the vault, never the token", async () => { + let clock = Date.parse("2026-11-22T00:00:00Z"); + const now = () => new Date(clock); + const { env, bus, logs } = await delivered(forge, now); + forge.tokens.clear(); + await minted(env, logs, { now }).listRepos(); + await bus.ask("mesh/state.create", { state: "token-lease", key: "mint", value: { holder: "ace/4242", since: "2026-11-22T00:00:30Z" }, ttl_seconds: 60 }); + clock += 90_000; + const tool = tokenLeaseTool(vaultOverBus(), leaseOverState(), ["mesh-tools", "mesh-packages"], now); + + const said = await tool.run({}, undefined as never) as any; + + assert.equal(tool.name, "forge_token_lease"); + assert.deepEqual(said.tokens.map((t: any) => [t.account, t.held, t.generation, t["age-seconds"]]), + [["mesh-tools", true, 1, 90], ["mesh-packages", false, undefined, undefined]]); + assert.ok(!JSON.stringify(said).includes(vaulted(bus)), "the token is never said"); + // The lease lives mint-lease: past it, nobody holds it. + clock += 30_000; + assert.deepEqual((await tool.run({}, undefined as never) as any).lease, { held: false }); }); test("a configured token wins, and is reported rather than minted over when the forge rejects it", async () => { @@ -510,8 +594,8 @@ test("a configured token wins, and is reported rather than minted over when the test("nothing to mint with and no token: the client says what is missing", async () => { assert.throws( - () => GiteaClient.fromEnv({ MESH_GITEA_URL: forge.url, MESH_GITEA_ADMIN_USER: ADMIN }), - /set GITEA_TOKEN, or MESH_GITEA_ADMIN_PASSWORD_FILE, MESH_GITEA_STATE_DIR/, + () => GiteaClient.fromEnv({ MESH_GITEA_URL: forge.url, MESH_GITEA_ADMIN_USER: ADMIN, MESH_GITEA_TOOLS_USER: "mesh-tools-nothing" }), + /set GITEA_TOKEN, or MESH_GITEA_ADMIN_PASSWORD_FILE/, ); }); diff --git a/modules/gitea/test/tools-account.test.ts b/modules/gitea/test/tools-account.test.ts index f77b199ae..69f4efc43 100644 --- a/modules/gitea/test/tools-account.test.ts +++ b/modules/gitea/test/tools-account.test.ts @@ -10,11 +10,12 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; -import { mkdtemp, readFile, writeFile, mkdir } from "node:fs/promises"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { MintedToken, TOKEN_SCOPES } from "../dist/token.js"; +import { MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus } from "../dist/token.js"; +import { fakeBus } from "./fakebus.ts"; import { GiteaClient } from "../dist/client.js"; import { TOOLS_ACCOUNT, TOOLS_TEAM_UNITS, BUILDER_ACCOUNT, AGENT_ACCOUNT, meshAccounts } from "../dist/tools-account.js"; import { PACKAGES_ACCOUNT, PACKAGES_TEAM_UNITS, PACKAGES_TOKEN_REFUSED, keepPackagesToken, packagesToken, renewOnRefusal } from "../dist/packages-account.js"; @@ -266,7 +267,12 @@ function fakeForge() { const forge = await fakeForge(); after(() => forge.close()); +/** The bus of the environment made last: the vault's secrets and the lease (design 47 H2 §808). */ +let bus = fakeBus(); +const vaulted = (account: string) => { const v = bus.vault.get(`module/gitea/${account}`)?.value; return v === undefined ? undefined : openValue(v).token; }; + async function environment(keepMainRules = false): Promise { + bus = fakeBus(); const dir = await mkdtemp(join(tmpdir(), "gitea-tools-account-")); const passwordFile = join(dir, "admin.secret"); await writeFile(passwordFile, PASSWORD + "\n", { mode: 0o600 }); @@ -281,7 +287,7 @@ async function environment(keepMainRules = false): Promise t.name === "mesh-tools"); - assert.deepEqual(held.map((t) => t.user), [TOOLS_ACCOUNT], "the one token is the tools' account's, none is the administrator's"); - assert.equal(await readFile(join(env.MESH_GITEA_STATE_DIR, "token"), "utf8"), held[0].sha1 + "\n"); + const held = forge.tokens.filter((t) => t.name === "mesh-tools-1" || t.name === "mesh-tools"); + assert.deepEqual(held.map((t) => [t.user, t.name]), [[TOOLS_ACCOUNT, "mesh-tools-1"]], "the one token is the tools' account's, none is the administrator's"); + assert.equal(vaulted(TOOLS_ACCOUNT), held[0].sha1, "kept in the vault as the module's own (design 47 H2 §808)"); const team = forge.teams.find((t) => t.name === "mesh-tools"); assert.ok(team, "the team is made in the mesh's organisation"); @@ -334,17 +340,13 @@ test("the administrator's token from before goes: a kept admin token is minted a // What the module kept before ADR 0365: a token of the administrator's own, by the same name, its scopes beside it. const old = { id: 900, name: "mesh-tools", sha1: "sha-admin-old", user: ADMIN, scopes: ["write:repository", "write:issue", "read:user"] }; forge.tokens.push(old); - await mkdir(env.MESH_GITEA_STATE_DIR, { recursive: true }); - await writeFile(join(env.MESH_GITEA_STATE_DIR, "token"), old.sha1 + "\n", { mode: 0o600 }); - await writeFile(join(env.MESH_GITEA_STATE_DIR, "token.scopes"), "read:user,write:issue,write:repository\n", { mode: 0o600 }); await fresh(env).listRepos(); assert.ok(!forge.tokens.some((t) => t.user === ADMIN), "the administrator holds no tools' token any more"); - const kept = (await readFile(join(env.MESH_GITEA_STATE_DIR, "token"), "utf8")).trim(); + const kept = vaulted(TOOLS_ACCOUNT)!; assert.notEqual(kept, old.sha1); assert.equal(forge.tokens.find((t) => t.sha1 === kept)?.user, TOOLS_ACCOUNT); - assert.match(await readFile(join(env.MESH_GITEA_STATE_DIR, "token.scopes"), "utf8"), / for mesh-tools\n$/); }); test("a tools' account someone made an administrator is made a plain account again at the next mint", async () => { @@ -363,17 +365,31 @@ test("the manifest hands the tools their account, and the Go forge bundle holds const manifest = JSON.parse(await readFile(new URL("../module.json", import.meta.url), "utf8")); const code = manifest.build.artifacts.find((a: any) => a.name === "code"); assert.equal(code.env.MESH_GITEA_TOOLS_USER, TOOLS_ACCOUNT); - // The Go forge bundle reads the token the tools' account holds, never the administrator's password. + // The Go forge bundle reads the token the tools' account holds, never the administrator's password; through the + // vault seat's get, never a file (design 47 H2 §808, H-A-422 (1)). const forgeBundle = manifest.build.artifacts.find((a: any) => a.name === "forge"); - assert.ok(forgeBundle.env.MESH_GITEA_TOKEN_FILE); + assert.equal(forgeBundle.env.MESH_GITEA_TOOLS_USER, TOOLS_ACCOUNT); assert.equal(forgeBundle.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined); // The package registry's bundle reads with the tools' token and writes with the packages account's (design 51). const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry"); - assert.equal(packages.env.MESH_GITEA_TOKEN_FILE, forgeBundle.env.MESH_GITEA_TOKEN_FILE); assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT); - assert.match(packages.env.MESH_GITEA_PACKAGES_TOKEN_FILE, /^\$\{dir:runtime-state\}\/packages-token$/); assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined); - assert.equal(code.env.MESH_GITEA_STATE_DIR, "${dir:runtime-state}", "the watcher mints the packages token where the bundle reads it"); + // H-A-564: until gitea runs as its own account, the Go bundles are handed the token files the TypeScript bundle keeps + // under its state directory, read when the vault refuses the caller's account; no other artifact is. + const files: Record = { + forge: ["${dir:runtime-state}/token", undefined], + "package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"], + }; + for (const a of manifest.build.artifacts) { + assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [undefined, undefined], + `${a.name}'s token files`); + } + assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(",")); + assert.ok(manifest.consumes.includes("mesh-vault.secret-changed"), "the Go bundles hear the vault's changes"); + // The lease and the two settings (§808, §820). + assert.deepEqual(manifest.state.find((s: any) => s.name === "token-lease"), { name: "token-lease", "key-ttl": true, "max-mib": 1 }); + assert.deepEqual([manifest.config["token-ttl"]?.default, manifest.config["token-ttl"]?.runtime], ["24h", true]); + assert.deepEqual([manifest.config["mint-lease"]?.default, manifest.config["mint-lease"]?.runtime], ["60s", true]); }); test("the package seats write as an account of their own: plain, in a team writing only packages, its token write:package alone, renewed when the forge rejects it", async () => { @@ -383,10 +399,10 @@ test("the package seats write as an account of their own: plain, in a team writi const account = forge.users.get(PACKAGES_ACCOUNT); assert.ok(account, "the module made the packages account"); assert.equal(account!.admin, false, "the packages account is no administrator"); - const held = forge.tokens.filter((t) => t.name === "mesh-packages"); - assert.deepEqual(held.map((t) => [t.user, t.scopes]), [[PACKAGES_ACCOUNT, ["write:package"]]]); - assert.equal(await readFile(join(env.MESH_GITEA_STATE_DIR, "packages-token"), "utf8"), held[0].sha1 + "\n"); - assert.equal(await readFile(join(env.MESH_GITEA_STATE_DIR, "packages-token.scopes"), "utf8"), "write:package for mesh-packages\n"); + const named = (t: { name: string }) => t.name === "mesh-packages" || t.name.startsWith("mesh-packages-"); + const held = forge.tokens.filter(named); + assert.deepEqual(held.map((t) => [t.user, t.name, t.scopes]), [[PACKAGES_ACCOUNT, "mesh-packages-1", ["write:package"]]]); + assert.equal(vaulted(PACKAGES_ACCOUNT), held[0].sha1, "kept in the vault as module/gitea/mesh-packages (H-A-426)"); const team = forge.teams.find((t) => t.name === "mesh-packages"); assert.ok(team?.members.has(PACKAGES_ACCOUNT)); assert.deepEqual(team!.units.units_map, PACKAGES_TEAM_UNITS.units_map, "the team writes packages and nothing else"); @@ -398,11 +414,12 @@ test("the package seats write as an account of their own: plain, in a team writi const renew = renewOnRefusal(source, forge.url, { delete: async (k) => { cleared.push(k); } }, (l) => said.push(l)); await renew({ key: "seat.gitea.other", op: "put" }); await renew({ key: PACKAGES_TOKEN_REFUSED, op: "delete" }); - assert.equal(forge.tokens.filter((t) => t.name === "mesh-packages").length, 0, "nothing renews but the refusal"); + assert.equal(forge.tokens.filter(named).length, 0, "nothing renews but the refusal"); await renew({ key: PACKAGES_TOKEN_REFUSED, op: "put" }); assert.deepEqual(said, ["the forge rejected the package seats' write token; minted afresh"]); assert.deepEqual(cleared, [PACKAGES_TOKEN_REFUSED]); - assert.equal(forge.tokens.filter((t) => t.name === "mesh-packages").length, 1); + assert.deepEqual(forge.tokens.filter(named).map((t) => t.name), ["mesh-packages-2"]); + assert.equal(vaulted(PACKAGES_ACCOUNT), forge.tokens.find(named)!.sha1); // The tools' token reads packages too: read:package (design 51's read-only tool token). assert.ok(TOKEN_SCOPES.includes("read:package")); }); @@ -433,12 +450,12 @@ test("an old token that cannot be deleted after the mint is said, the new token } finally { forge.faults.deleteToken = false; } - const kept = (await readFile(join(env.MESH_GITEA_STATE_DIR, "token"), "utf8")).trim(); + const kept = vaulted(TOOLS_ACCOUNT)!; assert.equal(forge.tokens.find((t) => t.sha1 === kept)?.user, TOOLS_ACCOUNT, "the account's token is kept and works"); assert.ok(forge.tokens.some((t) => t.sha1 === old.sha1)); - // The next process reuses the kept token and retires the old one it could not before. + // The next process reuses the vault's token and retires the old one it could not before. const next = new MintedToken({ url: forge.url, admin: ADMIN, passwordFile: env.MESH_GITEA_ADMIN_PASSWORD_FILE!, - file: join(env.MESH_GITEA_STATE_DIR, "token"), account: TOOLS_ACCOUNT, log: () => {} }); + account: TOOLS_ACCOUNT, oldName: TOKEN_NAME, vault: vaultOverBus(), lease: leaseOverState(), stateDir: env.MESH_GITEA_STATE_DIR, log: () => {} }); assert.equal(await next.current(), kept); assert.ok(!forge.tokens.some((t) => t.sha1 === old.sha1), "the admin's old token was deleted at the next start"); }); @@ -487,9 +504,9 @@ test("a glob rule covering main gives its approvals and override, not its status assert.deepEqual(rule.merge_whitelist_usernames, [TOOLS_ACCOUNT]); }); -test("a start with the token kept still puts main's rules right: the module's start asks for it each time (issue 948, review round 1)", async () => { - const src = await readFile(new URL("../index.ts", import.meta.url), "utf8"); - assert.match(src, /ensureMainMerges\("novox"\)/, "index.ts calls it outside the token's mint"); +// The module's start no longer puts main's rules right every ten minutes (design 47 H §764; H-A-100): ensureMainMerges is +// the mint's alone. +test("ensureMainMerges makes a main rule gone again with no token minted", async () => { const { GiteaAdmin } = await import("../dist/client.js"); const env = await environment(); forge.mainRules.delete("hq"); @@ -548,7 +565,7 @@ test("the start's pass gives each of the mesh's accounts read, as a collaborator assert.deepEqual((await fresh(env).listAllRepos()).map((r) => r.full_name).sort(), ["jschoubben/txt-game", "novox/hq"]); // The account's own token cannot grant itself: the forge asks the repository's administration (the reason for the admin login). - const own = (await readFile(join(env.MESH_GITEA_STATE_DIR, "token"), "utf8")).trim(); + const own = vaulted(TOOLS_ACCOUNT)!; const self = await fetch(`${forge.url}/api/v1/repos/jschoubben/car-hunter/collaborators/${TOOLS_ACCOUNT}`, { method: "PUT", headers: { Authorization: `token ${own}`, "Content-Type": "application/json" }, body: JSON.stringify({ permission: "read" }) }); assert.equal(self.status, 404, "a repository the account cannot read is not even there for it"); diff --git a/modules/gitea/test/trunk.test.ts b/modules/gitea/test/trunk.test.ts deleted file mode 100644 index 2323f0afd..000000000 --- a/modules/gitea/test/trunk.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341): both statuses name -// the head and the trunk commit; a trunk's move puts the merge check of every open pull request into that trunk — and -// of none into another — back to pending with the reason, and runs nothing; a verdict that lands judged against a trunk -// that has moved since is said out of date. - -import { test } from "node:test"; -import assert from "node:assert/strict"; - -import { checkOnItsWay, outOfDateStatuses, outOfDateWords, trunkNamed, verdictAtTrunk, weighTrunks } from "../dist/trunk.js"; -import { GateWriter } from "../dist/gate.js"; - -const HEAD = "dfb1415aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; -const TRUNK = "a2c2c35bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; -const MOVED = "d28ca95ccccccccccccccccccccccccccccccccc"; - -test("a trunk's move puts an open head's merge check out of date, naming both commits, unless a check is on its way", () => { - const verdict = (trunk: string, state = "success") => ({ - "mesh/merge-gate": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: x` }, - "mesh/repo-check": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: y` } }); - const put = outOfDateStatuses(verdict(TRUNK), MOVED); - assert.deepEqual(put.map((s) => [s.context, s.state]), [["mesh/merge-gate", "pending"], ["mesh/repo-check", "pending"]]); - assert.equal(put[0].description, "out of date: judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc; " + - "judged again on a recheck or when it is merged"); - assert.equal(put[0].description, outOfDateWords(TRUNK, MOVED)); - assert.equal(trunkNamed(put[0].description), "a2c2c35bbbbb", "an out-of-date status still names what it judged"); - // A failure is out of date too: it judged another merge. - assert.equal(outOfDateStatuses(verdict(TRUNK, "failure"), MOVED).length, 2); - // Already judged against the trunk's head; a check on its way or already out of date; no check yet: left alone. - assert.deepEqual(outOfDateStatuses(verdict(MOVED), MOVED), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: "building on ace since 14:02" } }, MOVED), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: put[0].description } }, MOVED), []); - assert.deepEqual(outOfDateStatuses({}, MOVED), []); - // A head with no repository check of its own gets no pending one a verdict would never set. - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": verdict(TRUNK)["mesh/merge-gate"] }, MOVED).map((s) => s.context), - ["mesh/merge-gate"]); - // A verdict naming no trunk, of a build seat from before the rule, judged an earlier trunk. - assert.match(outOfDateStatuses({ "mesh/merge-gate": { state: "success", description: "pass: x" } }, MOVED)[0].description, - /judged against a trunk it does not name, the trunk is now d28ca95ccccc/); - - assert.ok(checkOnItsWay({ state: "pending", description: "waiting in the build queue since 14:00" })); - assert.ok(checkOnItsWay({ state: "pending", description: "checking again: a person asked" })); - assert.ok(!checkOnItsWay({ state: "pending", description: put[0].description })); - assert.deepEqual(verdictAtTrunk(verdict(MOVED), MOVED), { current: true, onItsWay: false, judged: "d28ca95ccccc" }); - assert.equal(verdictAtTrunk(verdict(TRUNK), MOVED).current, false); -}); - -/** A forge holding open pull requests into two branches, each head's statuses, and what was written. */ -function aForge(pulls: { number: number; base: string; head: string }[], heads: Record) { - const statuses = new Map>(); - const writes: string[] = []; - const verdict = (trunk: string) => ({ - "mesh/merge-gate": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` }, - "mesh/repo-check": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` } }); - for (const p of pulls) statuses.set(p.head, verdict(heads[p.base])); - const forge = { - listOpenPulls: async () => pulls.map((p) => ({ number: p.number, title: "t", state: "open", merged: false, base: p.base, - head: "feat", head_sha: p.head, html_url: `http://forge/pulls/${p.number}` })), - branchHead: async (_o: string, _r: string, branch: string) => heads[branch], - setCommitStatus: async (_o: string, _r: string, sha: string, s: { context: string; state: string; description: string }) => { - writes.push(`${sha} ${s.context} ${s.state}`); - statuses.set(sha, { ...statuses.get(sha), [s.context]: { state: s.state, description: s.description } }); - }, - headChecks: async (_o: string, _r: string, sha: string) => statuses.get(sha) ?? {}, - }; - return { forge, writes, statuses }; -} - -test("a push to a trunk puts every open pull request into it out of date — twenty-five of them — and none into another", async () => { - const heads: Record = { main: TRUNK, release: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" }; - const pulls = Array.from({ length: 25 }, (_, i) => ({ number: i + 1, base: "main", head: `${String(i).padStart(2, "0")}`.repeat(20) })); - pulls.push({ number: 99, base: "release", head: "9".repeat(40) }); - const { forge, writes, statuses } = aForge(pulls, heads); - const gates = new GateWriter(forge); - const trunks: Record = {}; - - // First sight: each trunk is taken as it is, and nothing is put out of date. - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true); - assert.deepEqual(writes, []); - assert.equal(trunks["novox/mesh-host:main"], TRUNK); - // Nothing moved: nothing read past the trunks, nothing written. - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), false); - - heads.main = MOVED; - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true); - assert.equal(writes.length, 50, "both statuses of each of the 25 pull requests into main"); - for (const p of pulls.filter((p) => p.base === "main")) { - const s = statuses.get(p.head)!; - assert.equal(s["mesh/merge-gate"].state, "pending"); - assert.match(s["mesh/merge-gate"].description!, /judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc/); - assert.equal(s["mesh/repo-check"].state, "pending"); - } - assert.equal(statuses.get("9".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into another branch is left"); - assert.equal(trunks["novox/mesh-host:main"], MOVED); - - // Weighed again, nothing more: the move was taken once, and the out-of-date statuses are left as they are. - writes.length = 0; - heads.main = "f".repeat(40); - await weighTrunks(forge, gates, trunks, "novox", "mesh-host"); - assert.deepEqual(writes, [], "a check already out of date is not written again"); -}); - -test("a trunk that cannot be read is weighed again on the next pass, never recorded half", async () => { - const heads: Record = { main: TRUNK }; - const { forge } = aForge([{ number: 1, base: "main", head: "1".repeat(40) }], heads); - const trunks: Record = { "novox/mesh-host:main": TRUNK }; - heads.main = MOVED; - const failing = { ...forge, setCommitStatus: async () => { throw new Error("the forge is away"); } }; - assert.equal(await weighTrunks(failing, new GateWriter(failing), trunks, "novox", "mesh-host"), false); - assert.equal(trunks["novox/mesh-host:main"], TRUNK, "not recorded: the next pass weighs it again"); -}); - -test("a verdict judged against a trunk newer than the pass's first read is not put out of date", async () => { - const NEWER = "ffffffffffffffffffffffffffffffffffffffff"; - const heads: Record = { main: TRUNK }; - const { forge, statuses } = aForge([{ number: 1, base: "main", head: HEAD }], heads); - const trunks: Record = { "novox/mesh-host:main": TRUNK }; - // The pass reads main at MOVED; by the head's turn the trunk moved again, and the head's check answered for it. - let reads = 0; - const moving = { ...forge, branchHead: async () => (reads++ === 0 ? MOVED : NEWER) }; - statuses.set(HEAD, { "mesh/merge-gate": { state: "success", description: `head x merged into trunk ${NEWER.slice(0, 12)} — pass` } }); - await weighTrunks(moving, new GateWriter(moving), trunks, "novox", "mesh-host"); - assert.equal(statuses.get(HEAD)!["mesh/merge-gate"].state, "success", "a fresh verdict was put out of date"); -}); - -test("a release branch's move puts every open pull request into it out of date, as a trunk's does (ADR 0358 §5)", async () => { - // novox/hq ADR 0358 §5: for a pull request into a release branch, the release branch takes the trunk's place in ADR - // 0323 — the check merges the head onto the release branch's head and names it as the trunk commit, so the release - // branch's move puts its open verdicts out of date, and leaves those into main alone. - const release = "feat/57-config-and-provisioning"; - const heads: Record = { main: TRUNK, [release]: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" }; - const pulls = [{ number: 315, base: release, head: "3".repeat(40) }, { number: 1, base: "main", head: "1".repeat(40) }]; - const { forge, statuses } = aForge(pulls, heads); - const gates = new GateWriter(forge); - const trunks: Record = {}; - await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"); - - heads[release] = MOVED; - assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"), true); - const s = statuses.get("3".repeat(40))!; - assert.equal(s["mesh/merge-gate"].state, "pending"); - assert.match(s["mesh/merge-gate"].description!, /judged against trunk eeeeeeeeeeee, the trunk is now d28ca95ccccc/); - assert.equal(s["mesh/repo-check"].state, "pending"); - assert.equal(statuses.get("1".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into main is left"); - assert.equal(trunks[`novox/mesh-controller:${release}`], MOVED); - - // The merge tool's rule reads the same: a verdict judged against the release branch's old head is not current. - assert.equal(verdictAtTrunk({ "mesh/merge-gate": { state: "success", - description: "head x merged into trunk eeeeeeeeeeee — pass" } }, MOVED).current, false); -}); - -// Issue 1301: a trunk's move puts out of date only the controller's statuses the base still requires; on hq that is -// mesh/repo-check alone, judged by its own words; on a main requiring mesh/check, none (the checker's, ADR 0447 §4). -test("a trunk's move writes only the statuses the base still requires", async () => { - const { outOfDateStatuses, trunkNamed } = await import("../trunk.ts"); - const old = "1".repeat(40), now = "2".repeat(40); - const repo = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: y` }; - const gate = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: x` }; - assert.deepEqual(outOfDateStatuses({ "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context), ["mesh/repo-check"]); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context), - ["mesh/repo-check"]); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/check"]), []); - assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now).map((s: any) => s.context), - ["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before"); - // The checker's line names its trunk as " on ". - assert.equal(trunkNamed(`pass ${"a".repeat(12)} on ${old.slice(0, 12)} | unit 3 run`), old.slice(0, 12)); - assert.equal(trunkNamed("building on shanks since 10:00"), undefined); -}); diff --git a/modules/gitea/test/watch.test.ts b/modules/gitea/test/watch.test.ts index 39572a399..5680f693c 100644 --- a/modules/gitea/test/watch.test.ts +++ b/modules/gitea/test/watch.test.ts @@ -1,9 +1,9 @@ import assert from "node:assert/strict"; -import { mock, test } from "node:test"; +import { test } from "node:test"; import type { GiteaPull } from "../client.ts"; -// **No poll of the forge** (issue 1422, notes 10 and 11): the forge's events announce heads and merges; a pass runs once at -// the start and when the receiver listens. +// **No poll of the forge for heads** (issue 1422; design 47 H §764, H-A-100): the forge's events say a pull request's new +// head as pull.updated, a merge and a close; nothing weighs a sibling or asks a merge check. const edited = (base: string) => ({ name: "forge.pull-request.edited", body: { owner: "novox", repo: "hq", number: 7, base, merged: false } }); @@ -12,10 +12,9 @@ function deps() { return { calls, d: { getRepo: async () => ({ r: 1 }), getPull: async () => ({ state: "open", base: "trunk" }) as any, - announceHead: async () => { calls.push("head"); }, + announceUpdated: async () => { calls.push("updated"); }, announceMerge: async () => { calls.push("merge"); }, announceClosed: async () => { calls.push("closed"); }, - siblingMoves: async () => { calls.push("siblings"); }, } }; } @@ -23,51 +22,15 @@ test("an edited event announces the head into the base it now has, without a pol const { actOn } = await import("../watch.ts"); const { calls, d } = deps(); await actOn(edited("trunk"), d); - assert.deepEqual(calls, ["head"]); + assert.deepEqual(calls, ["updated"]); }); test("a close without a merge is announced by its event, a merged close is left to the merge event", async () => { const { actOn } = await import("../watch.ts"); const { calls, d } = deps(); await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: false } }, d); - assert.deepEqual(calls, ["closed", "siblings"]); + assert.deepEqual(calls, ["closed"]); calls.length = 0; await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: true } }, d); assert.deepEqual(calls, []); }); - -test("no timer polls after the start: one pass ends and nothing is scheduled; a failed one is asked again", async () => { - const { startPass } = await import("../watch.ts"); - mock.timers.enable({ apis: ["setTimeout", "setInterval"] }); - try { - let runs = 0; - await startPass(async () => { runs++; }, { retryMs: 60_000, log: () => {} }); - mock.timers.tick(24 * 3600_000); - assert.equal(runs, 1, "a day later the forge was not asked again"); - let tries = 0; - const retried = startPass(async () => { if (++tries < 2) throw new Error("forge down"); }, { retryMs: 60_000, log: () => {} }); - await Promise.resolve(); await Promise.resolve(); - mock.timers.tick(60_000); - await retried; - assert.equal(tries, 2); - } finally { - mock.timers.reset(); - } -}); - -test("a start pass announces a head nobody announced, and only remembers one the forge shows a check of", async () => { - const { announceNewHeads } = await import("../watch.ts"); - const pull = (n: number, sha: string): GiteaPull => ({ number: n, state: "open", head_sha: sha, base: "main", - updated_at: new Date().toISOString() } as unknown as GiteaPull); - const announced: number[] = [], said: string[] = []; - const heads: Record = {}; - await announceNewHeads("novox/hq", [pull(1, "a".repeat(40)), pull(2, "b".repeat(40))], heads, false, - new Date(Date.now() - 24 * 3600_000).toISOString(), { - alreadyChecked: async (p) => p.number === 2, - announceHead: async (p) => { announced.push(p.number); return true; }, - missed: (w) => said.push(w), - }); - assert.deepEqual(announced, [1]); - assert.equal(heads["novox/hq#2@main"], "b".repeat(40), "the checked head is remembered, not announced"); - assert.equal(said.length, 1); -}); diff --git a/modules/gitea/token.ts b/modules/gitea/token.ts index 2c02a65d7..c02c3fa01 100644 --- a/modules/gitea/token.ts +++ b/modules/gitea/token.ts @@ -4,45 +4,88 @@ // paste in, and pasting one into settings would put a secret in the inventory in plaintext. What // the mesh does deliver is the admin account: a login the manifest names and a password the vault // minted and the host unsealed into a file (novox/hq ADR 0086). That account is enough to mint a -// token, so the module mints its own (hq issue 100, the forge's tools): +// token, so the module mints its own (hq issue 100, the forge's tools), for each of its two accounts, the tools' +// (`mesh-tools`) and the package seats' (`mesh-packages`): // -// - at first use, when none is kept: POST /users/{admin}/tokens over basic auth, with the two -// scopes the tools and the watcher need, and no more; -// - kept in the module's own state, a 0600 file, and read back on the next start — the forge -// hands a token's value out exactly once, so a token not kept is a token lost; -// - re-minted when the forge rejects it (401) or the kept file is gone. The one case that is not -// a fault: the forge's data was restored from a predecessor and the token the file names never -// existed there; -// - minted by one process at a time. The runtime starts each of the bundle's entrypoints as a process -// of its own (novox/hq ADR 0193): the watcher (index.js) and the tools (tools/index.js) are two -// processes over one kept file. Two that minted at once left the forge two tokens by one name, which -// gitea then refuses to delete by name — for ever, and every forge tool with it (the 2026-10-14 -// outage). So a mint holds a lock file beside the kept token, and reads the kept file again once it -// holds it: what another process minted meanwhile is reused, not minted over; -// - replaced by id: an old token by this name is found in the account's list and deleted by its id, -// every one of them, so a name held twice is cleared rather than refused. -// -// - minted for the tools' account, not the administrator (novox/hq ADR 0365 §2, issue 469): the administrator's -// login mints it for `mesh-tools` (tools-account.ts), after making that account and its team, and deletes any -// token by this name the administrator itself still holds — the token the tools used before. A token kept -// for another account than the one asked (the scopes line says whose) is minted again at the next start. +// - **kept as a secret, the module's own in the vault** (design 47 H2 §808, §822; H-A-422, H-A-426): written through +// the seat `mesh-vault`'s two-step sealed write `own-put` under the account's name, so the vault keeps it as +// `module/gitea/`, its newest generation only, and read through the seat's `get`, sealed to this process's +// key. Never a file in the runtime state and never plain in a state: the forge hands a token's value out exactly +// once, and the vault is where the module keeps what it must not lose; +// - **one name per mint**, `-`, the generation the one this own-put makes (get's generation plus +// one; 1 when the vault holds none; H-A-430 (1)). The token minted is written through own-put first, and only then +// is the token it replaces deleted at the forge, by its id: no moment is without a valid token, and a mint that +// fails leaves the old one standing. The first mint replaces the tokens the module kept before under the account's +// old fixed name; +// - **minted by one process at a time** (§808). The runtime starts each of the bundle's entrypoints as a process of its +// own (novox/hq ADR 0193), and two that minted at once left the forge two tokens by one name (the 2026-10-14 outage). +// A process the forge refuses first reads the vault's token; only when the refused token is the vault's current one +// does it take the lease — the key `mint` in the module's state `token-lease`, created only, living `mint-lease` (a +// setting, default 60 s) — and mint. A process that finds the lease taken waits for that key to change, at most the +// lease, then reads the vault again; past it, the lease has expired and the waiter creates it itself; +// - **minted again when older than `token-ttl`** (a setting, default 24 hours), its age the vault's `changed-at`; +// - **minted again when minted with other scopes** (H-A-439): the value the vault keeps holds the token and the scopes +// it was minted with, so a token carrying a scope beyond the ones the tools take (such as write:admin) is minted again +// unasked, and the one it replaces deleted, as when the scopes were kept in a file beside the token; +// - minted for the account, not the administrator (novox/hq ADR 0365 §2, issue 469): the administrator's login mints +// it for the account, after making that account and its team, and deletes any token named `mesh-tools` the +// administrator itself still holds — the token the tools used before. // // An explicitly configured token still wins, and is never minted over: if it is rejected, that is // reported, not repaired — somebody chose it. // -// The token is never logged. Lines say that one was minted, reused or renewed, and where it is -// kept; never what it is. +// The token is never logged. Lines say that one was minted, reused or renewed, and under which name; +// never what it is. -import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; +import { existsSync, mkdirSync, rmSync, writeFileSync, readFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; +import { generateKeyPair, open, sealAnonymous, type Box, type KeyPair } from "@novox/mesh-sdk/seal"; +import { broker } from "@novox/mesh-sdk/messaging"; +import { askRuntime } from "@novox/mesh-sdk/runtime"; +import { state, type State } from "@novox/mesh-sdk/state"; import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js"; - -/** The name the token carries in the forge's own list — one per mesh runtime, found by name. */ import { keepMainRules } from "./mainrules.js"; +import { durationMs } from "./taken.js"; +/** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */ export const TOKEN_NAME = "mesh-tools"; +/** The module whose own secrets the vault keeps its tokens as (§822: the module named by the caller's account). */ +export const VAULT_MODULE = "gitea"; + +/** The vault's name of an account's token: `module/gitea/` (H-A-426). */ +export function vaultName(account: string): string { + return `module/${VAULT_MODULE}/${account}`; +} + +/** The forge's name of an account's token of one generation: `-` (H-A-422 (2)). */ +export function mintName(account: string, generation: number): string { + return `${account}-${generation}`; +} + +/** The state the mint's lease is kept in, and its one key (§808, §820). */ +export const LEASE_STATE = "token-lease"; +export const LEASE_KEY = "mint"; + +/** token-ttl's and mint-lease's defaults (§808). */ +export const TOKEN_TTL_DEFAULT = "24h"; +export const MINT_LEASE_DEFAULT = "60s"; + +/** A setting the node-engine composes as `MESH_CONFIG_`, a duration, in milliseconds; the default when unset, and + * when it is no duration (said). */ +export function settingMs(env: NodeJS.ProcessEnv, setting: string, fallback: string, log: (line: string) => void = () => {}): number { + const raw = env[`MESH_CONFIG_${setting.toUpperCase().replace(/-/g, "_")}`]; + const dflt = durationMs(fallback)!; + if (raw === undefined || raw.trim() === "") return dflt; + const ms = durationMs(raw); + if (ms === null) { + log(`the setting ${setting} is ${JSON.stringify(raw)}, no duration: the default ${fallback} holds`); + return dflt; + } + return ms; +} + /** * The least the fifteen tools and the watcher need (gitea's route groups, 1.20+ scoped tokens): * write:repository — create/delete repositories, pull requests (list/get/open/merge); @@ -58,8 +101,6 @@ export const TOKEN_NAME = "mesh-tools"; * **Not write:admin** (novox/hq ADR 0266). It was here so a person could settle the forge's users through * `gitea_api` (novox/hq 229); whoever may call a tool includes agents, and the forge's administration is the * operator's. The provisioner settles users with the admin account's own login (GiteaAdmin), never this token. - * A token kept with a different list is minted again with this one at the next start (the scopes are kept - * beside it), and the old one is deleted from the forge by its id — so the scope a kept token had does not outlive this. * * A token kept from before a scope was added lacks it: the forge answers such a call with * `403 token does not have at least one of required scope(s)`, and the client treats that like a @@ -91,19 +132,135 @@ export class ConfiguredToken implements TokenSource { } } -/** The forge would not take the admin account: it is missing, or its password is not the one the mesh holds. */ +/** The forge would not take the admin account: it refused the login the mesh holds (design 47 H2 §776). Said as the + * forge's refusal, never as an account to create: whether the forge is away is the seat's to judge (seat.ts). */ export class AdminRefused extends Error { constructor(admin: string, status: number) { - super( - `the forge refused the admin account "${admin}" (${status}) — it does not exist there, or its password is not ` + - `the one the vault delivered. The admin-bootstrap step creates it on a forge the mesh raised; a forge whose data ` + - `came from a predecessor does not have it. Create "${admin}" on the forge with the delivered password and the ` + - `token is minted on the next call — the tools stay registered and the watcher keeps trying`, - ); + super(`the forge refuses the mesh's admin account "${admin}" (${status})`); this.name = "AdminRefused"; } } +/** A token as the vault holds it: the token, the scopes it was minted with, the generation and when it changed (`get`'s + * answer, opened). */ +export interface VaultToken { + readonly token: string; + readonly scopes: readonly string[]; + readonly generation: number; + readonly changedAt: string; +} + +/** The value the vault keeps for an account: the token and the scopes it was minted with (§808, H-A-439). */ +export function vaultValue(token: string, scopes: readonly string[]): string { + return JSON.stringify({ token, scopes: [...scopes] }); +} + +/** A value the vault keeps, opened: its token and scopes. A value of another form names no scopes, so it is minted again. */ +export function openValue(value: string): { token: string; scopes: readonly string[] } { + try { + const v = JSON.parse(value); + if (v && typeof v.token === "string" && Array.isArray(v.scopes)) return { token: v.token, scopes: v.scopes.map(String) }; + } catch { + // not the token and its scopes + } + return { token: value.trim(), scopes: [] }; +} + +/** Whether two lists name the same scopes, in any order. */ +function sameScopes(a: readonly string[], b: readonly string[]): boolean { + return [...a].sort().join(",") === [...b].sort().join(","); +} + +/** The vault as the minter reaches it: the seat `mesh-vault`'s `get` and `own-put` (§808, §822). */ +export interface TokenVault { + /** The account's token the vault holds, or null when it holds none. */ + get(account: string): Promise; + /** Write the account's token and the scopes it was minted with as the module's own; answers the generation the vault kept. */ + put(account: string, token: string, scopes: readonly string[]): Promise; +} + +/** The lease `mint` in the state `token-lease` (§808). */ +export interface MintLease { + /** Create the lease for `holder`, living `ms`; false when another holds it. */ + take(holder: string, ms: number): Promise; + /** The lease's holder and since when, or null when nobody holds it. */ + read(): Promise<{ holder: string; since: string } | null>; + /** Delete the lease, when `holder` still holds it. */ + release(holder: string): Promise; + /** Resolves when the lease's key changes (deleted, or written again), or after `ms`, whichever is first. */ + changed(ms: number): Promise; +} + +/** The vault's words when it holds no secret by the name asked (mesh-vault's Get). */ +const HOLDS_NONE = /the vault holds no secret named/; + +/** The vault over the bus: `get` sealed to this process's own key, made once a process; `own-put` in its two steps. */ +export function vaultOverBus(request: (verb: string, body: unknown) => Promise = (v, b) => broker().request(v, b)): TokenVault { + let keys: KeyPair | undefined; + return { + async get(account) { + keys ??= generateKeyPair(); + let answer: { generation?: number; "changed-at"?: string; sealed?: Box }; + try { + answer = (await request("seat:mesh-vault.get", { name: vaultName(account), public_key: keys.publicKey })) as typeof answer; + } catch (err) { + if (HOLDS_NONE.test(err instanceof Error ? err.message : String(err))) return null; + throw err; + } + if (!answer?.sealed) throw new Error(`the vault answered no sealed ${vaultName(account)}`); + return { ...openValue(open(answer.sealed, keys.privateKey)), generation: answer.generation ?? 0, changedAt: answer["changed-at"] ?? "" }; + }, + async put(account, token, scopes) { + const opened = (await request("seat:mesh-vault.own-put", { name: account })) as { call?: string; seal_to?: string }; + if (!opened?.call || !opened.seal_to) throw new Error(`the vault opened no own-put call for ${vaultName(account)}`); + const kept = (await request("seat:mesh-vault.own-put", { call: opened.call, sealed: sealAnonymous(vaultValue(token, scopes), opened.seal_to) })) as { generation?: number }; + return kept?.generation ?? 0; + }, + }; +} + +/** The runtime's refusal of a create whose key has a value (mesh-sdk's CODE_CHANGED). */ +const CODE_CHANGED = -32010; + +/** The lease in the module's state `token-lease` over the runtime: a create with the lease as its time to live, and one + * watch of the key a process, handing each change to the waiters. */ +export function leaseOverState(st: State<{ holder: string; since: string }> = state(LEASE_STATE), + ask: (method: string, params: unknown) => Promise = askRuntime): MintLease { + const waiters = new Set<() => void>(); + let watching: Promise | undefined; + return { + async take(holder, ms) { + try { + await ask("mesh/state.create", { state: LEASE_STATE, key: LEASE_KEY, value: { holder, since: new Date().toISOString() }, + ttl_seconds: Math.max(1, Math.ceil(ms / 1000)) }); + return true; + } catch (err) { + if ((err as { code?: number }).code === CODE_CHANGED) return false; + throw err; + } + }, + async read() { + return (await st.get(LEASE_KEY))?.value ?? null; + }, + async release(holder) { + if ((await st.get(LEASE_KEY))?.value?.holder === holder) await st.delete(LEASE_KEY); + }, + async changed(ms) { + watching ??= st.watch((change) => { + if (!change.current) for (const wake of [...waiters]) wake(); + }, { key: LEASE_KEY }); + await watching; + await new Promise((resolve) => { + const wake = () => { clearTimeout(timer); waiters.delete(wake); resolve(); }; + const timer = setTimeout(wake, ms); + waiters.add(wake); + // Released between the refused create and this wait: nothing to wait for. + void st.get(LEASE_KEY).then((e) => { if (!e) wake(); }, () => {}); + }); + }, + }; +} + export interface MintedTokenOptions { /** The forge, e.g. http://127.0.0.1:3000. */ readonly url: string; @@ -111,115 +268,121 @@ export interface MintedTokenOptions { readonly admin: string; /** The file the host unsealed the admin password into (ADR 0086). Read at mint time, so a rotation takes. */ readonly passwordFile: string; - /** Where the token is kept: a 0600 file in the module's own state. */ - readonly file: string; - readonly name?: string; + /** The account the token is minted for, and the vault name it is kept under (H-A-426). */ + readonly account: string; + /** The token's fixed name before a name per mint: the first mint deletes the account's tokens by it (H-A-430 (1)). */ + readonly oldName: string; readonly scopes?: readonly string[]; - /** - * The account the token is minted for: the tools' own (novox/hq ADR 0365 §2). The admin login mints it, after - * `setUp` made the account, and the admin's own tokens by this name are deleted. Left out, the token is the - * admin's own, as it was before. - */ - readonly account?: string; - /** Run with the admin's password before each mint for `account`: makes the account and its team (tools-account.ts). */ + /** Run with the admin's password before each mint: makes the account and its team (tools-account.ts). */ readonly setUp?: (password: string) => Promise; + /** Where the module keeps its token, and the mint's lease (§808). */ + readonly vault: TokenVault; + readonly lease: MintLease; + /** token-ttl and mint-lease, in milliseconds (§808). */ + readonly ttlMs?: number; + readonly leaseMs?: number; + /** Who holds the lease when this process does: the node and the process. */ + readonly holder?: string; + /** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */ + readonly stateDir?: string; + readonly now?: () => Date; readonly log?: (line: string) => void; readonly fetch?: typeof fetch; } -/** The token the module mints for itself, kept in its state and renewed when the forge rejects it. */ +/** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */ export class MintedToken implements TokenSource { - private held: string | null = null; - private readFile = false; + private held: VaultToken | null = null; private inflight: Promise | null = null; - private readonly name: string; private readonly scopes: readonly string[]; - private readonly account: string; + private readonly ttlMs: number; + private readonly leaseMs: number; + private readonly holder: string; + private readonly now: () => Date; private readonly log: (line: string) => void; private readonly fetchImpl: typeof fetch; constructor(private readonly opts: MintedTokenOptions) { - this.name = opts.name ?? TOKEN_NAME; this.scopes = opts.scopes ?? TOKEN_SCOPES; - this.account = opts.account ?? opts.admin; + this.ttlMs = opts.ttlMs ?? durationMs(TOKEN_TTL_DEFAULT)!; + this.leaseMs = opts.leaseMs ?? durationMs(MINT_LEASE_DEFAULT)!; + this.holder = opts.holder ?? `${process.env.MESH_NODE || "unknown"}/${process.pid}`; + this.now = opts.now ?? (() => new Date()); this.log = opts.log ?? ((line) => console.log(`[gitea] ${line}`)); this.fetchImpl = opts.fetch ?? fetch; } + /** The account this source mints for. */ + get account(): string { + return this.opts.account; + } + /** - * Build from the runtime's environment: the forge's URL, the admin login and password file the - * manifest hands the runtime, and the module's state directory (MESH_GITEA_STATE_DIR, a directory - * the runtime mounts writable). Throws, naming what is missing, rather than hand back a source - * that cannot mint. + * The tools' token from the runtime's environment: the forge's URL, the admin login and password file the manifest + * hands the runtime, the vault and the lease over the bus. Throws, naming what is missing, rather than hand back a + * source that cannot mint. One source per account and runtime state in a process: two would each renew on a 401. */ static fromEnv(url: string, env: NodeJS.ProcessEnv = process.env): MintedToken { - const opts = MintedToken.optionsFromEnv(url, env); - // One source per kept file in a process: two sources in one process would each renew on a 401. - // This covers one process only. The watcher and the tools are two processes (the runtime starts - // each entrypoint as its own), and those are kept apart by the mint's lock file (mint, below). - const shared = MintedToken.shared.get(opts.file); + const account = env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT; + const { admin, passwordFile } = adminFromEnv(env, "no Gitea token, and nothing to mint one with — set GITEA_TOKEN, or"); + const key = `${account} ${env.MESH_GITEA_STATE_DIR ?? ""}`; + const shared = MintedToken.shared.get(key); if (shared) return shared; - const source = new MintedToken(opts); - MintedToken.shared.set(opts.file, source); + if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`); + const source = new MintedToken({ + ...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, + // GiteaAdmin is loaded when first used: client.ts imports this file. + setUp: async (password) => { + const { GiteaAdmin } = await import("./client.js"); + await setUpToolsAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"), keepMainRules(env)); + }, + }); + MintedToken.shared.set(key, source); return source; } private static readonly shared = new Map(); - private static optionsFromEnv(url: string, env: NodeJS.ProcessEnv): MintedTokenOptions { - const admin = env.MESH_GITEA_ADMIN_USER; - const passwordFile = env.MESH_GITEA_ADMIN_PASSWORD_FILE; - const stateDir = env.MESH_GITEA_STATE_DIR; - const missing = [ - admin ? null : "MESH_GITEA_ADMIN_USER", - passwordFile ? null : "MESH_GITEA_ADMIN_PASSWORD_FILE", - stateDir ? null : "MESH_GITEA_STATE_DIR", - ].filter((v): v is string => v !== null); - if (missing.length) { - throw new Error(`no Gitea token, and nothing to mint one with — set GITEA_TOKEN, or ${missing.join(", ")}`); - } - // The tools' own account, never the administrator (novox/hq ADR 0365 §2): MESH_GITEA_TOOLS_USER names it. - const account = env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT; - if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`); + /** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */ + static settingsFromEnv(env: NodeJS.ProcessEnv): Pick { + const log = (line: string) => console.log(`[gitea] ${line}`); return { - url, admin: admin!, passwordFile: passwordFile!, file: join(stateDir!, "token"), account, - // GiteaAdmin is loaded when first used: client.ts imports this file. - setUp: async (password) => { - const { GiteaAdmin } = await import("./client.js"); - await setUpToolsAccount(new GiteaAdmin(url, admin!, password), account, () => randomBytes(24).toString("base64url"), keepMainRules(env)); - }, + vault: sharedVault(), lease: sharedLease(), + ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log), + stateDir: env.MESH_GITEA_STATE_DIR || undefined, }; } + /** The token held, read from the vault when none is, minted when the vault holds none or one older than token-ttl. */ async current(): Promise { - if (this.held !== null) return this.held; - if (!this.readFile) { - this.readFile = true; - const kept = this.read(); - if (kept !== null && this.keptScopes() === this.scopesLine()) { - this.held = kept; - this.log(`reusing the token kept at ${this.opts.file}`); - // A retirement of the admin's old token that failed after the mint is tried again, once a process. - if (existsSync(this.retireFile)) await this.locked(() => this.retireAdmin()).catch((err) => this.log(`${err}`)); - return kept; - } - if (kept !== null) return this.mint("the kept token was minted with other scopes than the tools take now — minting one with them", kept); + if (this.held !== null && !this.expired(this.held)) return this.held.token; + const kept = await this.opts.vault.get(this.opts.account); + if (kept === null) return this.mint("the vault holds no token for this account — minting one", null); + if (this.expired(kept)) return this.mint(`the vault's token is older than token-ttl (${this.ttlMs / 1000}s) — minting one`, kept.token); + if (!sameScopes(kept.scopes, this.scopes)) { + return this.mint(`the vault's token was minted with other scopes than the tools take now (${kept.scopes.join(", ") || "none kept"}) — minting one with them`, kept.token); } - return this.mint("no token kept — minting one", null); + if (this.held === null) { + this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`); + // A retirement of the admin's old token that failed after the mint is tried again, once a process. + if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`)); + } + this.held = kept; + return kept.token; } async renew(rejected: string): Promise { // Another caller already renewed while this one was in flight with the old token. - if (this.held !== null && this.held !== rejected) return this.held; - // Or another process did, and kept it: use what is kept before minting over it. - const kept = this.read(); - if (kept !== null && kept !== rejected) { + if (this.held !== null && this.held.token !== rejected) return this.held.token; + // A refusal of a stale token mints nothing: the vault's newer one is used (§808). + const kept = await this.opts.vault.get(this.opts.account); + if (kept !== null && kept.token !== rejected) { this.held = kept; - this.log(`the forge rejected the token held; the kept one at ${this.opts.file} is newer — reusing it`); - return kept; + this.log(`the forge rejected the token held; the vault's ${vaultName(this.opts.account)} is newer (generation ${kept.generation}) — reusing it`); + return kept.token; } this.held = null; - return this.mint("the forge rejected the kept token — minting a fresh one", rejected); + return this.mint("the forge rejected the vault's token — minting a fresh one", rejected); } /** What the forge's scoped tokens say when a kept token predates a scope the tools now need. */ @@ -227,132 +390,55 @@ export class MintedToken implements TokenSource { return status === 403 && /required scope/i.test(body); } + private expired(t: VaultToken): boolean { + const at = Date.parse(t.changedAt); + return Number.isFinite(at) && this.now().getTime() - at > this.ttlMs; + } + /** - * One mint at a time: concurrent first calls in this process share it, and a mint in another process - * on this machine is waited for (the lock file). Once the lock is held, the kept file is read again: - * a token there that is not `stale` (the one rejected, or kept with other scopes) and carries the - * scopes asked for was minted by the process that held the lock before — it is reused. + * One mint at a time: concurrent calls in this process share it, and a mint in another process is waited for (the + * lease). Holding the lease, the vault is read again: a token there that is not `stale` (the one refused or expired) + * was minted by the process that held the lease before — it is used, not minted over. */ private mint(why: string, stale: string | null): Promise { if (this.inflight === null) { this.log(why); - this.inflight = this.locked(async () => { - const kept = this.read(); - if (kept !== null && kept !== stale && this.keptScopes() === this.scopesLine()) { - this.held = kept; - this.log(`another process minted it meanwhile — reusing the token kept at ${this.opts.file}`); - return kept; - } - return this.doMint(); - }).finally(() => { + this.inflight = this.leased(stale).finally(() => { this.inflight = null; }); } return this.inflight; } - /** How long a mint may hold the lock before another process takes it as left behind, and how long one waits. */ - static readonly LOCK_STALE_MS = 120_000; - static readonly LOCK_WAIT_MS = 150_000; - - /** - * Run `work` holding the lock file beside the kept token: created exclusively, holding this process's - * pid, the time and a nonce; removed after, only when it is still ours. A lock whose process is gone, - * or older than LOCK_STALE_MS, was left by a process that died mid-mint and is taken over — never - * waited on for ever, which would be the same lock-out by another road. - */ - private async locked(work: () => Promise): Promise { - const lock = `${this.opts.file}.lock`; - mkdirSync(dirname(this.opts.file), { recursive: true, mode: 0o700 }); - const mine = `${process.pid} ${Date.now()} ${randomBytes(8).toString("hex")}\n`; - const deadline = Date.now() + MintedToken.LOCK_WAIT_MS; + private async leased(stale: string | null): Promise { for (;;) { - try { - const fd = openSync(lock, "wx", 0o600); - try { writeSync(fd, mine); } finally { closeSync(fd); } - break; - } catch (err) { - if ((err as NodeJS.ErrnoException).code !== "EEXIST") { - throw new Error(`cannot take the mint lock at ${lock}: ${(err as Error).message}`); + if (await this.opts.lease.take(this.holder, this.leaseMs)) { + try { + const kept = await this.opts.vault.get(this.opts.account); + if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) { + this.held = kept; + this.log(`another process minted it meanwhile — reusing the vault's generation ${kept.generation}`); + return kept.token; + } + return await this.doMint(kept); + } finally { + await this.opts.lease.release(this.holder).catch((err) => + this.log(`the mint lease could not be deleted; it ends with mint-lease — ${err instanceof Error ? err.message : err}`)); } } - if (this.leftBehind(lock)) { - this.log(`the mint lock at ${lock} was left by a process that is gone — taking it over`); - try { unlinkSync(lock); } catch { /* another waiter took it over first */ } - continue; + const other = await this.opts.lease.read().catch(() => null); + this.log(`another process holds the mint lease${other ? ` (${other.holder} since ${other.since})` : ""} — waiting for it, at most mint-lease (${this.leaseMs / 1000}s)`); + await this.opts.lease.changed(this.leaseMs); + const kept = await this.opts.vault.get(this.opts.account); + if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) { + this.held = kept; + this.log(`the process that held the mint lease minted generation ${kept.generation} — reusing it`); + return kept.token; } - if (Date.now() > deadline) { - throw new Error(`another process has held the mint lock at ${lock} for over ${MintedToken.LOCK_WAIT_MS / 1000}s — not minting beside it`); - } - await new Promise((r) => setTimeout(r, 50 + Math.floor(Math.random() * 50))); - } - try { - return await work(); - } finally { - try { - if (readFileSync(lock, "utf8") === mine) unlinkSync(lock); - } catch { /* already gone */ } } } - /** Whether the lock's holder is gone: its pid answers no signal, or it is older than LOCK_STALE_MS. */ - private leftBehind(lock: string): boolean { - let text: string; - let age: number; - try { - text = readFileSync(lock, "utf8"); - age = Date.now() - statSync(lock).mtimeMs; - } catch { - return false; // released meanwhile: the next attempt takes it - } - if (age > MintedToken.LOCK_STALE_MS) return true; - const pid = Number(text.split(" ")[0]); - if (!Number.isInteger(pid) || pid <= 0) return age > 1_000; // half-written, or not ours: give it a moment - try { - process.kill(pid, 0); - return false; - } catch (err) { - return (err as NodeJS.ErrnoException).code === "ESRCH"; - } - } - - private read(): string | null { - try { - const token = readFileSync(this.opts.file, "utf8").replace(/\n$/, ""); - return token.length ? token : null; - } catch (err) { - if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; - throw new Error(`cannot read the kept Gitea token at ${this.opts.file}: ${(err as Error).message}`); - } - } - - /** The scopes as kept beside the token: sorted, one line, and whose it is when it is not the admin's. */ - private scopesLine(): string { - const scopes = [...this.scopes].sort().join(","); - return this.account === this.opts.admin ? scopes : `${scopes} for ${this.account}`; - } - - /** The scopes the kept token was minted with, "" when not kept (a token kept before they were). */ - private keptScopes(): string { - try { - return readFileSync(`${this.opts.file}.scopes`, "utf8").trim(); - } catch { - return ""; - } - } - - /** Write the token at 0600, whole or not at all: a temp file beside it, then a rename. Its scopes beside it. */ - private keep(token: string): void { - mkdirSync(dirname(this.opts.file), { recursive: true, mode: 0o700 }); - const tmp = `${this.opts.file}.tmp`; - writeFileSync(tmp, token + "\n", { mode: 0o600 }); - chmodSync(tmp, 0o600); - renameSync(tmp, this.opts.file); - writeFileSync(`${this.opts.file}.scopes.tmp`, this.scopesLine() + "\n", { mode: 0o600 }); - renameSync(`${this.opts.file}.scopes.tmp`, `${this.opts.file}.scopes`); - } - - /** One call to the forge's API with the admin login, the password read now. */ + /** The admin password, read now. */ private password(): string { try { return readFileSync(this.opts.passwordFile, "utf8").replace(/\n$/, ""); @@ -361,6 +447,7 @@ export class MintedToken implements TokenSource { } } + /** One call to the forge's API with the admin login. */ private adminCall(password = this.password()): AdminCall { const authorization = "Basic " + Buffer.from(`${this.opts.admin}:${password}`).toString("base64"); const api = `${this.opts.url.replace(/\/+$/, "")}/api/v1`; @@ -381,71 +468,81 @@ export class MintedToken implements TokenSource { } /** Where a retirement of the admin's old token that failed is remembered, to be tried again (retireAdmin). */ - private get retireFile(): string { - return `${this.opts.file}.retire-admin`; + private get retireFile(): string | null { + return this.opts.stateDir ? join(this.opts.stateDir, `${this.opts.account}.retire-admin`) : null; } /** - * The admin's own token by this name goes: what the tools used before must not outlive the move (novox/hq ADR - * 0365 §2). Run after the account's token is minted and kept, so a failure here never leaves the tools without - * a token: it is said, remembered beside the kept token, and tried again when a process next reads that token. + * The admin's own token named `mesh-tools` goes: what the tools used before must not outlive the move (novox/hq ADR + * 0365 §2). Run after the account's token is minted and kept, so a failure here never leaves the tools without a + * token: it is said, remembered, and tried again when a process next reads the vault's token. */ private async retireAdmin(admin: AdminCall = this.adminCall()): Promise { - if (this.account === this.opts.admin) return; + if (this.opts.oldName !== TOKEN_NAME) return; try { - const retired = await this.dropNamed(admin, `/users/${encodeURIComponent(this.opts.admin)}/tokens`, this.opts.admin); - if (retired > 0) this.log(`deleted ${retired} token(s) named "${this.name}" the admin account "${this.opts.admin}" held: the tools act as "${this.account}" now`); - rmSync(this.retireFile, { force: true }); + const retired = await this.dropNamed(admin, `/users/${encodeURIComponent(this.opts.admin)}/tokens`, this.opts.admin, TOKEN_NAME); + if (retired > 0) this.log(`deleted ${retired} token(s) named "${TOKEN_NAME}" the admin account "${this.opts.admin}" held: the tools act as "${this.opts.account}" now`); + if (this.retireFile) rmSync(this.retireFile, { force: true }); } catch (err) { - writeFileSync(this.retireFile, `${new Date().toISOString()}\n`, { mode: 0o600 }); - this.log(`FAILED to delete the token(s) named "${this.name}" the admin account "${this.opts.admin}" holds — tried again at the next start: ${(err as Error).message}`); + if (this.retireFile) { + mkdirSync(this.opts.stateDir!, { recursive: true, mode: 0o700 }); + writeFileSync(this.retireFile, `${new Date().toISOString()}\n`, { mode: 0o600 }); + } + this.log(`FAILED to delete the token(s) named "${TOKEN_NAME}" the admin account "${this.opts.admin}" holds — tried again at the next start: ${(err as Error).message}`); } } - private async doMint(): Promise { + /** + * Mint `-` (the generation this own-put makes), write it through own-put, and only then delete + * at the forge, by id, the token it replaces: `replaced`'s by its name, or at the first mint the tokens under the + * account's old fixed name (H-A-422 (2), H-A-430 (1)). + */ + private async doMint(replaced: VaultToken | null): Promise { const password = this.password(); const admin = this.adminCall(password); - const tokensOf = (account: string) => `/users/${encodeURIComponent(account)}/tokens`; - const call = (method: string, path = "", body?: unknown) => admin(method, tokensOf(this.account) + path, body); + const account = this.opts.account; + const tokens = `/users/${encodeURIComponent(account)}/tokens`; + const generation = (replaced?.generation ?? 0) + 1; + const name = mintName(account, generation); - if (this.account !== this.opts.admin) { - // The tools' account and its team first (novox/hq ADR 0365 §2): a failure here fails the mint, tried again - // at the next call. - const me = await admin("GET", "/user"); - if (me.status === 401 || me.status === 403) throw new AdminRefused(this.opts.admin, me.status); - await this.opts.setUp?.(password); - } + // The account and its team first (novox/hq ADR 0365 §2): a failure here fails the mint, tried again at the next call. + const me = await admin("GET", "/user"); + if (me.status === 401 || me.status === 403) throw new AdminRefused(this.opts.admin, me.status); + await this.opts.setUp?.(password); - let res = await call("POST", "", { name: this.name, scopes: this.scopes }); + let res = await admin("POST", tokens, { name, scopes: this.scopes }); if (res.status === 401 || res.status === 403) throw new AdminRefused(this.opts.admin, res.status); if (res.status === 400 || res.status === 422) { - // The forge still holds a token by this name whose value we no longer have — the kept file - // went while the forge's data stayed, or two processes once minted at once and left two. It is - // ours to replace: find every one by this name in the account's list and delete each by its id - // (gitea refuses a delete by a name held twice: "multiple matches for token name"), then mint. - await this.dropNamed(admin, tokensOf(this.account), this.account, true); - res = await call("POST", "", { name: this.name, scopes: this.scopes }); + // A mint of this generation whose own-put never landed left its token at the forge, unused: deleted by its id + // (gitea refuses a delete by a name held twice), then minted again. + await this.dropNamed(admin, tokens, account, name, true); + res = await admin("POST", tokens, { name, scopes: this.scopes }); } if (res.status !== 201 && res.status !== 200) { - throw new Error(`Gitea POST /users/${this.account}/tokens: ${res.status} ${detail(res.body)}`); + throw new Error(`Gitea POST /users/${account}/tokens: ${res.status} ${detail(res.body)}`); } const token = typeof res.body?.sha1 === "string" ? res.body.sha1 : null; - if (!token) throw new Error(`Gitea POST /users/${this.account}/tokens: ${res.status} but no token in the reply`); + if (!token) throw new Error(`Gitea POST /users/${account}/tokens: ${res.status} but no token in the reply`); - this.keep(token); - this.held = token; - this.log(`minted a token for "${this.account}" (${this.scopes.join(", ")}), kept at ${this.opts.file}`); - // Only now, with the account's own token kept, does the admin's old one go. + const kept = await this.opts.vault.put(account, token, this.scopes); + if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`); + this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() }; + this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`); + + // Only now, with the new token kept, does the one it replaces go. + const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName; + try { + const dropped = await this.dropNamed(admin, tokens, account, gone); + if (dropped > 0) this.log(`deleted ${dropped} token(s) named "${gone}" "${account}" held: ${name} replaces them`); + } catch (err) { + this.log(`FAILED to delete the token "${gone}" ${name} replaces; the forge holds both until the next mint — ${(err as Error).message}`); + } await this.retireAdmin(admin); return token; } - /** - * Delete every token by this name an account holds, each by its id (gitea refuses a delete by a name held twice: - * "multiple matches for token name"); answers how many. `replacing` says the line for a mint that found its name - * taken. - */ - private async dropNamed(admin: AdminCall, tokens: string, account: string, replacing = false): Promise { + /** Delete every token named `name` an account holds, each by its id; answers how many. */ + private async dropNamed(admin: AdminCall, tokens: string, account: string, name: string, replacing = false): Promise { const held: number[] = []; for (let page = 1; page <= 100; page++) { const listed = await admin("GET", `${tokens}?page=${page}&limit=50`); @@ -453,23 +550,59 @@ export class MintedToken implements TokenSource { throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`); } if (listed.body.length === 0) break; - for (const t of listed.body) if (t?.name === this.name && typeof t.id === "number") held.push(t.id); - } - if (replacing) { - this.log(held.length === 1 - ? `the forge already holds a token named "${this.name}" — replacing it` - : `the forge holds ${held.length} tokens named "${this.name}" — deleting each by its id and minting one`); + for (const t of listed.body) if (t?.name === name && typeof t.id === "number") held.push(t.id); } + if (replacing) this.log(`the forge already holds ${held.length} token(s) named "${name}" — deleting each by its id and minting one`); for (const id of held) { const dropped = await admin("DELETE", `${tokens}/${id}`); if (dropped.status !== 204 && dropped.status !== 404) { - throw new Error(`Gitea DELETE /users/${account}/tokens/${id} (named ${this.name}): ${dropped.status} ${detail(dropped.body)}`); + throw new Error(`Gitea DELETE /users/${account}/tokens/${id} (named ${name}): ${dropped.status} ${detail(dropped.body)}`); } } return held.length; } } +/** The admin login and password file the manifest hands the runtime, or an error naming what is missing. */ +export function adminFromEnv(env: NodeJS.ProcessEnv, missingWords: string): { admin: string; passwordFile: string } { + const admin = env.MESH_GITEA_ADMIN_USER; + const passwordFile = env.MESH_GITEA_ADMIN_PASSWORD_FILE; + const missing = [admin ? null : "MESH_GITEA_ADMIN_USER", passwordFile ? null : "MESH_GITEA_ADMIN_PASSWORD_FILE"] + .filter((v): v is string => v !== null); + if (missing.length) throw new Error(`${missingWords} ${missing.join(", ")}`); + return { admin: admin!, passwordFile: passwordFile! }; +} + +// One vault and one lease a process, shared by both accounts' sources: one key and one watch. +let vaultOnce: TokenVault | undefined; +let leaseOnce: MintLease | undefined; +function sharedVault(): TokenVault { + return (vaultOnce ??= vaultOverBus()); +} +function sharedLease(): MintLease { + return (leaseOnce ??= leaseOverState()); +} + +/** The tool forge_token_lease's reading (§808): the lease's holder and since when, and each account's token age, read + * from the vault's `changed-at`; never the token. */ +export async function tokenLease(vault: TokenVault, lease: MintLease, accounts: readonly string[], now: Date = new Date()) { + const held = await lease.read(); + const out: { account: string; vault: string; generation?: number; "changed-at"?: string; "age-seconds"?: number; held: boolean }[] = []; + for (const account of accounts) { + const t = await vault.get(account); + out.push(t === null ? { account, vault: vaultName(account), held: false } : { + account, vault: vaultName(account), held: true, generation: t.generation, "changed-at": t.changedAt, + "age-seconds": Math.max(0, Math.floor((now.getTime() - Date.parse(t.changedAt)) / 1000)), + }); + } + return { lease: held === null ? { held: false } : { held: true, holder: held.holder, since: held.since }, tokens: out }; +} + +/** The vault and the lease this process mints through, for the tool forge_token_lease. */ +export function processVaultAndLease(): { vault: TokenVault; lease: MintLease } { + return { vault: sharedVault(), lease: sharedLease() }; +} + function detail(body: unknown): string { return typeof body === "string" ? body : JSON.stringify(body); } diff --git a/modules/gitea/tools/calls.ts b/modules/gitea/tools/calls.ts new file mode 100644 index 000000000..06f0789fb --- /dev/null +++ b/modules/gitea/tools/calls.ts @@ -0,0 +1,126 @@ +// The tools of the forge module's merge calls (novox/hq design 47 H §766, §767): forge_calls reads the calls, newest first, +// with each member's state; forge_call_say_again says a call's merge-called again; forge_partial_clear clears a call's +// merge-partial by hand. Each act is written in the hand-act log before it is done. + +import type { ToolDefinition } from "@novox/mesh-sdk/tools"; +import { callerOf } from "@novox/mesh-sdk/callers"; +import type { HandAct } from "@novox/mesh-sdk/views"; +import type { Partials } from "../partials.js"; +import { sayCall, type Calls, type Say } from "../calls.js"; +import type { GiteaClient } from "../client.js"; +import { repositoryOf } from "../seat.js"; + +const word = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); + +export function callTools(calls: Calls, partials: Partials, say: Say, acts: (act: HandAct) => Promise): ToolDefinition[] { + return [ + { + name: "forge_calls", + description: "The merge calls the forge module keeps (its state calls), newest first: each call's by, account, when, whether its merge-called " + + "was said, and each member with its base, head and state (judged, merged with its commit, or refused with why) (design 47 H §766).", + input: { type: "object", properties: { call: { type: "string", description: "only this merge call" } } }, + run: async (args: Record) => { + const only = word(args.call); + const all = await calls.all(); + return { calls: only ? all.filter((c) => c.call === only) : all }; + }, + }, + { + name: "forge_call_say_again", + description: "Says one merge call's merge-called again, for what it landed, with why: a gate that missed it takes the call in. " + + "Written in the hand-act log first (design 47 H §766).", + input: { type: "object", required: ["call", "why"], properties: { + call: { type: "string", description: "the merge call, 16 lowercase hex characters" }, + why: { type: "string", description: "why it is said again, in plain words" } } }, + run: async (args: Record) => { + const call = word(args.call), why = word(args.why); + if (!/^[0-9a-f]{16}$/.test(call) || !why) throw new Error("forge_call_say_again names the call (16 lowercase hex characters) and why"); + const kept = await calls.get(call); + if (!kept) throw new Error(`the forge module keeps no merge call ${call}`); + const by = callerOf(args); + try { + await acts({ what: `said the merge-called of the merge call ${call} again`, why: `${why} (${by})`, cause: "merge-called-said-again", verb: "forge_call_say_again" }); + } catch (err) { + throw new Error(`the hand act was not recorded, so nothing was said: ${err instanceof Error ? err.message : String(err)}`); + } + const said = await sayCall(kept, say); + if (said && !kept.said) { + const { call: _c, ...value } = kept; + await calls.put(call, { ...value, said: true }); + } + return { call, said, why, by, ...(said ? {} : { "said-none": "the call landed no member, so it says no merge-called" }) }; + }, + }, + { + name: "forge_partial_clear", + description: "Clears the finding merge-partial of one merge call (a call the forge refused a member of after every member was judged), " + + "with why, when its refused members are not to be merged. Written in the hand-act log first (design 47 H §767).", + input: { type: "object", required: ["call", "why"], properties: { + call: { type: "string", description: "the merge call, 16 lowercase hex characters" }, + why: { type: "string", description: "why it is cleared, in plain words" } } }, + run: async (args: Record) => { + const call = word(args.call), why = word(args.why); + if (!/^[0-9a-f]{16}$/.test(call) || !why) throw new Error("forge_partial_clear names the call (16 lowercase hex characters) and why"); + const by = callerOf(args); + try { + await acts({ what: `cleared the merge-partial of the merge call ${call}`, why: `${why} (${by})`, cause: "merge-partial-cleared", verb: "forge_partial_clear" }); + } catch (err) { + throw new Error(`the hand act was not recorded, so nothing was cleared: ${err instanceof Error ? err.message : String(err)}`); + } + return { call, cleared: await partials.clear(call), why, by }; + }, + }, + ]; +} + +/** The most a read tool answers (design 47 H2 §811). */ +export const ANSWER_CAP_BYTES = 768 * 1024; + +/** + * forge_merged (design 47 H2 §812, §811; H-A-402): a repository's merged pull requests by number, from `from` to `to` + * inclusive, each read from the forge one by one (the forge lists none by number), with its merge commit, when it was + * merged, and the merge call that made it when a kept call names it merged. A number the forge does not hold, or a pull + * request not merged, is left out. At most 768 KB: past it `capped`, with `cursor` the next number to give as `from`. + */ +export function mergedTool(forge: Pick, calls: Pick): ToolDefinition { + return { + name: "forge_merged", + description: "A repository's merged pull requests by number, from..to inclusive: each with its merge commit, when it was merged, and " + + "the merge call that made it (none when it was merged outside a merge call). At most 768 KB: capped, with the cursor to give as from " + + "(design 47 H2 §812).", + input: { type: "object", required: ["repository", "from", "to"], properties: { + repository: { type: "string", description: "the repository, /" }, + from: { type: "integer", description: "the first pull request number" }, + to: { type: "integer", description: "the last pull request number" } } }, + run: async (args: Record) => { + const { owner, repo, full } = repositoryOf(args.repository); + const from = Number(args.from), to = Number(args.to); + if (!Number.isInteger(from) || from < 1 || !Number.isInteger(to) || to < from) { + throw new Error("forge_merged names from and to, pull request numbers from 1, to not below from"); + } + const madeBy = new Map(); + for (const c of await calls.all()) { + for (const m of c.members) if (m.repository === full && m.state === "merged") madeBy.set(m.number, c.call); + } + const merged: { number: number; "merge-commit": string; "merged-at"?: string; call?: string }[] = []; + let size = 0; + for (let n = from; n <= to; n++) { + let p; + try { + p = await forge.getPullRequest(owner, repo, n); + } catch (err) { + if (/: 404 /.test(err instanceof Error ? err.message : "")) continue; + throw err; + } + if (!p.merged || !p.merge_commit_sha) continue; + const row = { number: n, "merge-commit": p.merge_commit_sha, ...(p.merged_at ? { "merged-at": p.merged_at } : {}), + ...(madeBy.has(n) ? { call: madeBy.get(n) } : {}) }; + const rowSize = JSON.stringify(row).length + 1; + if (size + rowSize > ANSWER_CAP_BYTES) return { repository: full, from, to, total: to - from + 1, merged, capped: true, cursor: n }; + size += rowSize; + merged.push(row); + } + return { repository: full, from, to, total: to - from + 1, merged }; + }, + }; +} diff --git a/modules/gitea/tools/tokenlease.ts b/modules/gitea/tools/tokenlease.ts new file mode 100644 index 000000000..fc8a4f40f --- /dev/null +++ b/modules/gitea/tools/tokenlease.ts @@ -0,0 +1,16 @@ +// The tool forge_token_lease (design 47 H2 §808, the tools table): the mint lease's holder and since when, and each +// account's token age, read from the vault's `changed-at`; never the token. + +import type { ToolDefinition } from "@novox/mesh-sdk/tools"; +import { tokenLease, type MintLease, type TokenVault } from "../token.js"; + +export function tokenLeaseTool(vault: TokenVault, lease: MintLease, accounts: readonly string[], now: () => Date = () => new Date()): ToolDefinition { + return { + name: "forge_token_lease", + description: "The forge token's mint lease and each account's token age (design 47 H2 §808): who holds the lease `mint` in the " + + "state token-lease and since when, and for each account (" + accounts.join(", ") + ") the vault's generation of its token " + + "and when it changed, never the token itself.", + input: { type: "object", properties: {} }, + run: async () => tokenLease(vault, lease, accounts, now()), + }; +} diff --git a/modules/gitea/trunk.ts b/modules/gitea/trunk.ts deleted file mode 100644 index c1e2d98da..000000000 --- a/modules/gitea/trunk.ts +++ /dev/null @@ -1,211 +0,0 @@ -// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341). -// -// The build seat checks a pull request's head merged into its trunk's head at that moment — the verdict's trunk -// commit — and the verdict names both: "head 1a2b3c4d5e6f merged into trunk 7a8b9c0d1e2f", in both statuses' -// descriptions. When the trunk moves, every open pull request's verdict into it is out of date: -// -// - **the forge's holder** (index.ts) hears the move on its own — it reads each trunk's head on every pass that -// looks at the repository, never through mesh-delivery (ADR 0239 §36) — and sets mesh/merge-gate and -// mesh/repo-check on the head of every open pull request into that trunk back to pending, with the reason. -// Nothing is run for it: a recheck, a new head, or the merge tool asks the check again; -// - **the merge tool** (tools/index.ts) compares the trunk commit the head's verdict names with the trunk's head at -// the moment it is asked, merges nothing when they differ, asks the head's check once — the same announcement a -// new head makes — and never merges by itself after. -// -// Since issue 1301 (ADR 0447 §4) a main that requires mesh/check is the checker's: its line names the trunk commit it judged -// ("pass on "), the checker sets it out of date when the trunk moves, and the merge tool refuses a verdict -// of another trunk and asks nothing. The two statuses above are kept only where a base still requires them (a revert, -// pulls.ts maintained). -// -// Pure functions and two small files of the module's own state, so this is tested without a forge. - -import type { CommitStatus, GiteaClient, GiteaPull, HeadCheck } from "./client.js"; -import { CHECK_CONTEXT, WAITS_FOR_COMPOSED, maintained, requiredOf } from "./pulls.js"; - -/** A commit as a verdict names it: its first twelve characters. */ -export function twelve(sha: string | undefined): string { - return String(sha ?? "").slice(0, 12).toLowerCase(); -} - -/** Whether two commits are one, however either is abbreviated (seven characters at least). */ -export function sameCommit(a: string | undefined, b: string | undefined): boolean { - const x = String(a ?? "").toLowerCase(), y = String(b ?? "").toLowerCase(); - if (x.length < 7 || y.length < 7) return false; - return x.length <= y.length ? y.startsWith(x) : x.startsWith(y); -} - -/** What a verdict judged, as both statuses' descriptions begin (ADR 0323 §3). */ -export function judgedWords(head: string, trunk: string): string { - return `head ${twelve(head)} merged into trunk ${twelve(trunk)}`; -} - -/** The trunk commit a merge check's status names: the one its verdict judged ("merged into trunk …"), or, for a - * verdict put out of date, the one it had judged ("judged against trunk …"). Undefined when it names none, as a - * verdict of a build seat from before ADR 0323 does. */ -export function trunkNamed(description: string | undefined): string | undefined { - const m = /(?:merged into|judged against) trunk ([0-9a-f]{7,64})\b/i.exec(description ?? "") - // The checker's mesh/check line (ADR 0447 §3): " on ". - ?? /\b[0-9a-f]{12} on ([0-9a-f]{12})\b/i.exec(description ?? ""); - return m ? m[1].toLowerCase() : undefined; -} - -/** A verdict out of date, as its statuses say it (ADR 0323 §4). */ -export function outOfDateWords(judged: string | undefined, now: string): string { - const was = judged ? `judged against trunk ${twelve(judged)}` : "judged against a trunk it does not name"; - return `out of date: ${was}, the trunk is now ${twelve(now)}; judged again on a recheck or when it is merged`; -} - -/** Whether a pending gate says a check of the head is asked and not yet answered: waiting in the build queue, - * building on a machine (gate.ts), or asked again by a recheck (mesh-delivery). Such a check is not asked again. */ -export function checkOnItsWay(gate: HeadCheck | undefined): boolean { - if (!gate || gate.state !== "pending") return false; - const d = gate.description ?? ""; - return d.startsWith("waiting in the build queue") || d.startsWith("building on ") || d.startsWith("checking again"); -} - -/** Whether a gate says it waits for its group's composed check. */ -export function waitsForComposed(gate: HeadCheck | undefined): boolean { - return !!gate && gate.state === "pending" && (gate.description ?? "").startsWith(WAITS_FOR_COMPOSED); -} - -/** - * The statuses a trunk's move puts back to pending on one open pull request's head, from what the forge holds on it - * now: none when it has no merge check yet, when a check is pending (on its way, or already out of date — its - * verdict is weighed against the trunk when it lands), or when its verdict judged the trunk's head. Otherwise the - * gate, and the repository's own check when the head has one — a pending repo-check a verdict will not set would - * stand for ever (novox/hq issue 305's rule). - */ -export function outOfDateStatuses(checks: Record, trunkHead: string, required?: string[]): CommitStatus[] { - // Only the statuses the base still requires (issue 1301): the first of them the head holds judges. - const kept = maintained(required).filter((c) => checks[c]); - const judge = kept.length ? checks[kept[0]] : undefined; - if (!judge || judge.state === "pending") return []; - const judged = trunkNamed(judge.description); - if (judged && sameCommit(judged, trunkHead)) return []; - const description = outOfDateWords(judged, trunkHead); - return kept.map((context) => ({ state: "pending" as const, context, description })); -} - -/** Where the merge tool stands with a head's verdict and the trunk's head (ADR 0323 §5). */ -export interface VerdictAtTrunk { - /** The verdict judged the trunk's head: the required statuses decide, as before. */ - current: boolean; - /** A check of the head is asked and not yet answered: nothing is asked again. */ - onItsWay: boolean; - /** The trunk commit the verdict names, when it names one. */ - judged?: string; -} - -export function verdictAtTrunk(checks: Record, trunkHead: string, context = CHECK_CONTEXT): VerdictAtTrunk { - const gate = checks[context]; - const judged = trunkNamed(gate?.description); - if (checkOnItsWay(gate)) return { current: false, onItsWay: true, judged }; - return { current: !!gate && gate.state !== "pending" && !!judged && sameCommit(judged, trunkHead), onItsWay: false, judged }; -} - -/** The pending words the merge tool's ask of a check is said with: in the build queue from now, as an announced head's. */ -export function askedWords(at: Date, trunkHead: string): string { - const two = (n: number) => String(n).padStart(2, "0"); - return `waiting in the build queue since ${two(at.getHours())}:${two(at.getMinutes())}: asked by the merge tool ` + - `against trunk ${twelve(trunkHead)}`; -} - -// --- a trunk's move, weighed -------------------------------------------------------------------------------------- - -/** What weighing a trunk's move reads of the forge. */ -export interface TrunkForge { - listOpenPulls(owner: string, repo: string): Promise; - branchHead(owner: string, repo: string, branch: string): Promise; - /** The rule the forge applies to a branch: which of the controller's statuses are kept there (issue 1301). Not given, - * or not read: both, as before. */ - appliedProtection?(owner: string, repo: string, branch: string): Promise<{ enable_status_check?: boolean; status_check_contexts?: string[] | null } | null>; -} - -/** What it writes with: the merge check's one writer (gate.ts), which decides in the head's own turn. */ -export interface OutOfDateWriter { - outOfDate(owner: string, repo: string, sha: string, - decide: (checks: Record) => CommitStatus[] | Promise, target?: string): Promise; -} - -/** - * Every trunk of one repository that an open pull request merges into, read; for one that moved since it was last read - * (`trunks`, by `owner/repo:branch`, which this keeps current), the merge check of every open pull request into it put - * out of date (ADR 0323 §4). A trunk first seen is recorded as it is and nothing is put out of date. Bounded however - * many are open: one listing of the open pull requests (paged), one read of each trunk, then per open pull request into - * a trunk that moved one read and at most two writes, one at a time. A trunk that could not be weighed whole is not - * recorded, so the next pass weighs it again. Answers whether the record changed. `moved` is told of each base that moved, for the siblings whose base it is. - */ -export async function weighTrunks(forge: TrunkForge, gates: OutOfDateWriter, trunks: Record, owner: string, - name: string, moved?: (base: string) => Promise): Promise { - let changed = false; - try { - const open = (await forge.listOpenPulls(owner, name)).filter((p) => p.state === "open" && !!p.head_sha && !!p.base); - for (const base of new Set(open.map((p) => String(p.base)))) { - const key = `${owner}/${name}:${base}`.toLowerCase(); - const head = await forge.branchHead(owner, name, base); - const before = trunks[key]; - if (before && sameCommit(before, head)) continue; - if (before) { - let put = 0; - const required = forge.appliedProtection - ? requiredOf(await forge.appliedProtection(owner, name, base).catch(() => undefined)) : undefined; - for (const pull of open.filter((p) => p.base === base)) { - // The trunk is read again in the head's own turn: a verdict judged against a head newer than the pass's first - // read — the trunk moved again meanwhile, and a check answered — is not put out of date. - const written = await gates.outOfDate(owner, name, String(pull.head_sha), - async (checks) => outOfDateStatuses(checks, await forge.branchHead(owner, name, base), required), pull.html_url || undefined); - if (written.length) put++; - } - console.log(`[gitea] ${owner}/${name}'s ${base} moved from ${twelve(before)} to ${twelve(head)}: ${put} open pull ` + - `request(s) into it put out of date, nothing run (novox/hq ADR 0323)`); - // A verdict that read a pull request into this trunk as a sibling is out of date by its move too (ADR 0382 §5). - if (moved) await moved(base); - } - trunks[key] = head; - changed = true; - } - } catch (err) { - console.error(`[gitea] ${owner}/${name}: whether a trunk moved could not be weighed, so it is weighed again on the next ` + - `pass — ${err instanceof Error ? err.message : err}`); - } - return changed; -} - -// --- the announcement of a head, shared by the watcher and the merge tool --------------------------------------- - -/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be - * 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */ -export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined, - pull: GiteaPull): Promise> { - const files = await client.listPullFiles(owner, name, pull.number); - const head = String(pull.head_sha); - // What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which - // changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as - // touching everything built from the repository. - let moduleDirs: string[] | null = null; - try { - if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths); - } catch (err) { - console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`); - } - // The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against - // (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none. - const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined; - return { - owner, - repo: name, - number: pull.number, - ...(baseSHA ? { base_sha: baseSHA } : {}), - title: pull.title, - body: pull.body, - base: pull.base, - head: pull.head, - head_sha: pull.head_sha, - clone_url: cloneURL, - html_url: pull.html_url, - paths: files.paths, - paths_truncated: files.truncated, - removed: files.removed, - ...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}), - }; -} diff --git a/modules/gitea/updated.ts b/modules/gitea/updated.ts new file mode 100644 index 000000000..8ed934da8 --- /dev/null +++ b/modules/gitea/updated.ts @@ -0,0 +1,42 @@ +// **A pull request's new head is said as the seat git's pull.updated** (novox/hq design 47 H §764; H-A-100): from the forge's +// event of an opened, pushed, reopened or retargeted pull request alone; nothing polls for heads and no merge check is +// asked or written (the merge-check machinery went with milestone H). + +import type { GiteaClient, GiteaPull } from "./client.js"; + +/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be + * 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */ +export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined, + pull: GiteaPull): Promise> { + const files = await client.listPullFiles(owner, name, pull.number); + const head = String(pull.head_sha); + // What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which + // changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as + // touching everything built from the repository. + let moduleDirs: string[] | null = null; + try { + if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths); + } catch (err) { + console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`); + } + // The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against + // (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none. + const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined; + return { + owner, + repo: name, + number: pull.number, + ...(baseSHA ? { base_sha: baseSHA } : {}), + title: pull.title, + body: pull.body, + base: pull.base, + head: pull.head, + head_sha: pull.head_sha, + clone_url: cloneURL, + html_url: pull.html_url, + paths: files.paths, + paths_truncated: files.truncated, + removed: files.removed, + ...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}), + }; +} diff --git a/modules/gitea/watch.ts b/modules/gitea/watch.ts index 7dc1f135e..dc0f97468 100644 --- a/modules/gitea/watch.ts +++ b/modules/gitea/watch.ts @@ -1,29 +1,24 @@ // What the forge's events ask of the announcer, and the one pass at a start (issue 1422, notes 10 and 11). Nothing polls the -// forge: a head or merge is announced when its event is heard, and a pass over every repository runs once when the module -// starts and again when the receiver is listening, so what happened while it was down is announced too. +// forge for heads: a pull request's new head is said as pull.updated when its event is heard, a merge or a close by its +// event and by the pass over every repository's merges at the start (design 47 H §764; H-A-100). // // Apart from index.ts, which has side effects at import, so these are tested with the announcers injected. -import type { GiteaPull, GiteaRepo } from "./client.js"; -import type { Announced } from "./pulls.js"; -import { headKey, headsToAnnounce } from "./pulls.js"; import type { ForgeEvent } from "./webhook.js"; export interface ActDeps { getRepo(owner: string, repo: string): Promise; getPull(owner: string, repo: string, number: number): Promise

; - announceHead(repo: R, pull: P): Promise; + announceUpdated(repo: R, pull: P): Promise; announceMerge(repo: R, pull: P): Promise; announceClosed(repo: R, pull: P): Promise; - siblingMoves(full: string, number: number): Promise; } const HEAD_EVENTS = ["forge.pull-request.opened", "forge.pull-request.synchronized", "forge.pull-request.reopened"]; /** - * What the forge's event asks of the announcer at once: a new head is announced, a merge, a close without a merge, and a - * pull request retargeted (an edit: the head is announced into the base it now has — the base is in the head's key, so an - * edit that changed nothing about the base announces nothing). + * What the forge's event asks of the announcer at once: a new head is said, a merge, a close without a merge, and a pull + * request retargeted (an edit: the head is said into the base it now has). */ export async function actOn(event: ForgeEvent, d: ActDeps): Promise { const b = event.body as { owner?: string; repo?: string; number?: number; merged?: boolean }; @@ -37,51 +32,8 @@ export async function actOn(event: ForgeEvent, d: ActDeps): Promise< const [repo, pull] = await Promise.all([d.getRepo(b.owner, b.repo), d.getPull(b.owner, b.repo, b.number)]); if (closed) { await d.announceClosed(repo, pull); - await d.siblingMoves(`${b.owner}/${b.repo}`, b.number); return; } - if (head && pull.state === "open") await d.announceHead(repo, pull); + if (head && pull.state === "open") await d.announceUpdated(repo, pull); if (merged) await d.announceMerge(repo, pull); } - -/** - * The one pass at a start, and its retry: run now; if it fails, say so and run again after `retryMs`, until one pass has - * ended. A retry of a failed pass, never a poll: after a pass has ended nothing is scheduled. - */ -export function startPass(run: () => Promise, opts: { retryMs: number; log?: (l: string) => void }): Promise { - const log = opts.log ?? ((l) => console.error(`[gitea] ${l}`)); - return run().catch((err) => { - log(`the pass over every repository failed, asked again in ${opts.retryMs / 1000} s — ${err instanceof Error ? err.message : err}`); - return new Promise((resolve) => setTimeout(() => resolve(startPass(run, opts)), opts.retryMs)); - }); -} - -export interface HeadDeps { - /** Whether the forge shows a merge check of the head: only an announced head has one. */ - alreadyChecked(pull: GiteaPull): Promise; - /** Announce it; true when it was this call that announced it (not an event before it). */ - announceHead(pull: GiteaPull): Promise; - /** Told of a head this pass announced that no event had. */ - missed(what: string): void; -} - -/** - * The heads of one repository's open pull requests a pass announces. A head is announced when it is new and fresh (moved in - * the last day); at the first pass after a start (`primed` false) one the forge shows a merge check of was announced - * already, and is only remembered. - */ -export async function announceNewHeads(full: string, open: GiteaPull[], heads: Announced, primed: boolean, dayAgo: string, d: HeadDeps): Promise { - for (const pull of headsToAnnounce(full, open, heads)) { - const key = headKey(full, pull.number, pull.base); - const fresh = primed || (!!pull.updated_at && pull.updated_at > dayAgo); - if (fresh && !primed && await d.alreadyChecked(pull)) { - heads[key] = String(pull.head_sha); - continue; - } - if (fresh) { - if (await d.announceHead(pull)) d.missed(`${key} at ${String(pull.head_sha).slice(0, 8)}`); - } else heads[key] = String(pull.head_sha); - } -} - -export type { GiteaRepo }; diff --git a/modules/gitlab/module.json b/modules/gitlab/module.json index 960832669..7bded31ca 100644 --- a/modules/gitlab/module.json +++ b/modules/gitlab/module.json @@ -1,6 +1,7 @@ { "module": "gitlab", "version": "0.1", + "class": "leaf", "own-secrets": { "token": "${dir:state}/token" }, diff --git a/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_helpers_test.go b/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_helpers_test.go index fb992951b..b121bfa63 100644 --- a/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_helpers_test.go +++ b/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_helpers_test.go @@ -1,64 +1,19 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Items []item `json:"items"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest. -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} - // shell is the code the module adds to a shell's or the session's start, read from the templates of its items of // the collections shell::, in the order they are declared. -func (m manifest) shell(t *testing.T) []shellCode { +func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode { t.Helper() - var out []shellCode + var out []catalogue.ShellCode for _, it := range m.Items { parts := strings.Split(it.Collection, ":") if len(parts) != 3 || parts[0] != "shell" { @@ -68,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode { if err != nil { t.Fatal(err) } - out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)}) + out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)}) } return out } // environmentOf is the variables the module sets, read from the templates of its items of the environment. -func (m manifest) environmentOf(t *testing.T) *environment { +func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment { t.Helper() - var env *environment + var env *catalogue.Environment for _, it := range m.Items { if it.Collection != "environment" || it.Attributes["kind"] != "variable" { continue @@ -86,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment { t.Fatal(err) } if env == nil { - env = &environment{Variables: map[string]string{}} + env = &catalogue.Environment{Variables: map[string]string{}} } env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n") } return env } -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - m.Environment = m.environmentOf(t) - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -120,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -136,9 +75,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -158,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -167,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -180,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -195,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -237,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } diff --git a/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_test.go b/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_test.go index 25f7b3f67..81910f708 100644 --- a/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_test.go +++ b/modules/gnome-keyring/cmd/gnome-keyring-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // gnome-keyring's shape (novox/hq ADR 0208, ADR 0102): it claims node-secret-service, writes its PAM @@ -11,31 +15,47 @@ import ( // of its own: PAM and D-Bus do. func TestItClaimsTheSecretServiceSeat(t *testing.T) { - m := readManifest(t) - if m.Module != "gnome-keyring" || m.Seats != nil || m.Requires != nil { - t.Fatalf("module %q, seats %v, requires %v", m.Module, m.Seats, m.Requires) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-secret-service", Scope: "node"}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "gnome-keyring" || m.DefinesSeats != nil || m.Requires != nil { + t.Fatalf("module %q, seats %v, requires %v", m.Module, m.DefinesSeats, m.Requires) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-secret-service", Scope: "node"}}) { t.Fatalf("claims: %+v", m.Claims) } - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for id, want := range map[string]struct{ path, source string }{ "pam-login": {"/etc/pam.d/login", "files/pam/login"}, "pam-passwd": {"/etc/pam.d/passwd", "files/pam/passwd"}, } { - m.fromTemplate(t, id, want.source) - r := m.resource(t, id) + fromTemplate(t, m, id, want.source) + r := resource(t, m, id) if r["path"] != want.path || r["into"] != "block" || r["at"] != "end" || r["owner"] != nil { t.Errorf("%s: %v", id, r) } } - login := m.text(t, "pam-login") + login := templateText(t, m, "pam-login") if !strings.Contains(login, "\nauth optional pam_gnome_keyring.so\n") || !strings.Contains(login, "\nsession optional pam_gnome_keyring.so auto_start\n") { t.Fatalf("%s", login) @@ -43,27 +63,52 @@ func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) { } func TestItStartsNoDaemonAndOnlyNamesTheAgentsSocket(t *testing.T) { - m := readManifest(t) - if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "first" { - t.Fatalf("%+v", m.shell(t)) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - code := m.shell(t)[0].Code + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "first" { + t.Fatalf("%+v", shell(t, m)) + } + code := shell(t, m)[0].Code if strings.Contains(code, "gnome-keyring-daemon") || strings.Contains(code, "--unlock") || !strings.Contains(code, `SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/gcr/ssh"`) { t.Fatalf("%q", code) } - if m.Environment != nil { + if environmentOf(t, m) != nil { t.Fatal("SSH_AUTH_SOCK needs the runtime directory, which ADR 0203 forbids in a value; it is not an environment contribution yet") } } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/gnome-keyring/module.json b/modules/gnome-keyring/module.json index 76ca633c5..a7b663deb 100644 --- a/modules/gnome-keyring/module.json +++ b/modules/gnome-keyring/module.json @@ -1,6 +1,7 @@ { "module": "gnome-keyring", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/go/module.json b/modules/go/module.json index ca0264bd8..10cb723e5 100644 --- a/modules/go/module.json +++ b/modules/go/module.json @@ -1,6 +1,7 @@ { "module": "go", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/grafana/module.json b/modules/grafana/module.json index ce84cc904..8acd7b622 100644 --- a/modules/grafana/module.json +++ b/modules/grafana/module.json @@ -1,6 +1,7 @@ { "module": "grafana", "version": "0.1", + "class": "leaf", "emits": [ "alert.firing" ], diff --git a/modules/hello-web/module.json b/modules/hello-web/module.json index bbe7fd9af..d6cf28b03 100644 --- a/modules/hello-web/module.json +++ b/modules/hello-web/module.json @@ -2,6 +2,7 @@ "module": "hello-web", "slug": "hello", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/home-assistant/module.json b/modules/home-assistant/module.json index f43735649..fad6eec97 100644 --- a/modules/home-assistant/module.json +++ b/modules/home-assistant/module.json @@ -1,6 +1,7 @@ { "module": "home-assistant", "version": "0.1", + "class": "leaf", "slug": "hass", "capabilities": [ "container-runtime" diff --git a/modules/hostname/module.json b/modules/hostname/module.json index 94ec44788..dc9a84014 100644 --- a/modules/hostname/module.json +++ b/modules/hostname/module.json @@ -1,6 +1,7 @@ { "module": "hostname", "version": "0.1", + "class": "core", "claims": [ { "name": "node-hostname", diff --git a/modules/i3/module.json b/modules/i3/module.json index 04a5810b4..315b77deb 100644 --- a/modules/i3/module.json +++ b/modules/i3/module.json @@ -1,6 +1,7 @@ { "module": "i3", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/i3status-rust/cmd/i3status-rust-tools/blocks_test.go b/modules/i3status-rust/cmd/i3status-rust-tools/blocks_test.go index 05c068e28..92b859ca5 100644 --- a/modules/i3status-rust/cmd/i3status-rust-tools/blocks_test.go +++ b/modules/i3status-rust/cmd/i3status-rust-tools/blocks_test.go @@ -5,15 +5,25 @@ import ( "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // The blocks other modules contribute are a collection of text (design 57 L3, novox/hq ADR 0349 clause 13): each // contributor gives its block in i3status-rust's grammar, and the bars place the collection where they want it. func TestEachBarPlacesBothPlacesOnce(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for _, bar := range []string{"bottom", "top"} { - content := m.text(t, bar+"-bar") + content := templateText(t, m, bar+"-bar") for _, place := range []string{"resources", "status"} { ph := "${collected:contribution:node-bar:block:bar=" + bar + ",place=" + place + "}" if strings.Count(content, ph) != 1 { @@ -21,7 +31,7 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) { } } } - bottom := m.text(t, "bottom-bar") + bottom := templateText(t, m, "bottom-bar") resources := strings.Index(bottom, "place=resources") if !(strings.Index(bottom, `block = "memory"`) < resources && resources < strings.Index(bottom, `block = "docker"`)) || !(strings.Index(bottom, `block = "sound"`) < strings.Index(bottom, "place=status") && @@ -31,7 +41,16 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) { } func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) { - bottom := readManifest(t).text(t, "bottom-bar") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + bottom := templateText(t, m, "bottom-bar") if !strings.Contains(bottom, `format = "$icon $mem_used.eng(w:2) ($mem_used_percents.eng(w:2))"`) || strings.Contains(bottom, "mem_total_used") { t.Fatal("the memory block counts the cache as used") @@ -39,9 +58,17 @@ func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) { } func TestABarNamesNoTemplateOfItsOwnForTheBlocksItPlaces(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for _, id := range []string{"top-bar", "bottom-bar"} { - if strings.Contains(m.text(t, id), "${contribution:") { + if strings.Contains(templateText(t, m, id), "${contribution:") { t.Errorf("the %s still places a contribution the old way", id) } } diff --git a/modules/i3status-rust/cmd/i3status-rust-tools/manifest_helpers_test.go b/modules/i3status-rust/cmd/i3status-rust-tools/manifest_helpers_test.go index c33db7ecb..740a42250 100644 --- a/modules/i3status-rust/cmd/i3status-rust-tools/manifest_helpers_test.go +++ b/modules/i3status-rust/cmd/i3status-rust-tools/manifest_helpers_test.go @@ -1,68 +1,19 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Items []item `json:"items"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - // Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here. - Contributions []any `json:"contributions"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` - // How the holder renders each kind its seat receives as data (novox/hq ADR 0255). - Renders map[string]string `json:"renders"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest. -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} - // shell is the code the module adds to a shell's or the session's start, read from the templates of its items of // the collections shell::, in the order they are declared. -func (m manifest) shell(t *testing.T) []shellCode { +func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode { t.Helper() - var out []shellCode + var out []catalogue.ShellCode for _, it := range m.Items { parts := strings.Split(it.Collection, ":") if len(parts) != 3 || parts[0] != "shell" { @@ -72,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode { if err != nil { t.Fatal(err) } - out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)}) + out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)}) } return out } // environmentOf is the variables the module sets, read from the templates of its items of the environment. -func (m manifest) environmentOf(t *testing.T) *environment { +func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment { t.Helper() - var env *environment + var env *catalogue.Environment for _, it := range m.Items { if it.Collection != "environment" || it.Attributes["kind"] != "variable" { continue @@ -90,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment { t.Fatal(err) } if env == nil { - env = &environment{Variables: map[string]string{}} + env = &catalogue.Environment{Variables: map[string]string{}} } env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n") } return env } -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - m.Environment = m.environmentOf(t) - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -124,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -140,9 +75,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -162,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -171,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -184,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -199,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -241,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } @@ -273,7 +208,7 @@ const displaySession = "contribution:node-display-session:config" // i3Lines is what the module contributes to the window manager: the text of its item of the collection // contribution:node-display-session:config (design 57 L3, issue 848). -func (m manifest) i3Lines() string { +func i3Lines(m catalogue.Manifest) string { var out string for _, it := range m.Items { if it.Collection == displaySession { @@ -289,7 +224,7 @@ func (m manifest) i3Lines() string { // i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no // old-form contribution to node-display-session is left. -func (m manifest) i3LinesAreSource(t *testing.T, source string) { +func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) { t.Helper() if len(m.Contributions) != 0 { t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession) @@ -303,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) { if len(templates) != 1 || templates[0] != source { t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source) } - if m.i3Lines() == "" { + if i3Lines(m) == "" { t.Fatalf("the template %s holds no line", source) } } diff --git a/modules/i3status-rust/cmd/i3status-rust-tools/manifest_test.go b/modules/i3status-rust/cmd/i3status-rust-tools/manifest_test.go index e4811c48d..c6745cc7d 100644 --- a/modules/i3status-rust/cmd/i3status-rust-tools/manifest_test.go +++ b/modules/i3status-rust/cmd/i3status-rust-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // i3status-rust's shape (novox/hq ADR 0208): it claims node-bar, requires the X display on its own @@ -12,12 +16,20 @@ import ( // devices. func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } if !m.Moved { t.Fatal("the module is not marked moved") } - if m.Module != "i3status-rust" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + if m.Module != "i3status-rust" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) } if len(m.Claims) != 1 || m.Claims[0].Name != "node-bar" || m.Claims[0].Scope != "node" || len(m.Claims[0].Renders) != 0 { @@ -26,25 +38,41 @@ func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) { if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("requires: %v", m.Requires) } - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestItOwnsItsFilesAsWrittenInTheModule(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for id, src := range map[string]string{ "top-bar": "files/top-bar.toml", "bottom-bar": "files/bottom-bar.toml", "icons": "files/icons/custom-icons.toml", "updates": "files/bin/i3status-updates", "watchdog": "files/bin/i3bar-watchdog", "value": "files/bin/i3status-value", } { - m.fromTemplate(t, id, src) + fromTemplate(t, m, id, src) } } func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testing.T) { - m := readManifest(t) - bottom := m.text(t, "bottom-bar") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + bottom := templateText(t, m, "bottom-bar") for _, never := range []string{`block = "battery"`, `block = "amd_gpu"`, `block = "nvidia_gpu"`, "mac = ", "api_key", "city_id", "openweathermap", "~/scripts/"} { if strings.Contains(bottom, never) { t.Errorf("the bottom bar has %s", never) @@ -53,26 +81,51 @@ func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testin } func TestTheBarsAreAContributionToTheWindowManagerAndTheWatchdogRunsOncePerSession(t *testing.T) { - m := readManifest(t) - m.i3LinesAreSource(t, "files/i3/60-i3status-rust.conf") - c := m.i3Lines() + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + i3LinesAreSource(t, m, "files/i3/60-i3status-rust.conf") + c := i3Lines(m) if strings.Count(c, "bar {") != 2 || !strings.Contains(c, "status_command i3status-rs ~/.config/i3status-rust/bottom-bar.toml") || !strings.Contains(c, "font pango:JetBrainsMono Nerd Font 11") { t.Fatalf("%s", c) } - if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" || - !strings.Contains(m.shell(t)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) { - t.Fatalf("%+v", m.shell(t)) + if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" || + !strings.Contains(shell(t, m)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) { + t.Fatalf("%+v", shell(t, m)) } } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/i3status-rust/module.json b/modules/i3status-rust/module.json index 8e052bf67..4e85779f9 100644 --- a/modules/i3status-rust/module.json +++ b/modules/i3status-rust/module.json @@ -1,6 +1,7 @@ { "module": "i3status-rust", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/icecast/module.json b/modules/icecast/module.json index 052147018..ca6de7876 100644 --- a/modules/icecast/module.json +++ b/modules/icecast/module.json @@ -1,6 +1,7 @@ { "module": "icecast", "version": "0.1", + "class": "leaf", "requires": [ "route", "secret" diff --git a/modules/influxdb/module.json b/modules/influxdb/module.json index 23e0e4b25..80d2f225a 100644 --- a/modules/influxdb/module.json +++ b/modules/influxdb/module.json @@ -1,6 +1,7 @@ { "module": "influxdb", "version": "0.1", + "class": "leaf", "provides": [ { "name": "influxdb-api", diff --git a/modules/invoicing/module.json b/modules/invoicing/module.json index 89ace98a3..f56e75359 100644 --- a/modules/invoicing/module.json +++ b/modules/invoicing/module.json @@ -1,6 +1,7 @@ { "module": "invoicing", "version": "0.1", + "class": "leaf", "slug": "invoice", "capabilities": [ "container-runtime" diff --git a/modules/jira/module.json b/modules/jira/module.json index 81b7e845d..3d48f9f63 100644 --- a/modules/jira/module.json +++ b/modules/jira/module.json @@ -1,6 +1,7 @@ { "module": "jira", "version": "0.1", + "class": "leaf", "own-secrets": { "token": "${dir:state}/token" }, diff --git a/modules/kernel/module.json b/modules/kernel/module.json index d5fd22bc9..97a21caed 100644 --- a/modules/kernel/module.json +++ b/modules/kernel/module.json @@ -1,6 +1,7 @@ { "module": "kernel", "version": "0.1", + "class": "leaf", "capabilities": [ "service-manager" ], diff --git a/modules/keycloak/module.json b/modules/keycloak/module.json index 38f9b0610..cfad61b60 100644 --- a/modules/keycloak/module.json +++ b/modules/keycloak/module.json @@ -1,6 +1,7 @@ { "module": "keycloak", "version": "0.1", + "class": "leaf", "moved": true, "upgrade": { "policy": "record", diff --git a/modules/lab/module.json b/modules/lab/module.json index 4bddf1725..0d2f574e2 100644 --- a/modules/lab/module.json +++ b/modules/lab/module.json @@ -1,6 +1,7 @@ { "module": "lab", "version": "0.1", + "class": "leaf", "moved": true, "capabilities": [ "container-runtime", diff --git a/modules/lemurs/module.json b/modules/lemurs/module.json index 668e94a1f..8c143702d 100644 --- a/modules/lemurs/module.json +++ b/modules/lemurs/module.json @@ -1,6 +1,7 @@ { "module": "lemurs", "version": "0.1", + "class": "core", "capabilities": [ "package-manager", "service-manager", diff --git a/modules/letta/module.json b/modules/letta/module.json index d97ba80cb..fffb0e5ce 100644 --- a/modules/letta/module.json +++ b/modules/letta/module.json @@ -1,6 +1,7 @@ { "module": "letta", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/local-model-consumer/module.json b/modules/local-model-consumer/module.json index 47403651f..cb35bdcad 100644 --- a/modules/local-model-consumer/module.json +++ b/modules/local-model-consumer/module.json @@ -1,6 +1,7 @@ { "module": "local-model-consumer", "version": "0.1", + "class": "leaf", "slug": "local", "requires": [ "model-access" diff --git a/modules/localization/module.json b/modules/localization/module.json index 14d5845e8..dad52ffbf 100644 --- a/modules/localization/module.json +++ b/modules/localization/module.json @@ -1,6 +1,7 @@ { "module": "localization", "version": "0.1", + "class": "leaf", "capabilities": [ "service-manager" ], diff --git a/modules/logrotate/module.json b/modules/logrotate/module.json index 1c41ac39b..4ec39c136 100644 --- a/modules/logrotate/module.json +++ b/modules/logrotate/module.json @@ -1,6 +1,7 @@ { "module": "logrotate", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/mailu/module.json b/modules/mailu/module.json index c1dd44617..f88907ddd 100644 --- a/modules/mailu/module.json +++ b/modules/mailu/module.json @@ -1,6 +1,7 @@ { "module": "mailu", "version": "0.1", + "class": "leaf", "upgrade": { "policy": "record", "why": "people's mail: any change to how its containers are declared recreates them together in one send, and the mail is down for everyone until they are up again — a person chooses the moment (hq ADR 0242, issue 295)" diff --git a/modules/marrytts/module.json b/modules/marrytts/module.json index ddadf075c..916c106f2 100644 --- a/modules/marrytts/module.json +++ b/modules/marrytts/module.json @@ -1,6 +1,7 @@ { "module": "marrytts", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/matrix/module.json b/modules/matrix/module.json index 3c6282545..38ff40b06 100644 --- a/modules/matrix/module.json +++ b/modules/matrix/module.json @@ -1,6 +1,7 @@ { "module": "matrix", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/memory-pressure/module.json b/modules/memory-pressure/module.json index 6fe32ff11..c4fc5ffec 100644 --- a/modules/memory-pressure/module.json +++ b/modules/memory-pressure/module.json @@ -1,6 +1,7 @@ { "module": "memory-pressure", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/mesh-build-go/README.md b/modules/mesh-build-go/README.md index ceee31df6..bd6f2bc30 100644 --- a/modules/mesh-build-go/README.md +++ b/modules/mesh-build-go/README.md @@ -37,7 +37,11 @@ Three read tools answer what the module stored in its own states, without the gu forge-account provision's ssh name, so the account's own ssh files and git rewrite are used) into a workspace of the work directory, then runs `go mod download` and `go mod verify` in every directory with a `go.mod` that does not vendor, with `GOTOOLCHAIN=local`, `GOFLAGS=-mod=mod` and the module's cache directory. Every command runs with an -environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes. +environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes. The fetch downloads in two +passes: each pinned mesh package from the Go package registry seat alone (`GOPROXY=,off`; a version the seat does +not hold fails as `the Go package registry holds no @`, and with no binding of the seat the fetch +refuses: `no Go package registry bound`), then the rest of the build list through Go's public proxy alone, never `direct`; +every other go command runs with `GOPROXY=off` (design 47 H, H-A-494). ## Room to work and the workspace's end @@ -53,11 +57,13 @@ The programs this module builds from a commit and keeps in its cache (composers asks) are read by `build_go_kept` (kind, key, size, last use) and removed by `build_go_kept_drop {kind, key}`; one no ask used for 30 days is swept with the workspaces (issue 1921). -A pin on a pull request's head (issue 1148): when `go mod download` fails on a `git.novox.be/novox/*` pseudo-version, the -fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the workspace's -`pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with `GOPROXY=off`) through a -temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin Go can fetch is left as -it is, a pin on no ref fails naming the module and the commit, and a directory that vendors is never resolved. +A pin on a pull request's head (issue 1148): when the ask pins a mesh package at a commit the Go package registry does not +hold, the fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the +workspace's `pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with +`GOPROXY=off`) through a temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin +on no ref fails naming the module and the commit, and a directory that vendors is never resolved. A go.mod names a mesh +package at the zero version only: one it names at another version is refused before any download (` names +@; a mesh package is required at the zero version`), never placed (design 47 H, H-A-494). The asked versions of the mesh's packages (novox/hq ADR 0573 §2, §4; issue 1585): a fetch given `packages` (a full commit by Go module path, which the builder and the checker fill from the indexer's trunk values or a group's heads) writes each diff --git a/modules/mesh-build-go/cmd/mesh-build-go/announce.go b/modules/mesh-build-go/cmd/mesh-build-go/announce.go index e4145bbf7..605792692 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/announce.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/announce.go @@ -1,7 +1,7 @@ package main // What this module keeps on the bus, announced from its code (novox/hq ADR 0495 §2 §5; issue 1790): every state it -// keeps, each readable by others, since another module reads each today (the builder, the checker and the indexer read toolchains; the builder and the checker read steps; gitea reads keys). A state of its own that it +// keeps, each readable by others, since another module reads each today (the builder and the indexer read toolchains; the builder reads steps; gitea reads keys). A state of its own that it // did not name here is refused at the call (stdio.Keeps). import ( diff --git a/modules/mesh-build-go/cmd/mesh-build-go/archive.go b/modules/mesh-build-go/cmd/mesh-build-go/archive.go index 5957f287c..42d1dd45f 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/archive.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/archive.go @@ -46,9 +46,9 @@ func (m *Module) httpClient() *http.Client { // buildArchive packs one archive artifact of the module in dir: a pinned file when it names a url, else the directory // `from` of the module's tree. -func (m *Module) buildArchive(ctx context.Context, workspace, module, name, dir string, art catalogue.Artifact, keep *sdkstep.KeptFor) (any, error) { +func (m *Module) buildArchive(ctx context.Context, workspace, module, name, dir string, art catalogue.Artifact, version string, keep *sdkstep.KeptFor) (any, error) { if art.URL != "" { - return m.pinnedArchive(ctx, workspace, module, name, art, keep) + return m.pinnedArchive(ctx, workspace, module, name, art, version, keep) } from := strings.Trim(path.Clean("/"+filepath.ToSlash(art.From)), "/") if strings.TrimSpace(art.From) == "" { @@ -80,12 +80,12 @@ func (m *Module) buildArchive(ctx context.Context, workspace, module, name, dir if !within(realDir, realRoot) { return nil, fmt.Errorf("the archive %s is taken from %q, which lies outside the module: it resolves to %s, and the module is %s", art.Name, art.From, realRoot, realDir) } - return m.packInto(ctx, workspace, module, name, art.Name, "archive", root, keep) + return m.packInto(ctx, workspace, module, name, art.Name, "archive", version, root, keep) } // pinnedArchive fetches the file an artifact is pinned to, checks it against the pin, lays it out as the artifact says // (kept whole as `file`, or unpacked from `within`) and packs it. -func (m *Module) pinnedArchive(ctx context.Context, workspace, module, name string, art catalogue.Artifact, keep *sdkstep.KeptFor) (any, error) { +func (m *Module) pinnedArchive(ctx context.Context, workspace, module, name string, art catalogue.Artifact, version string, keep *sdkstep.KeptFor) (any, error) { file, err := m.pinnedFile(ctx, workspace, art) if err != nil { return nil, fmt.Errorf("%s: %w", art.Name, err) @@ -114,7 +114,7 @@ func (m *Module) pinnedArchive(ctx context.Context, workspace, module, name stri } else if err := unpackUpstream(file, laid, art.Within); err != nil { return nil, fmt.Errorf("%s: %s (%s): %w", art.Name, art.URL, art.Version, err) } - return m.packInto(ctx, workspace, module, name, art.Name, "archive", laid, keep) + return m.packInto(ctx, workspace, module, name, art.Name, "archive", version, laid, keep) } // pinnedFile is the path of the pinned file in the workspace: kept from an earlier build when its bytes are still the diff --git a/modules/mesh-build-go/cmd/mesh-build-go/archive_test.go b/modules/mesh-build-go/cmd/mesh-build-go/archive_test.go index e7506cba0..6e2d1e2a7 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/archive_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/archive_test.go @@ -6,6 +6,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "encoding/json" "errors" "io" "net" @@ -305,3 +306,66 @@ func TestAnArchiveOfALinkedModuleDirectoryIsRefused(t *testing.T) { t.Errorf("an archive of outside files was left: %v", entries) } } + +// H-A-371: an archive-only lane of a module with no Go code fetches (its directory chooses no Go module: an empty +// scope, never a refusal) and packs its archive. +func TestAnArchiveOnlyLaneOfAModuleWithNoGoCodeFetchesAndPacks(t *testing.T) { + files := map[string]string{} + fixture := filepath.Join("testdata", "repos", "archive") + err := filepath.Walk(fixture, func(p string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return err + } + body, err := os.ReadFile(p) + rel, _ := filepath.Rel(fixture, p) + files[strings.TrimSuffix(filepath.ToSlash(rel), ".fixture")] = string(body) + return err + }) + if err != nil { + t.Fatal(err) + } + // Another module of the repository holds Go code; the archive module's directory holds none. + f := &fakeStep{gomods: "modules/other/go.mod\n", files: files} + m, states := fetchModule(t, f) + withStore(t, m) + if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-catalog", "commit": commitSHA, "dir": "modules/demo"}); err != nil { + t.Fatal(err) + } + st := states.waitEnd(t) + if st.State != sdkstep.StepPassed { + t.Fatalf("the fetch ended %s: %s", st.State, st.Reason) + } + var fetched FetchResult + if err := json.Unmarshal(st.Result, &fetched); err != nil { + t.Fatal(err) + } + if len(fetched.Modules) != 0 { + t.Errorf("the fetch chose the Go modules %v, want none", fetched.Modules) + } + if b, err := os.ReadFile(filepath.Join(m.Work, fetched.Workspace, scopeMark)); err != nil || len(b) != 0 { + t.Errorf("the scope beside the tree is %q, %v; want the empty scope", b, err) + } + for _, l := range f.lines() { + if strings.HasPrefix(l, "go ") { + t.Errorf("a fetch that chose no Go module ran %s", l) + } + } + for _, tool := range m.Tools(m.StepTools()) { + if tool.Name == "build_go_build" { + if _, err := tool.Run(map[string]any{"workspace": fetched.Workspace, "module": "modules/demo", "artifact": "files"}); err != nil { + t.Fatal(err) + } + } + } + st = states.waitEnd(t) + if st.State != sdkstep.StepPassed { + t.Fatalf("the build ended %s: %s", st.State, st.Reason) + } + var res BuildResult + if err := json.Unmarshal(st.Result, &res); err != nil { + t.Fatal(err) + } + if res.Artifact != "files" || res.Size == 0 || res.Reference == "" || len(archiveOf(t, res)) != res.Size { + t.Errorf("the archive was not packed and published: %+v", res) + } +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/asks.go b/modules/mesh-build-go/cmd/mesh-build-go/asks.go index 395f9193b..28170e413 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/asks.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/asks.go @@ -10,6 +10,7 @@ import ( sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/busstate" ) // **The module pulls its seat's asks** (novox/hq ADR 0525 §2-§6, ADR 0536 §4; issue 1887 A3go). It holds the seat @@ -50,16 +51,35 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps { Lint: m.lintStep, Node: m.Node, SayStep: m.sayStep(), + // A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517, + // H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's). + SayImports: m.sayImports(), + Outputs: m.outputs(), } } +// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with +// SayEvent; nil when the module says no event. +func (m *Module) sayImports() func(seat.ImportsReported) error { + if m.SayEvent == nil { + return nil + } + return steprun.SayImportsOn(sdkstep.AskGo, m.Node, m.SayEvent) +} + +// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791, +// §820): Outputs when a test sets it, else the module's own objects store on the bus. +func (m *Module) outputs() steprun.OutputObjects { + if m.Outputs != nil { + return m.Outputs + } + return busstate.ObjectsOf(steprun.OutputsStore) +} + // Puller is the module's pull of its seat's asks, on source (the runtime's seat pull when nil). func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller { if source == nil { source = &steprun.SeatAsks{Language: sdkstep.AskGo, Logf: m.Say} - if m.Callers == nil { - m.Callers = steprun.SeatListCallers(sdkstep.AskGo, m.Say) - } } capacity := m.Capacity // The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config @@ -91,7 +111,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul if m.SayEvent != nil { say = steprun.SayOn(sdkstep.AskGo, m.Node, m.SayEvent) } - return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskGo, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, + return &steprun.Puller{KeepAnswer: steprun.KeepAnswerIn(m.Answers), Source: source, Language: sdkstep.AskGo, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Logf: m.Say, Has: m.Has, Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) { if err := m.Check(ctx); err != nil { @@ -112,7 +132,8 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul // SeatTools are the seat's verbs on this node (ADR 0525 §10): what it runs, and its pause and resume. func (m *Module) SeatTools(p *steprun.Puller) []stdio.Tool { - return append(steprun.SeatTools(Seat, "Go", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, steprun.ReadOutputFrom(m.Outputs))) + return append(steprun.SeatTools(Seat, "Go", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, m.Node, m.outputs(), steprun.EndedHere(m.Node, m.ReadSteps.Keys, m.ReadSteps.Get)), + steprun.AnswerTool(Seat, steprun.ReadAnswerFrom(m.Answers))) } // StepEndTool ends one step left running (issue 1890); the module's steps state is the one it reads and writes. diff --git a/modules/mesh-build-go/cmd/mesh-build-go/asks_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/asks_integration_test.go index b1b9bc13c..ae3434874 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/asks_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/asks_integration_test.go @@ -4,6 +4,7 @@ package main import ( "context" + "encoding/json" "sync" "testing" "time" @@ -11,6 +12,7 @@ import ( "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" "git.novox.be/novox/mesh-sdk/go/testbus" @@ -30,6 +32,9 @@ const checkCommit = "89abcdef0123456789abcdef0123456789abcdef" // **The order is read from the record.** At capacity 1 the puller starts the check the instant the delivery ask's step // ends, well before any poll, so "the check key holds a state" is true on correct behaviour (issue 1887). The test // waits for both asks to end and compares the step records' own Started and Ended times, and the fetch order by commit. +// +// G1/AC2 (design 47 H2 H-A-517, H-A-532 DQ-2): each build that read its imports says imports-reported, and the +// delivery ask's is on the bus, on the seat's subject of the node. func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) { nc, err := nats.Connect(testbus.URL(t)) if err != nil { @@ -55,7 +60,7 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) { // A build rides main's subject, any other kind a named asker's (design 47 G §543). subject, _ := sdkstep.AskSubject(a.Language, a.Kind) if a.Kind != sdkstep.AskDelivery { - subject, _ = sdkstep.AskSubjectBy(a.Language, a.Kind, "mesh-delivery-checker") + subject, _ = sdkstep.AskSubjectBy(a.Language, a.Kind, "mesh-delivery-runner") } if _, err := js.Publish(ctx, subject, raw); err != nil { t.Fatal(err) @@ -64,9 +69,24 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) { states := newStates() m := moduleWith(states, "go1.26.0") m.Capacity = func() int { return 1 } + reported := make(chan *nats.Msg, 4) + sub, err := nc.ChanSubscribe(seat.SubjectImportsReportedAll, reported) + if err != nil { + t.Fatal(err) + } + defer func() { _ = sub.Unsubscribe() }() + m.SayEvent = func(subject string, body any, _ string) error { + raw, err := json.Marshal(body) + if err != nil { + return err + } + return nc.Publish(subject, raw) + } var mu sync.Mutex var order []string - steps := fakeSteps(new([]string)) + steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) { + return ImportsResult{Imports: []string{"git.novox.be/novox/mesh-sdk/go"}}, nil + }}) for i := range steps { if steps[i].Name == "build_go_fetch" { run := steps[i].Run @@ -87,7 +107,7 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) { ended := 0 states.mu.Lock() for _, a := range []sdkstep.StepAsk{first, check} { - asker := "mesh-delivery-checker" // a named ask's step is keyed under its asker, main's under its node (§481) + asker := "mesh-delivery-runner" // a named ask's step is keyed under its asker, main's under its node (§481) if a.Kind == sdkstep.AskDelivery { asker = "" } @@ -113,8 +133,26 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) { t.Fatalf("the check ask started at %v, before the delivery ask ended at %v at capacity 1", checkStarted, deliveryEnded) } mu.Lock() - defer mu.Unlock() if len(order) != 2 || order[0] != askCommit || order[1] != checkCommit { t.Fatalf("fetched %v, want the delivery ask's commit %s first, then the check's %s", order, askCommit, checkCommit) } + mu.Unlock() + for timeout := time.After(10 * time.Second); ; { + select { + case msg := <-reported: + var r seat.ImportsReported + if err := json.Unmarshal(msg.Data, &r); err != nil { + t.Fatal(err) + } + if r.Commit != askCommit { + continue + } + if msg.Subject != seat.SubjectImportsReported("ace") || r.Module != "mesh-delivery-view" || len(r.Imports) != 1 { + t.Fatalf("imports-reported on %s: %+v", msg.Subject, r) + } + return + case <-timeout: + t.Fatal("the delivery ask's imports-reported never reached the bus") + } + } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/asks_say_test.go b/modules/mesh-build-go/cmd/mesh-build-go/asks_say_test.go index f10e55ab4..465c142e3 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/asks_say_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/asks_say_test.go @@ -1,8 +1,11 @@ package main import ( + "context" + "encoding/json" "testing" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) @@ -11,15 +14,11 @@ import ( func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) { var subjects []string m := &Module{Node: "ace", Capacity: func() int { return 0 }, - Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" }, SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }} p := m.Puller(nil, steprun.NewFakeAsks()) if p.Say == nil { t.Fatal("the puller says no event") } - if got, ok := p.Callers("step"); !ok || len(got) != 1 { - t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok) - } seat, _ := sdkstep.BuildSeat(sdkstep.AskGo) for _, event := range []string{"ask-taken", "step-progress", "step-ended"} { if err := p.Say(event, nil, "id"); err != nil { @@ -32,3 +31,47 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) { } } } + +// G1/AC1 (design 47 H2 H-A-517, H-A-532 DQ-2): a build ask of a module with Go bundles that ends done says one +// imports-reported on the seat's subject of the node, naming the module, the fingerprint, the commit and the imports +// the imports step read. +func TestADoneBuildSaysItsImportSetOnTheNodesSubject(t *testing.T) { + type said struct { + subject, id string + body seat.ImportsReported + } + var events []said + m := moduleWith(newStates(), "go1.26.0") + m.SayEvent = func(subject string, body any, id string) error { + r, ok := body.(seat.ImportsReported) + if !ok { + raw, _ := json.Marshal(body) + t.Fatalf("said %s with %T: %s", subject, body, raw) + } + events = append(events, said{subject, id, r}) + return nil + } + imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/busstate"} + steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) { + return ImportsResult{Imports: imports}, nil + }}) + a := deliveryAsk() + a.Build.Fp = "src2:0123" + if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil { + t.Fatal(err) + } + if len(events) != 1 { + t.Fatalf("said %d imports-reported, want 1: %+v", len(events), events) + } + e := events[0] + if e.subject != seat.SubjectImportsReported("ace") { + t.Errorf("said on %s, want %s", e.subject, seat.SubjectImportsReported("ace")) + } + if e.id != "imports-reported.mesh-delivery-view.src2:0123" { + t.Errorf("id %s", e.id) + } + if e.body.Node != "ace" || e.body.Module != "mesh-delivery-view" || e.body.Fingerprint != "src2:0123" || e.body.Commit != askCommit || + len(e.body.Imports) != 2 || e.body.Imports[0] != imports[0] || e.body.Imports[1] != imports[1] { + t.Errorf("said %+v", e.body) + } +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/asks_test.go b/modules/mesh-build-go/cmd/mesh-build-go/asks_test.go index b8e3f6802..5ebd5d91c 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/asks_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/asks_test.go @@ -13,6 +13,8 @@ import ( sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/catalogue" ) const askCommit = "0123456789abcdef0123456789abcdef01234567" @@ -100,6 +102,29 @@ func TestAtCapacityZeroNothingIsPulledAndTheToolsAnswer(t *testing.T) { if src.Waiting(sdkstep.AskDelivery) != 1 || len(calls) != 0 { t.Fatalf("a node at capacity 0 pulled: waiting %d, calls %v", src.Waiting(sdkstep.AskDelivery), calls) } + // Design 47 H2 §801: the seat's current says the holder takes no ask and why: capacity 0, and once paused, paused. + current := func() string { + for _, tool := range m.SeatTools(p) { + if tool.Name == Seat+".current" { + out, err := tool.Run(map[string]any{}) + if err != nil { + t.Fatal(err) + } + return string(mustJSON(out)) + } + } + t.Fatal("no current verb") + return "" + } + if got := current(); !strings.Contains(got, `"takes":false`) || !strings.Contains(got, `"why-not":"capacity 0"`) { + t.Errorf("current at capacity 0 = %s", got) + } + if err := p.Pause("test@node"); err != nil { + t.Fatal(err) + } + if got := current(); !strings.Contains(got, `"why-not":"paused"`) { + t.Errorf("current paused = %s", got) + } for _, tool := range m.Tools(steps) { if tool.Name == "build_go_fetch" { out, err := tool.Run(map[string]any{"repository": "novox/x", "commit": askCommit}) @@ -119,7 +144,7 @@ func mustJSON(v any) []byte { b, _ := json.Marshal(v); return b } // the node's build capacity as a setting, with the builder's default; the seat's verbs are served as its tools. func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) { m := readManifest(t) - if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output"}) { + if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output", "answer"}) { t.Fatalf("claims = %+v", m.Claims) } if len(m.Reads) != 0 { @@ -133,6 +158,19 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) { } `json:"config"` } _ = json.Unmarshal(raw, &doc) + // Design 47 H2 H-A-411 (2), (3): a core module; its state detected-steps is pruned at its own writes, with the two prune + // tools and the settings prune-mark (70 %) and prune-target (50 %). + if m.Class != catalogue.ClassCore { + t.Errorf("class = %q, want %s", m.Class, catalogue.ClassCore) + } + for _, tool := range []string{ModuleName + "_state_prune_now", ModuleName + "_state_keep"} { + if !slices.Contains(m.Tools, tool) { + t.Errorf("tools = %v lack %s", m.Tools, tool) + } + } + if mark, target := string(doc.Config[stdio.PruneMarkSetting].Default), string(doc.Config[stdio.PruneTargetSetting].Default); mark != "70" || target != "50" { + t.Errorf("prune-mark %s and prune-target %s, want 70 and 50", mark, target) + } // Issue 1806's follow-up: the cores a step needs is a setting of its own, in the settings file, with the SDK's default. if cores := string(doc.Config[steprun.CoresPerStepSetting].Default); cores != fmt.Sprint(steprun.DefaultCoresPerStep[sdkstep.AskGo]) { t.Errorf("the cores-per-step default = %s, want %g", cores, steprun.DefaultCoresPerStep[sdkstep.AskGo]) @@ -157,6 +195,10 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) { if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") { t.Errorf("the build-hours description names a node pair") } + // Design 47 H2 H-A-539: no prefix tells a mesh package apart, so the module declares no setting import-prefix. + if _, ok := doc.Config["import-prefix"]; ok { + t.Errorf("the manifest declares import-prefix, which H-A-539 withdrew") + } var capacity float64 _ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity) if capacity != 0 { @@ -198,7 +240,7 @@ func TestACheckAsksDigestIsTheToolsAnswerInTheCall(t *testing.T) { } } ask := m.askSteps(steps) - a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker", + a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner", At: time.Now(), Check: &sdkstep.CheckJob{Fetch: sdkstep.Fetch{Repository: "novox/x", Commit: askCommit}, Levels: []string{sdkstep.LevelUnit}}} out, err := steprun.RunAsk(context.Background(), ask, a) if err != nil { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/build.go b/modules/mesh-build-go/cmd/mesh-build-go/build.go index c903d1e80..d6a9a78ad 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/build.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/build.go @@ -129,7 +129,7 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) { return m.buildGoPackage(ctx, workspace, dir, *art, version, seat) } if art.Kind == "archive" { - return m.buildArchive(ctx, workspace, module, manifest.Module, dir, *art, keep) + return m.buildArchive(ctx, workspace, module, manifest.Module, dir, *art, version, keep) } if art.Kind != "bundle" || art.Language != "go" { return nil, fmt.Errorf("the artifact %s of %s is a %s of language %q: this module builds Go bundles and archives", name, manifest.Module, art.Kind, art.Language) @@ -176,7 +176,7 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) { if err := m.insideModule(workspace, dir, out); err != nil { return nil, fmt.Errorf("the output directory of %s: %w", art.Name, err) } - res, err := m.packInto(ctx, workspace, module, manifest.Module, art.Name, "bundle", out, keep) + res, err := m.packInto(ctx, workspace, module, manifest.Module, art.Name, "bundle", version, out, keep) if err != nil { return nil, err } @@ -186,16 +186,17 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) { // packInto packs a directory with mesh-sdk's Pack, as the build agent packs every artifact, and publishes the archive // on the seat oci-artifact-registry from this process, after the build step ended (design 51 *Publishing*; publish.go): -// a candidate's as a trunk build's, under / by its digest, of kind (bundle or archive). The step -// answers the reference; a publish the seat refuses fails the step `not stored:`, unless keep names the build of the -// artifact store's holder, which this node then keeps and answers as kept (keptbuilds.go). The packed bytes never stay on -// the node: they are held in this process until the publish answered (the lead's decision L9). -func (m *Module) packInto(ctx context.Context, workspace, module, name, artifact, kind, root string, keep *sdkstep.KeptFor) (BuildResult, error) { +// a candidate's as a trunk build's, under / by its digest and the ask's version (H-A-373), of kind +// (bundle or archive). The step answers the reference; a publish the seat refuses fails the step `not stored:`, unless +// keep names the build of the artifact store's holder, which this node then keeps and answers as kept (keptbuilds.go). +// The packed bytes never stay on the node: they are held in this process until the publish answered (the lead's +// decision L9). +func (m *Module) packInto(ctx context.Context, workspace, module, name, artifact, kind, version, root string, keep *sdkstep.KeptFor) (BuildResult, error) { archive, digest, err := steprun.Pack(root) if err != nil { return BuildResult{}, fmt.Errorf("packing %s: %w", artifact, err) } - if err := m.publishArchive(ctx, name, artifact, kind, digest, archive); err != nil { + if err := m.publishArchive(ctx, name, artifact, kind, version, digest, archive); err != nil { if keep == nil { return BuildResult{}, fmt.Errorf("%s%s: %w", builds.NotStored, artifact, err) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/build_test.go b/modules/mesh-build-go/cmd/mesh-build-go/build_test.go index 4b1bebf26..e56bac62e 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/build_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/build_test.go @@ -57,10 +57,26 @@ func buildModule(t *testing.T, manifest, content string) (*Module, *keptStates, } func runBuild(t *testing.T, m *Module, states *keptStates, artifact string) (BuildResult, sdkstep.Step) { + t.Helper() + return runBuildArgs(t, m, states, map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact}) +} + +// askedVersion is the version a test's bundle ask reserved: every bundle publishes under the ask's version, and the +// delivery SDK refuses one that names none (design 47 H, H-A-373); an archive may still publish by its digest alone. +const askedVersion = "1.4.3" + +// runBundle runs the build tool for a bundle artifact under the ask's version, as the builder asks it. +func runBundle(t *testing.T, m *Module, states *keptStates, artifact string) (BuildResult, sdkstep.Step) { + t.Helper() + return runBuildArgs(t, m, states, map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact, "version": askedVersion}) +} + +// runBuildArgs runs the build tool with args, such as an ask's version, and answers what its step ended with. +func runBuildArgs(t *testing.T, m *Module, states *keptStates, args map[string]any) (BuildResult, sdkstep.Step) { t.Helper() for _, tool := range m.Tools(m.StepTools()) { if tool.Name == "build_go_build" { - if _, err := tool.Run(map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact}); err != nil { + if _, err := tool.Run(args); err != nil { t.Fatal(err) } } @@ -105,7 +121,7 @@ func goEntry(t *testing.T) (compile []string, linker []string, stamp string) { // GOFLAGS=-trimpath -buildvcs=false, go build, -ldflags -s -w -X main.builtFor=, -o /, the package. func TestTheBuildCommandCarriesTodaysFlagsAndEnvironment(t *testing.T) { m, states, calls := buildModule(t, manifestWith(goBundle), "binary") - res, st := runBuild(t, m, states, "tools") + res, st := runBundle(t, m, states, "tools") if st.State != sdkstep.StepPassed { t.Fatalf("the step ended %s: %s", st.State, st.Reason) } @@ -129,7 +145,7 @@ func TestTheBuildCommandCarriesTodaysFlagsAndEnvironment(t *testing.T) { } dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo") out := filepath.Join(dir, ".mesh-build", "tools") - want := "go -C " + dir + " build -ldflags " + strings.Join(linker, " ") + " -X " + stamp + "=arch -o " + filepath.Join(out, "demo-bin") + " ./cmd/demo-tools" + want := "go -C " + dir + " build -ldflags " + strings.Join(linker, " ") + " -X " + stamp + "=arch -X " + versionStamp + "=" + askedVersion + " -o " + filepath.Join(out, "demo-bin") + " ./cmd/demo-tools" if c.line != want { t.Errorf("command = %q\nwant %q", c.line, want) } @@ -142,8 +158,8 @@ func TestTheBuildCommandCarriesTodaysFlagsAndEnvironment(t *testing.T) { // are one digest. func TestTheArchiveHoldsOneExecutableAndTwoBuildsAreOneDigest(t *testing.T) { m, states, _ := buildModule(t, manifestWith(goBundle), "the program") - first, _ := runBuild(t, m, states, "tools") - second, _ := runBuild(t, m, states, "tools") + first, _ := runBundle(t, m, states, "tools") + second, _ := runBundle(t, m, states, "tools") if first.Digest != second.Digest || first.Reference != second.Reference { t.Errorf("two builds: %+v and %+v", first, second) } @@ -176,7 +192,7 @@ func TestAnArtifactOfAnotherLanguageFailsTheStepNamingIt(t *testing.T) { `{"name":"tools","kind":"image","from":"files"}`: "image", } { m, states, calls := buildModule(t, manifestWith(artifact), "x") - _, st := runBuild(t, m, states, "tools") + _, st := runBundle(t, m, states, "tools") if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "tools") || !strings.Contains(st.Reason, want) || len(*calls) != 0 { t.Errorf("%s: the step ended %s: %q after %d commands", artifact, st.State, st.Reason, len(*calls)) } @@ -196,7 +212,7 @@ func TestTheBinaryIsNamedAsTheBuildAgentNamesIt(t *testing.T) { `{"name":"tools","kind":"bundle","language":"go","system":"arch","from":".","loads":["tools"]}`: "tools", } { m, states, _ := buildModule(t, manifestWith(artifact), "x") - if res, st := runBuild(t, m, states, "tools"); res.Binary != want { + if res, st := runBundle(t, m, states, "tools"); res.Binary != want { t.Errorf("%s: binary %q, want %q (%s %s)", artifact, res.Binary, want, st.State, st.Reason) } } @@ -229,7 +245,7 @@ func TestABuildOutputDirectoryLinkedOutsideTheModuleIsRefused(t *testing.T) { if err := os.Symlink(outside, filepath.Join(m.Work, "ws1", "tree", "modules", "demo", ".mesh-build")); err != nil { t.Fatal(err) } - _, st := runBuild(t, m, states, "tools") + _, st := runBundle(t, m, states, "tools") if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "outside") || !strings.Contains(st.Reason, outside) || len(*calls) != 0 { t.Errorf("the step ended %s: %q after %d commands", st.State, st.Reason, len(*calls)) } @@ -247,7 +263,7 @@ func TestAManifestFallingBackToAPredefinedKeyBuilds(t *testing.T) { t.Fatal("the captured manifest no longer falls back to a predefined key") } m, states, _ := buildModule(t, string(raw), "binary") - res, st := runBuild(t, m, states, "tools") + res, st := runBundle(t, m, states, "tools") if st.State != sdkstep.StepPassed { t.Fatalf("the step ended %s: %s", st.State, st.Reason) } @@ -268,8 +284,10 @@ func TestTheBuildGetsTheVersionTheAskCarriesAsMeshVersion(t *testing.T) { } } } - if st := states.waitEnd(t); st.State != sdkstep.StepPassed { - t.Fatalf("the step ended %s: %s", st.State, st.Reason) + // A bundle asked with no version is built, stamped with none, and its publish refused loudly (H-A-373). + if st := states.waitEnd(t); (version != "") != (st.State == sdkstep.StepPassed) || + version == "" && !strings.Contains(st.Reason, "names no version") { + t.Fatalf("ask version %q: the step ended %s: %s", version, st.State, st.Reason) } got := "" for _, r := range *calls { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/builds.go b/modules/mesh-build-go/cmd/mesh-build-go/builds.go index 200b01c75..588ac2c1f 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/builds.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/builds.go @@ -10,13 +10,18 @@ import ( "archive/zip" "bytes" "context" + "crypto/sha256" + "encoding/hex" "fmt" "io" + "net/http" "os" "path" "path/filepath" "strings" + artifactref "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient/reference" + imageseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) @@ -108,3 +113,65 @@ func unzipBuild(data []byte, dir string) error { } return nil } + +// **A step's install archive, unpacked into the workspace** (design 47 H2 §800; H-A-399 (2)): an integration step whose +// module's Go artifact needs node-build-node names the archive the Node build module's install published to the artifact +// store, as its reference (`oci-artifact-registry//@`); the level's tests run with its tree +// laid into the workspace's tree. It is read from the store by its digest, as a pinned archive is fetched by its pin: +// bytes that are not the digest's are refused, and a store that does not answer is a transport fault (§799). +var installForms = artifactref.Seats{Image: imageseat.Seat, Object: ArtifactSeat} + +// layInstall fetches the archive reference names from the artifact store and unpacks it into tree. +func (m *Module) layInstall(ctx context.Context, workspace, tree, reference string) error { + where, kept := installForms.InArtifactStore(reference) + _, digest, _ := strings.Cut(where, "/blobs/") + if !kept || !strings.HasPrefix(digest, "sha256:") { + return fmt.Errorf("the install archive %q is no reference of an archive in the artifact store", reference) + } + base, err := steprun.StoreURL(m.ArtifactStoreFile) + if err != nil { + return fmt.Errorf("the install archive %s is read from the artifact store: %w", reference, err) + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/v2/"+where, nil) + if err != nil { + return err + } + response, err := m.httpClient().Do(request) + if err != nil { + return steprun.Transport(fmt.Errorf("cannot fetch the install archive %s: %w", reference, err)) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return fmt.Errorf("the artifact store answered %s for the install archive %s", response.Status, reference) + } + dir := filepath.Join(m.Work, workspace, "upstream") + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + part, err := os.CreateTemp(dir, "install.*.part") + if err != nil { + return err + } + defer os.Remove(part.Name()) + hash := sha256.New() + n, err := io.Copy(io.MultiWriter(part, hash), io.LimitReader(response.Body, maxUpstream+1)) + if cerr := part.Close(); err == nil { + err = cerr + } + if err != nil { + return steprun.Transport(fmt.Errorf("fetching the install archive %s: %w", reference, err)) + } + if n > maxUpstream { + return fmt.Errorf("the install archive %s is larger than %d bytes, more than a machine unpacks", reference, maxUpstream) + } + if got := "sha256:" + hex.EncodeToString(hash.Sum(nil)); got != digest { + return fmt.Errorf("the install archive %s read as %s, not its digest", reference, got) + } + if err := unpackUpstream(part.Name(), tree, ""); err != nil { + return fmt.Errorf("the install archive %s: %w", reference, err) + } + if m.Say != nil { + m.Say("laid the install archive %s into the workspace %s", reference, workspace) + } + return nil +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/builds_test.go b/modules/mesh-build-go/cmd/mesh-build-go/builds_test.go index bfc578415..3e09bd1ba 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/builds_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/builds_test.go @@ -14,6 +14,7 @@ import ( "testing" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) // Design 47 G §465, §373 (BG7): a fetch naming builds reads each member from the artifact store by its digest, checks the @@ -28,9 +29,21 @@ func TestAFetchLaysAGroupMembersBuildFromTheArtifactStore(t *testing.T) { zw.Close() sum := sha256.Sum256(zbuf.Bytes()) digest := "sha256:" + hex.EncodeToString(sum[:]) + // Design 47 H2 §800: an install archive, as the Node build module packs it, its paths from the workspace's tree. + npm := t.TempDir() + os.MkdirAll(filepath.Join(npm, "modules", "gitea", "node_modules", "x"), 0o755) + os.WriteFile(filepath.Join(npm, "modules", "gitea", "node_modules", "x", "index.js"), []byte("module.exports = 1\n"), 0o644) + install, installDigest, err := steprun.Pack(npm) + if err != nil { + t.Fatal(err) + } var asked []string store := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { asked = append(asked, r.URL.Path) + if r.URL.Path == "/v2/gitea/node-modules/blobs/"+installDigest { + rw.Write(install) + return + } if r.URL.Path != "/v2/lib/pkg/blobs/"+digest { http.NotFound(rw, r) return @@ -68,7 +81,21 @@ func TestAFetchLaysAGroupMembersBuildFromTheArtifactStore(t *testing.T) { t.Errorf("member %+v: error %v", c, err) } } + // Design 47 H2 §800: the step's install archive is read from the store by its reference and unpacked into the tree; a + // reference whose bytes are not its digest is refused, and a store that does not answer is a transport fault (§799). + if err := m.layInstall(context.Background(), "ws1", filepath.Join(root, "tree"), "oci-artifact-registry/gitea/node-modules@"+installDigest); err != nil { + t.Fatal(err) + } + if b, err := os.ReadFile(filepath.Join(root, "tree", "modules", "gitea", "node_modules", "x", "index.js")); err != nil || string(b) != "module.exports = 1\n" { + t.Errorf("the install archive was not unpacked into the tree: %q, %v", b, err) + } + if err := m.layInstall(context.Background(), "ws1", filepath.Join(root, "tree"), "oci-artifact-registry/gitea/node-modules@"+digest); err == nil { + t.Error("an install archive whose bytes are not its digest was laid") + } store.Close() + if err := m.layInstall(context.Background(), "ws1", filepath.Join(root, "tree"), "oci-artifact-registry/gitea/node-modules@"+installDigest); !sdkstep.IsPassing(err) { + t.Errorf("an install archive from a store that does not answer: %v, want a transport fault", err) + } if err := m.layBuilds(context.Background(), root, []string{"."}, []sdkstep.FetchBuild{member}); err == nil || !strings.Contains(err.Error(), "example.test/lib") { t.Errorf("a store that does not answer: %v", err) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/compose_test.go b/modules/mesh-build-go/cmd/mesh-build-go/compose_test.go index 20a5c522a..f2d708c2c 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/compose_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/compose_test.go @@ -166,14 +166,15 @@ func TestAComposeAskFailsLoudly(t *testing.T) { } // Design 47 G §615: the module reads the manifests a compose ask names from the catalog graph's entry, by the seat's verb -// entry, and invokes no tool of the delivery indexer. 1921 (B0): a run's input is asked of the checker seat's verb input, as -// the manifest invokes it, and no state of the checker's inputs is read (ADR 0596 §2). +// entry, and invokes no tool of the delivery indexer. 1921 (B0): a run's input is asked of the seat mesh-wants' verb input, as +// the manifest invokes it, and no state of the checker's inputs is read (ADR 0596 §2); the seat mesh-delivery-checker is no +// longer invoked (design 47 H §764, H-A-57). func TestTheModuleReadsTheCatalogEntries(t *testing.T) { m := readManifest(t) if !slices.Contains(m.Invokes, catalogclient.EntryVerb) || slices.ContainsFunc(m.Invokes, func(i string) bool { return strings.HasPrefix(i, "mesh-delivery-indexer") }) { t.Errorf("invokes = %v: want %s and no tool of the indexer", m.Invokes, catalogclient.EntryVerb) } - if !slices.Contains(m.Invokes, runInputVerb) || slices.Contains(m.Reads, "mesh-delivery-checker.inputs") { + if !slices.Contains(m.Invokes, runInputVerb) || slices.ContainsFunc(m.Invokes, func(i string) bool { return strings.HasPrefix(i, "seat:mesh-delivery-checker") }) || slices.Contains(m.Reads, "mesh-delivery-checker.inputs") { t.Errorf("invokes = %v, reads = %v: want %s invoked and no inputs state read", m.Invokes, m.Reads, runInputVerb) } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/detected.go b/modules/mesh-build-go/cmd/mesh-build-go/detected.go new file mode 100644 index 000000000..4bf0beabe --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/detected.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "os" + "sync" + + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/stateobjects" +) + +// ModuleName is this module's name, which its prune tools are named for (stateobjects.PruneTools). +const ModuleName = "mesh-build-go" + +// prunedDetected is the state detected-steps, pruned toward its cap at this module's own writes (design 47 H2 §812; +// H-A-411 (2), (3)): past prune-mark of its 8 MiB the oldest keys go down to prune-target, in one journal line. Each key +// is an artifact's steps as detected, which the verb steps detects again when its key is gone. A setting that is no +// percentage is said, and the defaults hold. +var prunedDetected = sync.OnceValue(func() *stdio.PrunedState { + p, err := stdio.PruneSettings() + if err != nil { + fmt.Fprintf(os.Stderr, "the prune of %s keeps its defaults (%d %% to %d %%): %v\n", seat.StateDetectedSteps, stdio.PruneMarkDefault, stdio.PruneTargetDefault, err) + p = stdio.Prune{Mark: stdio.PruneMarkDefault, Target: stdio.PruneTargetDefault} + } + return stdio.State(seat.StateDetectedSteps).Pruned(p) +}) + +// pruneTools are the module's two prune tools over detected-steps, each written in the hand-act log (H-A-380 (3)). +func pruneTools() []stdio.Tool { + return stateobjects.PruneTools(ModuleName, []stateobjects.Pruning{{Name: seat.StateDetectedSteps, State: prunedDetected()}}, + meshhandactsclient.Recorder{Ask: stdio.Ask}) +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/digest.go b/modules/mesh-build-go/cmd/mesh-build-go/digest.go index 9aa9c4616..5a29a290a 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/digest.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/digest.go @@ -18,12 +18,14 @@ import ( "os" "path" "path/filepath" + "slices" "sort" "strconv" "strings" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // DigestVersion is the form of the digest's text: changed whenever what the digest hashes changes in kind. @@ -56,31 +58,53 @@ const namesVariable = "MESH_NODE_NAMES" // from the Go test log with each verdict, replaces the lists (issue 1936). const ReadsOutsideMarker = "reads-outside" -// NeedsMarker is the name of a file in a package's directory that names, one per line, what its integration tests need -// of the node they run on (issue 890; mesh-delivery-sdk steprun.AskNeeds): `node-build-node` for tests that read the Node build -// module's installed toolchain. The digest reports it (DigestResult.Needs); a check ask leaves such a package untested on -// a node that lacks it, and the checker asks it again of a node that has it. A marker beside the tests, as -// ReadsOutsideMarker is, and not a manifest field: it is a property of the package's tests, read only where they are -// run, and the manifest describes the module on the machines. The unit level is never given anything of the node (ADR -// 0533 §1), so a marker binds the integration level alone. Blank lines and lines starting with # are not read. -const NeedsMarker = "check-needs" - -// readNeeds is what the marker in dir names; nil when there is none. -func readNeeds(dir string) ([]string, error) { - raw, err := os.ReadFile(filepath.Join(dir, NeedsMarker)) - if errors.Is(err, fs.ErrNotExist) { - return nil, nil - } - if err != nil { - return nil, err - } - var needs []string - for _, l := range strings.Split(string(raw), "\n") { - if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "#") { - needs = append(needs, l) +// readNeeds is what a package's integration tests need of the node they run on (issue 890; mesh-delivery-sdk +// steprun.AskNeeds): the seats its module's manifest names in `check-needs` on each Go artifact whose path holds the +// package's directory (design 47 H2 §800; H-A-350 DMC-6, H-A-399 (3)), `node-build-node` for tests that read the Node +// build module's installed toolchain, and for a package none of its Go artifacts holds, the manifest's own top-level +// `check-needs` (H-A-453 (2)). The manifest is the nearest module.json in dir or above it within the tree; nil when +// there is none, or it names no needs for dir. The digest reports it (DigestResult.Needs); a check ask +// leaves such a package untested on a node that lacks it, and the checker asks it again of a node that has it. The unit +// level is never given anything of the node (ADR 0533 §1), so the field binds the integration level alone. +func readNeeds(tree, dir string) ([]string, error) { + for at := dir; within(tree, at); at = filepath.Dir(at) { + raw, err := os.ReadFile(filepath.Join(at, "module.json")) + if errors.Is(err, fs.ErrNotExist) { + if at == tree { + break + } + continue } + if err != nil { + return nil, err + } + manifest, err := catalogue.Decode(raw) + if err != nil { + return nil, fmt.Errorf("the manifest %s: %w", filepath.Join(at, "module.json"), err) + } + var needs []string + held := false + if manifest.Build != nil { + for _, a := range manifest.Build.Artifacts { + if a.Language != "go" || !within(filepath.Join(at, filepath.FromSlash(a.From)), dir) { + continue + } + held = true + for _, n := range a.CheckNeeds { + if !slices.Contains(needs, n) { + needs = append(needs, n) + } + } + } + } + if !held { + // A package no Go artifact's from holds (the forge module's internal/seatgit) takes the manifest's own + // check-needs (H-A-453 (2)). + needs = slices.Clone(manifest.CheckNeeds) + } + return needs, nil } - return needs, nil + return nil, nil } // integrationTags are the build tags of the integration level, its run and its digest alike: integration, and isolation @@ -149,7 +173,7 @@ type DigestResult struct { // of the files markers name, which several packages share (the catalogue's manifests). neverKept map[string]string hashedFiles map[string]string - // Needs are the packages whose tests at this level need something of the node, as their NeedsMarker names it. + // Needs are the packages whose tests at this level need something of the node, as their module's manifest names them (check-needs). Needs []sdkstep.PackageNeeds `json:"needs,omitempty"` // JudgedBy is the program that ran the digest (ADR 0535 §5): "installed", or "candidate " under the // runner workspace. @@ -340,9 +364,9 @@ func digestModule(res *DigestResult, pkgs map[string]*goPackage, tree string, he return fmt.Errorf("go list gave no test binary for %s", path) } if needs { - n, err := readNeeds(root.Dir) + n, err := readNeeds(tree, root.Dir) if err != nil { - return fmt.Errorf("%s: its %s: %w", path, NeedsMarker, err) + return fmt.Errorf("%s: its check-needs: %w", path, err) } if len(n) > 0 { res.Needs = append(res.Needs, sdkstep.PackageNeeds{Package: path, Needs: n}) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/digest_test.go b/modules/mesh-build-go/cmd/mesh-build-go/digest_test.go index df2fbb19d..ef7414428 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/digest_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/digest_test.go @@ -353,15 +353,40 @@ func TestAListedReadsOutsideMarkerKeepsTheDigestOfOnlyWhatItLists(t *testing.T) before = after } - // Issue 890/AC3: a package whose directory carries the needs marker is named with its needs at the integration level, - // comments and blank lines not read, and at the unit level not at all. - edit(t, tree, "a/"+NeedsMarker, "# its integration tests copy the installed Node toolchain\n\nnode-build-node\n") + // Issue 890/AC3, design 47 H2 §800 (H-A-350 DMC-6): a package a Go artifact of its module's manifest holds is named + // with the artifact's check-needs at the integration level, a package no such artifact holds (c) not, and at the + // unit level not at all. + edit(t, tree, "module.json", `{"module":"digest","build":{"artifacts":[`+ + `{"name":"tools","kind":"bundle","language":"go","from":"a","check-needs":["node-build-node"]},`+ + `{"name":"other","kind":"bundle","language":"go","from":"c"}]}}`) if n := digests(t, m, LevelIntegration).Needs; len(n) != 1 || n[0].Package != a || strings.Join(n[0].Needs, ",") != "node-build-node" { t.Errorf("the integration level's needs = %+v, want %s needing node-build-node", n, a) } if n := digests(t, m, LevelUnit).Needs; len(n) != 0 { t.Errorf("the unit level names needs: %+v", n) } + + // H-A-453 (2): the manifest's own check-needs name the seats of a package no Go artifact's from holds (the forge + // module's internal/seatgit), and never those of a package an artifact holds, which keeps the artifact's. + for _, row := range []struct { + manifest, cNeeds string + }{ + {`{"module":"digest","check-needs":["node-build-node"],"build":{"artifacts":[` + + `{"name":"tools","kind":"bundle","language":"go","from":"a","check-needs":["node-build-node"]},` + + `{"name":"other","kind":"bundle","language":"go","from":"c"}]}}`, ""}, + {`{"module":"digest","check-needs":["node-build-node"],"build":{"artifacts":[` + + `{"name":"tools","kind":"bundle","language":"go","from":"a","check-needs":["node-build-node"]},` + + `{"name":"code","kind":"bundle","language":"typescript"}]}}`, "node-build-node"}, + } { + edit(t, tree, "module.json", row.manifest) + got := map[string]string{} + for _, n := range digests(t, m, LevelIntegration).Needs { + got[n.Package] = strings.Join(n.Needs, ",") + } + if got[a] != "node-build-node" || got[c] != row.cNeeds { + t.Errorf("%s: the integration level's needs = %v, want %s and %s needing %q", row.manifest, got, a, c, row.cNeeds) + } + } } // Issue 1935: a catalogue module's packages read ../../module.json and the module's files: a change to them changes the diff --git a/modules/mesh-build-go/cmd/mesh-build-go/fetch.go b/modules/mesh-build-go/cmd/mesh-build-go/fetch.go index 47d6586fd..539790977 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/fetch.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/fetch.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "os" + "path" "path/filepath" "regexp" "slices" @@ -157,7 +158,7 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str return nil, err } if (base == "" || res.Merge != "") && len(req.Paths) > 0 { - if err := steprun.Narrow(tree, req); err != nil { + if err := narrowTree(tree, repository, req); err != nil { // with what H-A-136 adds return nil, err } // Said beside the tree, so the steps that list the tree's go.mod files leave out those narrowed away. @@ -173,7 +174,7 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str // A fetch asked with a module's directory is of that Go module and what its go.mod replaces with a local path, // never another Go module of the tree (design 47 G, A-447). Said beside the tree, so every later step lists the // same modules. - if dirs, err = scopedDirs(tree, dir, dirs); err != nil { + if dirs, err = scopedDirs(tree, dir, req.Paths, dirs); err != nil { return nil, err } if err := os.WriteFile(filepath.Join(root, scopeMark), []byte(strings.Join(dirs, "\n")), 0o600); err != nil { @@ -193,35 +194,63 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str } // The directories download side by side, up to the bound (ADR 0536 §2); the first failure in directory order is the // step's. Resolving a pin places a repository beside the workspace, which two directories may share: one at a time. + // Two passes (design 47 H, H-A-494 addendum): every directory's mesh packages from the Go package registry first, + // then every directory's rest through the public proxy, so the module cache holds each mesh package before any + // download of the rest. var pins sync.Mutex errs := make([]error, len(dirs)) taken := make([][]TakenVersion, len(dirs)) slots := make(chan struct{}, m.parallel()) - var wg sync.WaitGroup - for i, d := range dirs { - if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil { - continue // a module that vendors resolves nothing + sideBySide := func(pass func(i int, d string)) { + var wg sync.WaitGroup + for i, d := range dirs { + if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil { + continue // a module that vendors resolves nothing + } + if errs[i] != nil { + continue // failed in the first pass + } + wg.Add(1) + slots <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-slots }() + pass(i, d) + }() } - wg.Add(1) - slots <- struct{}{} - go func() { - defer wg.Done() - defer func() { <-slots }() - // The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go). - if taken[i], errs[i] = m.takeVersions(ctx, root, filepath.Join(tree, d), d, req.Packages, &pins); errs[i] != nil { - return - } - var more []TakenVersion - // Then what only a module the directory replaces names, which the download would not miss (pins.go). - more, errs[i] = m.takeReplacedZeroPins(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins) - if taken[i] = append(taken[i], more...); errs[i] != nil { - return - } - more, errs[i] = m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages) - taken[i] = append(taken[i], more...) - }() + wg.Wait() } - wg.Wait() + sideBySide(func(i int, d string) { + // A mesh package is required at the zero version only: one a go.mod names at another version is refused + // before either download, so the second can never carry a forge path to the public proxy (H-A-494 second addendum). + if errs[i] = namedForgeVersion(repository, filepath.Join(tree, d)); errs[i] != nil { + return + } + // The checked repository's own modules come from the fetched tree, at whatever version go.mod names them + // (pins.go takeOwnRequirements; design 47 H, S31). + if taken[i], errs[i] = m.takeOwnRequirements(root, repository, filepath.Join(tree, d), d); errs[i] != nil { + return + } + // The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go). + more, err := m.takeVersions(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, &pins) + if taken[i], errs[i] = append(taken[i], more...), err; errs[i] != nil { + return + } + // Then every requirement at the zero version of the directory's graph the asked versions did not take, its own + // and what only a module it replaces names, taken or refused before any download of the rest, so no forge + // path reaches the public proxy first (pins.go; H-A-494 third addendum). + more, errs[i] = m.takeZeroPinsFirst(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins) + taken[i] = append(taken[i], more...) + }) + for _, err := range errs { + if err != nil { + return nil, err + } + } + sideBySide(func(i int, d string) { + more, err := m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages) + taken[i], errs[i] = append(taken[i], more...), err + }) for _, err := range errs { if err != nil { return nil, err @@ -236,10 +265,10 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str return res, nil } -// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree). A pin of a forge module -// that Go cannot fetch is looked for among the forge's pull request heads and handed to Go by a modfile (pins.go); a -// failure that names no such pin is the first failure. A requirement at the zero version is taken from the asked -// versions (pins.go takeZeroPins). +// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree): the fetch's second +// download, after every mesh package was taken. A requirement at the zero version a failure still names is taken from +// the asked versions (pins.go takeZeroPins); any other failure is the first failure. A version a go.mod names is never +// placed from a pull request's head (H-A-494 third addendum): namedForgeVersion refused it before. func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d string, pins *sync.Mutex, asked sdkstep.PackageVersions) ([]TakenVersion, error) { var taken []TakenVersion for { @@ -255,13 +284,7 @@ func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d s if err != nil { return taken, err } - pins.Lock() - progress, err := m.resolvePins(ctx, root, dir, failure.Error()) - pins.Unlock() - if err != nil { - return taken, err - } - if !progress && len(took) == 0 { + if len(took) == 0 { return taken, failure } } @@ -438,10 +461,11 @@ func (m *Module) downloadAndVerify(ctx context.Context, dir, d string) error { } } } - cmd, env := []string{"-C", dir, "mod", verb}, m.goEnvFor(dir) + // The second download: the rest of the build list through Go's public proxy alone (publicEnv). + cmd, env := []string{"-C", dir, "mod", verb}, publicEnv(m.goEnvFor(dir)) if modfile, ok := m.pinModfile(dir); ok && verb == "verify" { // go mod verify takes no -modfile: it is run on the modfile itself, which names the placed repositories. - cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, m.goEnv() + cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, publicEnv(m.goEnv()) } r := m.Run(ctx, env, "go", cmd...) if r.Status != 0 || r.Err != "" { @@ -515,8 +539,10 @@ func inTestdata(path string) bool { } // goEnv is what a go command of a step is given beyond the base environment: the installed go alone (GOTOOLCHAIN=local, ADR 0477 §1: no toolchain is ever downloaded), -// modules resolved by their go.mod and go.sum, the module's own caches, the mesh's own modules fetched directly (by -// git, through the account's rewrite of the forge's address to ssh), and nothing that asks a question. For a directory +// modules resolved by their go.mod and go.sum, the module's own caches, the checksum database off for the forge's paths +// (go.sum and the builder's h1: digest guard them, ADR 0605 §6), and no proxy at all (GOPROXY=off): only the fetch's two +// downloads reach the network, each with its own proxy (registryEnv, publicEnv; design 47 H, H-A-494 and its addendum), +// and every other step (the test and lint steps, the compile) reads the module cache the fetch filled. For a directory // that vendors, see goEnvFor. func (m *Module) goEnv() []string { modcache := filepath.Join(m.Cache, "gomod") @@ -528,20 +554,48 @@ func (m *Module) goEnv() []string { "GOFLAGS=-mod=mod", "GOMODCACHE=" + modcache, "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), + "GONOSUMDB=" + ForgeGoPaths, + "GOPROXY=off", } - if proxy := m.goSeat(); proxy != "" { - // The Go seat first, the public proxy second, the forge's git last (CAT-BG3, E11: direct goes in the first - // change after mesh-sdk's and mesh-contracts' first numbered versions are in the Go seat); no GOPRIVATE, and - // the checksum database off for the forge's paths, which go.sum and the builder's h1: digest guard instead. - // The seat goes on to the public proxy only on a 404 or 410 (",": a package it does not hold), so a seat that - // fails otherwise (5xx, refused, timeout) fails the fetch loudly; the public proxy goes on to direct on any - // failure ("|"): a public proxy the node cannot reach stopped the fetch before direct, and direct reaches the - // forge's git for a package the seat does not hold (issue 1966, ADR 0605 §6). - env = append(env, "GOPROXY="+proxy+","+PublicGoProxy+"|direct", "GONOSUMDB="+ForgeGoPaths, "GOPRIVATE=") - } else { - env = append(env, "GOPRIVATE="+ForgeGoPaths) + return append(env, m.threadEnv()...) +} + +// errNoRegistry is a fetch that needs a mesh package with no binding of the Go package registry seat: the package +// comes from that seat alone (design 47 H, H-A-494), never from the public proxy nor the forge's git. +var errNoRegistry = errors.New("no Go package registry bound") + +// registryEnv is env for the fetch's first download, of each pinned mesh package (takeVersion): the Go package registry +// seat alone and nothing behind it (GOPROXY=,off), so a version the seat does not hold fails as its miss +// (registryMiss), never reaching the public proxy, which serves the forge's paths from git tags, nor the forge's git +// (design 47 H, H-A-494 addendum). With no binding it refuses (errNoRegistry). +func (m *Module) registryEnv(env []string) ([]string, error) { + seat := m.goSeat() + if seat == "" { + return nil, errNoRegistry } - return append(append(env, "GIT_TERMINAL_PROMPT=0", "GIT_SSH_COMMAND=ssh -o BatchMode=yes"), m.threadEnv()...) + return withProxy(env, seat+",off"), nil +} + +// publicEnv is env for the fetch's second download, of the rest of the build list: Go's public proxy alone, no direct +// (design 47 H, H-A-494 addendum). The module cache already holds the mesh packages the first download took, so a forge +// path never reaches the public proxy. +func publicEnv(env []string) []string { return withProxy(env, PublicGoProxy) } + +// withProxy is env with its GOPROXY set to proxy, once. +func withProxy(env []string, proxy string) []string { + out := make([]string, 0, len(env)+1) + for _, e := range env { + if !strings.HasPrefix(e, "GOPROXY=") { + out = append(out, e) + } + } + return append(out, "GOPROXY="+proxy) +} + +// registryMiss says whether a failure of the first download is the Go package registry seat not holding the version: +// the seat answered 404 or 410, and Go, with nothing behind the seat but off, words it as the lookup off. +func registryMiss(failure string) bool { + return strings.Contains(failure, "disabled by GOPROXY=off") || strings.Contains(failure, "404 Not Found") || strings.Contains(failure, "410 Gone") } // PublicGoProxy is Go's public module proxy; ForgeGoPaths the module paths the forge serves. @@ -550,7 +604,7 @@ const ( ForgeGoPaths = "git.novox.be" ) -// goSeat is the Go seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the +// goSeat is the Go package registry seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the // module holds no binding of it or the binding names no address. func (m *Module) goSeat() string { if m.GoSeatFile == "" { @@ -685,9 +739,9 @@ func cleanDir(dir string) string { // scopedDirs are the go.mod directories of all that a module directory dir chooses: dir itself and each directory its // go.mod replaces with a local path, followed through their own replaces (design 47 G, A-447), in order. A directory -// the tree holds no go.mod for is left out. A directory holding no go.mod chooses every go.mod under it, and one that -// chooses no Go module at all is an error naming it (A-447a). -func scopedDirs(tree, dir string, all []string) ([]string, error) { +// the tree holds no go.mod for is left out. A directory holding no go.mod chooses every go.mod under it (A-447a), and one that +// chooses no Go module at all is an empty scope (H-A-371). +func scopedDirs(tree, dir string, paths, all []string) ([]string, error) { have := map[string]bool{} for _, d := range all { have[d] = true @@ -696,11 +750,23 @@ func scopedDirs(tree, dir string, all []string) ([]string, error) { todo := []string{dir} if !have[dir] { // A directory with no go.mod of its own (a module whose Go code lies in go/, a contracts module with a go.mod per - // seat) is every go.mod under it; the tree is already narrowed to the module's paths (A-447a). + // seat) is every go.mod under it, in a narrowed tree under its named paths (A-447a): the narrowed tree also holds + // the module's generated-from directories and its repository's zero-version packages (H-A-136), which are not + // the artifact's own Go modules. + roots := []string{dir} + if len(paths) > 0 { + roots = nil + for _, p := range paths { + roots = append(roots, path.Join(dir, filepath.ToSlash(p))) + } + } todo = nil for _, d := range all { - if dir == "." || strings.HasPrefix(d, dir+"/") { - todo = append(todo, d) + for _, r := range roots { + if r == "." || d == r || strings.HasPrefix(d, r+"/") { + todo = append(todo, d) + break + } } } } @@ -734,8 +800,8 @@ func scopedDirs(tree, dir string, all []string) ([]string, error) { out = append(out, d) } } - if len(out) == 0 { - return nil, fmt.Errorf("the module directory %q holds no Go module (no go.mod in it or under it)", dir) - } + // A directory that chooses no Go module (a module with an archive artifact and no Go code) is an empty scope, never + // a refusal: the builder sends its directory with every lane, and its archive is packed here. A Go bundle or package + // whose directory holds no go.mod fails at its build step, naming it (design 47 H, H-A-371). return out, nil } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/fetch_test.go b/modules/mesh-build-go/cmd/mesh-build-go/fetch_test.go index aeaa3e44f..5086a427e 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/fetch_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/fetch_test.go @@ -95,9 +95,33 @@ func fetchModule(t *testing.T, f *fakeStep) (*Module, *keptStates) { states := newStates() m := moduleWith(states, "go1.27.1") m.Run, m.Home, m.Work, m.Cache = f.run, t.TempDir(), t.TempDir(), t.TempDir() + bindRegistry(t, m) return m, states } +// testRegistry is the Go package registry seat's proxy a test binding names (bindRegistry). +const testRegistry = "http://forge.mesh:3000/api/packages/novox/go" + +// bindRegistry gives m a binding of the Go package registry seat, as every build node has (go-package-registry). +func bindRegistry(t *testing.T, m *Module) { + t.Helper() + m.GoSeatFile = filepath.Join(t.TempDir(), "go-package-registry.json") + if err := os.WriteFile(m.GoSeatFile, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil { + t.Fatal(err) + } +} + +// proxyValues are the GOPROXY settings of env. +func proxyValues(env []string) []string { + var out []string + for _, e := range env { + if strings.HasPrefix(e, "GOPROXY=") { + out = append(out, e) + } + } + return out +} + // fetchTool is the fetch tool as a build module is asked, always with its module's directory (A-447b): the root of the // tree unless the args name one. rawFetchTool is the tool as it is. func fetchTool(t *testing.T, m *Module) func(map[string]any) (any, error) { @@ -132,10 +156,20 @@ var fetchArgs = map[string]any{"repository": "novox/mesh-sdk", "commit": commitS // directory (not in one that vendors) with GOTOOLCHAIN=local, GOFLAGS=-mod=mod and the module's cache paths. func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) { // The root go.mod replaces the other two by directory: a fetch asked with a module's directory chooses what it replaces. + // Each Go module requires a mesh package at the zero version, which the ask pins (H-A-494 addendum: the first download). + const contracts = "git.novox.be/novox/mesh-contracts/go/x" f := &fakeStep{gomods: "go.mod\nsub/dir/go.mod\nvend/go.mod\n", vendors: []string{"vend"}, - files: map[string]string{"go.mod": "module fake\nreplace a => ./sub/dir\nreplace b => ./vend\n"}} + files: map[string]string{"go.mod": "module fake\nrequire " + contracts + " " + zeroVersion + "\nreplace a => ./sub/dir\nreplace b => ./vend\n", + "sub/dir/go.mod": "module fake/sub\nrequire " + contracts + " " + zeroVersion + "\n"}, + goRule: func(line string) forgekey.Ran { + if strings.Contains(line, " mod download -json "+contracts+"@") { + return forgekey.Ran{Stdout: `{"Path":"` + contracts + `","Version":"v0.1.85","Sum":"h1:zip=","GoModSum":"h1:mod="}`} + } + return forgekey.Ran{} + }} m, states := fetchModule(t, f) - if _, err := fetchTool(t, m)(fetchArgs); err != nil { + m.Parallel = 1 // one directory at a time, so the order of the commands is the fetch's own + if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-sdk", "commit": commitSHA, "packages": map[string]any{contracts: "v0.1.85"}}); err != nil { t.Fatal(err) } st := states.waitEnd(t) @@ -165,27 +199,47 @@ func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) { if strings.Contains(c.line, "vend") { t.Errorf("a module that vendors was downloaded: %s", c.line) } + // The second download (H-A-494 addendum): the rest of the build list through Go's public proxy alone. env := strings.Join(c.env, " ") - for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPRIVATE=git.novox.be"} { + for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPROXY=" + PublicGoProxy} { if !strings.Contains(env, want) { t.Errorf("%s: environment lacks %s: %s", c.line, want, env) } } - } - // CAT-BG3: with the Go seat bound, the fetch goes through it first, Go's public proxy second and the forge's git - // last, with no GOPRIVATE and the checksum database off for the forge's paths. - seat := filepath.Join(t.TempDir(), "go-package-registry.json") - if err := os.WriteFile(seat, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil { - t.Fatal(err) - } - m.GoSeatFile = seat - env := strings.Join(m.goEnv(), " ") - for _, want := range []string{"GOPROXY=http://forge.mesh:3000/api/packages/novox/go,https://proxy.golang.org|direct", "GONOSUMDB=git.novox.be", "GOPRIVATE= "} { - if !strings.Contains(env+" ", want) { - t.Errorf("with the Go seat bound the environment lacks %q: %s", want, env) + if got := proxyValues(c.env); len(got) != 1 || got[0] != "GOPROXY="+PublicGoProxy { + t.Errorf("%s: GOPROXY settings %v, want the public proxy alone", c.line, got) } } - m.GoSeatFile = "" + // Design 51 *Go packages*, H-A-494: no go command of the fetch reaches the forge's git (Go's direct), and none is + // handed GOPRIVATE or the account's ssh; the checksum database stays off for the forge's paths (ADR 0605 §6), and a + // step's own environment has no proxy at all. + for _, c := range f.calls { + if !strings.HasPrefix(c.line, "go ") { + continue + } + for _, e := range c.env { + if strings.HasPrefix(e, "GOPROXY=") && strings.Contains(e, "direct") || strings.HasPrefix(e, "GOPRIVATE=") || strings.HasPrefix(e, "GIT_SSH_COMMAND=") { + t.Errorf("%s: the environment says %s", c.line, e) + } + } + } + // H-A-494 addendum: every download of the Go package registry seat comes before every download through the public proxy. + lastRegistry, firstPublic, registry := -1, -1, 0 + for i, c := range f.calls { + switch got := proxyValues(c.env); { + case len(got) == 1 && got[0] == "GOPROXY="+testRegistry+",off": + lastRegistry, registry = i, registry+1 + case len(got) == 1 && got[0] == "GOPROXY="+PublicGoProxy && firstPublic < 0: + firstPublic = i + } + } + if registry != 2 || firstPublic < 0 || lastRegistry > firstPublic { + t.Errorf("%d downloads from the seat, the last at %d, the first public at %d: want both directories' seat downloads before every public one:\n%s", registry, lastRegistry, firstPublic, lines) + } + env := strings.Join(m.goEnv(), " ") + if got := proxyValues(m.goEnv()); len(got) != 1 || got[0] != "GOPROXY=off" || !strings.Contains(env, "GONOSUMDB=git.novox.be") { + t.Errorf("a step's environment says GOPROXY %v, want off once, and GONOSUMDB=git.novox.be: %s", got, env) + } if downloads != 2 || verifies != 2 { t.Errorf("%d downloads and %d verifies, want 2 each (go.mod and sub/dir/go.mod):\n%s", downloads, verifies, lines) } @@ -265,18 +319,18 @@ func TestAVerifyThatFailsEndsTheStepNamingTheDirectoryAndTheLine(t *testing.T) { loadedModuleMark + "github.com/nats-io/nats.go v1.54.0\n", tagged: loadedModuleMark + "github.com/nats-io/nats-server/v2 v2.11.17\n", files: map[string]string{ - "tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n", + "tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n", "tools/go.sum": "github.com/nats-io/nats.go v1.54.0 h1:a=\ngithub.com/nats-io/nats.go v1.54.0/go.mod h1:b=\n", }, want: []string{"tools", "go.mod: require github.com/nats-io/nats-server/v2 v2.11.17", "go.sum: github.com/nats-io/nats-server/v2 v2.11.17 h1:", "go.sum: github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:"}, notWant: "nats.go"}, // Issue 1966's kind: a mesh module reached only through another, which go.mod does not require, is lacked at the zero - // version (ADR 0573 §2); one go.mod names at a commit (§4) is not. + // version (ADR 0573 §2); one go.mod requires is not. {name: "a mesh module the load reaches is not required", ran: "tools list -e -deps -test", out: loadedModuleMark + seatPkg + " " + zeroVersion + "\n" + - loadedModuleMark + "git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n", - files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n"}, + loadedModuleMark + "git.novox.be/novox/mesh-sdk/go " + zeroVersion + " /tree/sdk \n", + files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n"}, want: []string{"tools", "go.mod: require " + seatPkg + " " + zeroVersion}, notWant: "mesh-sdk"}, } { t.Run(c.name, func(t *testing.T) { @@ -296,8 +350,9 @@ func TestAVerifyThatFailsEndsTheStepNamingTheDirectoryAndTheLine(t *testing.T) { return forgekey.Ran{} }} m, states := fetchModule(t, f) - // Asked for the module of tools, as a build is for one module (A-447b). - if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-sdk", "commit": commitSHA, "dir": "tools"}); err != nil { + // Asked for the module of tools, as a build is for one module (A-447b), of a repository other than mesh-sdk's, + // whose packages its go.mod requires: one of its own repository is built from the tree (S31). + if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA, "dir": "tools"}); err != nil { t.Fatal(err) } st := states.waitEnd(t) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go b/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go index a54618ce4..8b6fbd31d 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go @@ -151,19 +151,23 @@ func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *test // detected-steps: the state of the verb steps (design 47 G §326, §414), asked by the template state. // kept-builds: the builds kept for the artifact store's holder (keptbuilds.go), by the template objects (W12.5). kept := map[string]any{"name": "kept-builds", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024)}} - // outputs: a run's answer over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313). - outputs := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256)}} - detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1)}} + // steps: a step's end over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313; + // H2 H-A-412 addendum), read by the verb answer. + steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(128)}} + // outputs: a run's test output, read by the verb output (design 47 H2 §791, §820: 1 GiB, 7 days). + outputs := map[string]any{"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}} + detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1), "max-mib": float64(8)}} // The findings are asked in requires as a part that is no foundation part asks them (design 47 G §529, A-30). - findings := map[string]any{"name": "findings", "storage": "key-value", "template": "state"} + findings := map[string]any{"name": "findings", "storage": "key-value", "template": "state", "options": map[string]any{"max-mib": float64(8)}} findingEvents := map[string]any{"name": "finding-events", "storage": "stream", "template": "events", "options": map[string]any{ - "events": []any{"finding-written.*", "finding-cleared.*", "findings-stated.*"}, "max-age-days": float64(7), "max-mib": float64(16)}} - if want := []any{outputs, detected, kept, "artifact-store", "forge-account", "go-toolchain", "go-package-registry", "node-tools", findings, findingEvents}; !reflect.DeepEqual(m.Requires, want) { + "events": []any{"finding-written.*", "finding-cleared.*", "findings-stated.*"}, "max-age-days": float64(7), "max-mib": float64(8)}} + if want := []any{steps, detected, outputs, kept, "artifact-store", "forge-account", "go-toolchain", "go-package-registry", "node-tools", findings, findingEvents}; !reflect.DeepEqual(m.Requires, want) { t.Errorf("requires = %v, want %v", m.Requires, want) } keeps := false for _, s := range m.State { - if s == "keys" { + // Design 47 H2 H-A-411 (2): every state names its cap, 8 MiB. + if e, _ := s.(map[string]any); e["name"] == "keys" && e["max-mib"] == float64(8) { keeps = true } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/gomoddirs_test.go b/modules/mesh-build-go/cmd/mesh-build-go/gomoddirs_test.go index 1a7a8d429..78d4c1a43 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/gomoddirs_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/gomoddirs_test.go @@ -58,7 +58,7 @@ func TestAFetchAskedWithADirectoryChoosesItsModuleAndWhatItReplacesAlone(t *test {"seats", []string{"seats/a", "seats/b"}}, // a go.mod per seat, none in seats itself {".", []string{"."}}, // the root holds a go.mod {"rootless/x", []string{"rootless/x/go"}}, // Go code lies in go/ - {"modules/none", nil}, // chooses no Go module: an error naming it + {"modules/none", []string{}}, // chooses no Go module: an empty scope (H-A-371) } { tree := t.TempDir() for d, body := range mods { @@ -69,13 +69,7 @@ func TestAFetchAskedWithADirectoryChoosesItsModuleAndWhatItReplacesAlone(t *test t.Fatal(err) } } - got, err := scopedDirs(tree, cleanDir(c.dir), all) - if c.want == nil { - if err == nil || !strings.Contains(err.Error(), c.dir) { - t.Errorf("dir %q chose %v, %v; want an error naming it", c.dir, got, err) - } - continue - } + got, err := scopedDirs(tree, cleanDir(c.dir), nil, all) if err != nil || !reflect.DeepEqual(got, c.want) { t.Errorf("dir %q chooses %v, %v; want %v", c.dir, got, err, c.want) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/imports.go b/modules/mesh-build-go/cmd/mesh-build-go/imports.go index f7d7aa10b..0520d13bc 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/imports.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/imports.go @@ -1,10 +1,12 @@ package main -// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which mesh packages the module's Go programs -// import, so the indexer can take the fingerprint over those packages' content and no other. It is `go list -deps` of -// each Go bundle artifact's program, the tests left out, kept to the packages of the mesh's forge that lie outside the -// module's own directory (a sibling package of the module's own repository counts, a package under the module itself -// comes with its tree). +// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which packages the module's Go programs +// import, so the indexer can take the fingerprint over the ones a module of the module graph publishes and no other. It +// is `go list -deps` of each Go bundle artifact's program and of the packages each Go package artifact's paths hold +// (design 47 H2 H-A-532 DQ-5), the tests left out: the import path of every package of the import closure (H-A-517, +// H-A-541) but the standard library's, with no prefix telling a mesh package apart (H-A-539: mesh modules come from the +// seat go-package-registry), and none of the module's own (its main module, or a module that lies under its own +// directory, which comes with its tree). import ( "context" @@ -14,7 +16,6 @@ import ( "slices" "strings" - trunk "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/forgekey" ) @@ -27,8 +28,9 @@ type ImportsResult struct { func (m *Module) importsTool() StepTool { return StepTool{ Name: ImportsTool, - Description: "Read the mesh packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " + - "bundle artifact, without tests, kept to the forge's packages outside the module's own directory, sorted and each once. " + + Description: "Read the packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " + + "bundle artifact and of the packages each Go package artifact's paths hold, without tests, the import path of every " + + "package but the standard library's and the module's own, sorted and each once. " + "It is what a build says at its end for the fingerprint (ADR 0593 §2). Read-only.", Input: map[string]any{ "type": "object", @@ -65,27 +67,49 @@ func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) if err != nil { return nil, err } - return ModuleImports(ctx, run, m.buildEnv(dir), dir, manifest) + return ModuleImports(ctx, run, m.buildEnv, dir, manifest) } -// ModuleImports are the mesh packages the Go bundle artifacts of manifest, in the module directory dir, import. -func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) { +// ModuleImports are the packages the Go bundle and package artifacts of manifest, in the module directory dir, import: +// one sorted union of import paths (design 47 H2 H-A-518, H-A-541), the standard library, the tests and the module's +// own left out. Each listing runs with env of the directory it runs in, the environment the build gives that directory +// (its own module file of the fetch's pins, and the tree a module of the module's own repository is built from; design +// 47 H2 H-A-633), never one environment for them all. +func ModuleImports(ctx context.Context, run forgekey.Runner, env func(dir string) []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) { seen := map[string]bool{} if manifest.Build != nil { for _, a := range manifest.Build.Artifacts { - if a.Kind != "bundle" || a.Language != "go" || strings.TrimSpace(a.From) == "" { + if a.Language != "go" { continue } - r := run(ctx, env, "go", "-C", dir, "list", "-deps", "-f", "{{.ImportPath}} {{.Dir}}", "./"+strings.Trim(a.From, "./")) - if r.Status != 0 || r.Err != "" { - return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout)) + // A bundle lists its program; a package (design 47 H2 H-A-532 DQ-5) lists every package each of its paths + // holds, in the Go module that path is, so a contracts module reports its import set too. + var lists [][2]string + switch a.Kind { + case "bundle": + if strings.TrimSpace(a.From) != "" { + lists = append(lists, [2]string{dir, "./" + strings.Trim(a.From, "./")}) + } + case "package": + for _, p := range a.Paths { + if strings.TrimSpace(p) != "" { + lists = append(lists, [2]string{filepath.Join(dir, filepath.FromSlash(strings.Trim(p, "./"))), "./..."}) + } + } } - for _, l := range strings.Split(r.Stdout, "\n") { - pkg, where, ok := strings.Cut(strings.TrimSpace(l), " ") - if !ok || !meshPackage(pkg) || ownedBy(dir, where) { - continue + for _, l := range lists { + r := run(ctx, env(l[0]), "go", "-C", l[0], "list", "-deps", "-f", listFormat, l[1]) + if r.Status != 0 || r.Err != "" { + return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout)) + } + for _, line := range strings.Split(r.Stdout, "\n") { + //

; a package of the standard library has no module. + f := strings.Fields(line) + if len(f) != 4 || f[3] == "true" || ownedBy(dir, f[1]) { + continue + } + seen[f[0]] = true } - seen[pkg] = true } } } @@ -94,16 +118,12 @@ func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir s out = append(out, p) } slices.Sort(out) - if err := trunk.CheckImports(out); err != nil { - return ImportsResult{}, err - } return ImportsResult{Imports: out}, nil } -func meshPackage(pkg string) bool { - _, _, ok := trunk.PackageRepository(pkg) - return ok -} +// listFormat is what go list says of each package a program reaches: its import path, its directory and, outside the +// standard library, its module's path and whether that is the main module. +const listFormat = "{{.ImportPath}} {{.Dir}}{{with .Module}} {{.Path}} {{.Main}}{{end}}" // ownedBy says the package directory where lies under the module directory dir and is not a vendored copy. func ownedBy(dir, where string) bool { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/imports_test.go b/modules/mesh-build-go/cmd/mesh-build-go/imports_test.go index 76227e405..66fcef796 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/imports_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/imports_test.go @@ -12,33 +12,39 @@ import ( "git.novox.be/novox/mesh-sdk/go/forgekey" ) -// ADR 0593 §2 (C3): a fixture whose program imports announce, a sibling package of its own repository and a package of its -// own directory reports the first two; a test's import never appears (go list is run without -test), and the standard -// library, a package of another host and the module's own packages are left out. -func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) { +// noEnv is the environment of a listing a test's fake compiler reads nothing from. +func noEnv(string) []string { return nil } + +// ADR 0593 §2 (C3), design 47 H2 H-A-517, H-A-539, H-A-541: a fixture whose program imports packages of other Go +// modules reports the import path of each package, whatever its host (a mesh module comes from the seat +// go-package-registry, never told apart by a forge prefix): a sibling module's package and an outside package count, +// each once; the standard library (no module), the module's own packages (its main module, or a module under its own +// directory) and a test's import (go list runs without -test) are left out. +func TestModuleImportsAreTheModulesItsBuildResolved(t *testing.T) { dir := "/w/ws1/tree/modules/demo" var line string run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { line = name + " " + strings.Join(args, " ") return forgekey.Ran{Stdout: strings.Join([]string{ "fmt /usr/lib/go/src/fmt", - "git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce", - "git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce", - "git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib", - "git.novox.be/novox/mesh-catalog/modules/demo/internal/own " + dir + "/internal/own", - "git.novox.be/novox/mesh-sdk/go/vendored " + dir + "/vendor/git.novox.be/novox/mesh-sdk/go/vendored", - "github.com/nats-io/nats.go /cache/nats.go", + "git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce git.novox.be/novox/mesh-sdk/go false", + "git.novox.be/novox/mesh-sdk/go/busstate /cache/mesh-sdk@v1/go/busstate git.novox.be/novox/mesh-sdk/go false", + "git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib git.novox.be/novox/mesh-catalog/modules/sibling/lib false", + "demo/internal/own " + dir + "/internal/own demo true", + "git.novox.be/novox/mesh-catalog/modules/demo/inner " + dir + "/inner git.novox.be/novox/mesh-catalog/modules/demo/inner false", + "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false", }, "\n")} } m, err := catalogue.Decode([]byte(`{"module":"demo","version":"1","build":{"artifacts":[` + goBundle + `,{"name":"files","kind":"archive","from":"files"}]}}`)) if err != nil { t.Fatal(err) } - got, err := ModuleImports(context.Background(), run, nil, dir, m) + got, err := ModuleImports(context.Background(), run, noEnv, dir, m) if err != nil { t.Fatal(err) } - want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", "git.novox.be/novox/mesh-sdk/go/vendored"} + want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", + "git.novox.be/novox/mesh-sdk/go/busstate", "github.com/nats-io/nats.go"} if !slices.Equal(got.Imports, want) { t.Errorf("imports %v, want %v", got.Imports, want) } @@ -60,4 +66,116 @@ func TestImportsStepReadsTheWorkspace(t *testing.T) { if got := out.(ImportsResult).Imports; len(got) != 0 { t.Errorf("a fake compiler's go list names no package, and the answer was %v", got) } + + // Issue 1984 (design 47 H2 H-A-633): each listing runs with the environment the build gives its directory. A + // package path's Go module requires a module of its own repository at the zero version, which only the path's own + // temporary modfile of the fetch (its replace to the tree) resolves; the module directory's environment names no + // such modfile, and Go's lookup is shut off (GOPROXY=off), as main.510 met on mesh-delivery-contracts' paths. + t.Run("a path resolved only through its own module file", func(t *testing.T) { + const sdk = "git.novox.be/novox/mesh-delivery/modules/demo-sdk" + pkg := `{"name":"clients","kind":"package","language":"go","paths":["go/clients/registry"],"series":"0.1"}` + m, _, _ := buildModule(t, manifestWith(pkg), "x") + tree := filepath.Join(m.Work, "ws1", "tree", "modules") + path, own := filepath.Join(tree, "demo", "go", "clients", "registry"), filepath.Join(tree, "demo-sdk") + for dir, body := range map[string]string{ + path: "module git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry\n\nrequire " + sdk + " " + zeroVersion + "\n", + own: "module " + sdk + "\n", + } { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + // What the fetch does for a same-repository requirement: a modfile of the path's directory replacing the module. + if err := m.replaceInModfile(path, sdk, own); err != nil { + t.Fatal(err) + } + // Go, as far as the listing needs it: the module file it reads is the one -modfile names, else the directory's + // own go.mod, and a required module no replace of that file points at is looked up, which GOPROXY=off refuses. + m.Run = throughBubblewrap(t, func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { + modfile := filepath.Join(args[1], "go.mod") + for _, e := range env { + if flags, ok := strings.CutPrefix(e, "GOFLAGS="); ok { + for _, f := range strings.Fields(flags) { + if file, ok := strings.CutPrefix(f, "-modfile="); ok { + modfile = file + } + } + } + } + body, err := os.ReadFile(modfile) + if err != nil { + return forgekey.Ran{Status: 1, Stderr: err.Error()} + } + if !strings.Contains(string(body), "replace "+sdk+" => "+own) { + return forgekey.Ran{Status: 1, Stderr: "go: " + sdk + "@" + zeroVersion + ": module lookup disabled by GOPROXY=off"} + } + return forgekey.Ran{Stdout: strings.Join([]string{ + "git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry " + path + " git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry true", + sdk + "/buildstep " + own + "/buildstep " + sdk + " false", + "git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false", + }, "\n")} + }, &[]shutOff{}) + out, err := m.imports(context.Background(), map[string]any{"workspace": "ws1", "module": "modules/demo"}) + if err != nil { + t.Fatal(err) + } + want := []string{sdk + "/buildstep", "git.novox.be/novox/mesh-sdk/go/stdio"} + if got := out.(ImportsResult).Imports; !slices.Equal(got, want) { + t.Errorf("imports %v, want %v: the sibling module's imports as the path's own module file resolves them", got, want) + } + }) +} + +// G2 (design 47 H2 H-A-532 DQ-5, H-A-518, H-A-541): a Go package artifact reports the packages the packages its paths +// hold import, listed in the Go module each path is, without tests and without the module's own directory; a module +// with both kinds reports one sorted union. +func TestAPackageArtifactReportsItsImportSet(t *testing.T) { + dir := "/w/ws1/tree/modules/contracts" + pkg := `{"name":"seat","kind":"package","language":"go","paths":["go/seats/demo"],"series":"0.1"}` + listed := map[string]string{ + dir + "/go/seats/demo ./...": strings.Join([]string{ + "encoding/json /usr/lib/go/src/encoding/json", + "git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo " + dir + "/go/seats/demo git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo true", + "git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false", + }, "\n"), + dir + " ./cmd/demo-tools": "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false", + } + for _, c := range []struct { + name string + artifacts string + want []string + }{ + // G2/AC1: a contracts module whose artifact is of kind package. + {"package", pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio"}}, + // G2/AC2: a module with a bundle and a package reports one sorted union. + {"both", goBundle + "," + pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio", "github.com/nats-io/nats.go"}}, + } { + t.Run(c.name, func(t *testing.T) { + run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { + line := args[1] + " " + args[len(args)-1] + if slices.Contains(args, "-test") || args[2] != "list" { + t.Errorf("go ran as %v: it lists dependencies without tests", args) + } + out, ok := listed[line] + if !ok { + t.Errorf("go list in %q, not asked", line) + } + return forgekey.Ran{Stdout: out} + } + m, err := catalogue.Decode([]byte(`{"module":"contracts","version":"1","build":{"artifacts":[` + c.artifacts + `]}}`)) + if err != nil { + t.Fatal(err) + } + got, err := ModuleImports(context.Background(), run, noEnv, dir, m) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(got.Imports, c.want) { + t.Errorf("imports %v, want %v", got.Imports, c.want) + } + }) + } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/installed_toolchain_test.go b/modules/mesh-build-go/cmd/mesh-build-go/installed_toolchain_test.go index e1fe33d8c..ec1b45bd9 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/installed_toolchain_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/installed_toolchain_test.go @@ -45,6 +45,13 @@ func TestEveryStepEnvironmentSaysGotoolchainLocal(t *testing.T) { if got := toolchainValues(env); len(got) != 1 || got[0] != "GOTOOLCHAIN=local" { t.Errorf("%s: GOTOOLCHAIN settings %v, want exactly GOTOOLCHAIN=local", name, got) } + // H-A-494: a step's own go commands reach no proxy (the test and lint steps, the compile); only the fetch's two + // downloads do, each with its own. + if strings.HasPrefix(name, "goEnv") { + if got := proxyValues(env); len(got) != 1 || got[0] != "GOPROXY=off" { + t.Errorf("%s: GOPROXY settings %v, want exactly GOPROXY=off", name, got) + } + } // Issue 1806: and its threads, its part of the node's processor cap (probeEnv runs no build). if procs := strings.Count(strings.Join(env, "\n"), "GOMAXPROCS="); name != "probeEnv" && procs != 1 { t.Errorf("%s: GOMAXPROCS said %d times, want once: %v", name, procs, env) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/integration.go b/modules/mesh-build-go/cmd/mesh-build-go/integration.go index cfa51ba98..9a12ed5a8 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/integration.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/integration.go @@ -34,7 +34,8 @@ func (m *Module) integrationBounds() Bounds { return b } -func (m *Module) integration(ctx context.Context, workspace, tree string, packages []string, pattern string) (res *TestResult, err error) { +// integration runs the level judged by b, the integration bounds at the step's start (H-A-488). +func (m *Module) integration(ctx context.Context, workspace, tree string, packages []string, pattern string, b Bounds) (res *TestResult, err error) { major, err := m.checkPostgres(ctx) if err != nil { return nil, err // a *steprun.Refusal: this level only @@ -42,14 +43,14 @@ func (m *Module) integration(ctx context.Context, workspace, tree string, packag if !m.Inside { // The store, the bus and the tests run together in one shut-off process (level.go), so the tests reach the // level's own store and bus and nothing else. - return m.integrationShutOff(ctx, workspace, packages, pattern) + return m.integrationShutOff(ctx, workspace, packages, pattern, b) } - return m.integrationHere(ctx, workspace, tree, packages, pattern, major) + return m.integrationHere(ctx, workspace, tree, packages, pattern, major, b) } // integrationHere is the level itself, in the shut-off process: the store and the bus started for the run, the tests // compiled and run against them, both stopped and the run's directory removed however it ends. -func (m *Module) integrationHere(ctx context.Context, workspace, tree string, packages []string, pattern string, major int) (res *TestResult, err error) { +func (m *Module) integrationHere(ctx context.Context, workspace, tree string, packages []string, pattern string, major int, b Bounds) (res *TestResult, err error) { run := filepath.Join(m.Work, workspace, "run-"+sdkstep.NewID()) if err := os.MkdirAll(run, 0o700); err != nil { return nil, err @@ -90,7 +91,7 @@ func (m *Module) integrationHere(ctx context.Context, workspace, tree string, pa return m.runLevel(ctx, tree, levelOpts{ workspace: workspace, run: pattern, - level: LevelIntegration, tags: integrationTags, packages: packages, bounds: m.integrationBounds(), + level: LevelIntegration, tags: integrationTags, packages: packages, bounds: b, env: env, setup: setup, wall: true, store: "postgres " + strconv.Itoa(major), bus: "nats-server " + m.Recipe.NatsServer, diff --git a/modules/mesh-build-go/cmd/mesh-build-go/integration_level_test.go b/modules/mesh-build-go/cmd/mesh-build-go/integration_level_test.go index 49889ee94..3f7c9facf 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/integration_level_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/integration_level_test.go @@ -256,6 +256,22 @@ func TestSetupAndRunningTimeAreJudgedApart(t *testing.T) { if res, _ = runLevelTool(t, m, states, "integration"); !res.Passed || res.OverBound || res.Setup != 29 || res.Elapsed != 59 { t.Errorf("29 s of setup and 59 s of running are within both bounds: %+v", res) } + + // Design 47 H2 H-A-488: with four steps in hand at the step's start, the bounds are four times their defaults: the + // tests get 240 s as their level's bound, the 35 s setup is within its 120 s, and the result names both. + k := newIntegFake(t, "slow") + k.advance["compile"], k.advance["start"] = 20*time.Second, 15*time.Second + m, states = integModule(t, k) + m.inHand = func() int { return 4 } + res, _ = runLevelTool(t, m, states, "integration") + if !res.Passed || res.OverBound || res.Setup != 35 || res.Bound != 240 || res.SetupBound != 120 { + t.Errorf("a setup of 35 s with four steps in hand: %+v", res) + } + for _, c := range k.calls { + if strings.Contains(c.line, " -json ") && !strings.Contains(strings.Join(c.env, " "), "MESH_TEST_LEVEL_BOUND=4m0s") { + t.Errorf("%s ran without the level's bound of 240 s: %v", c.line, c.env) + } + } } // 1486/AC5: a run that fails, and a run that panics: the store is stopped, the bus is stopped, the run's directory is @@ -290,7 +306,7 @@ func TestAFailedOrPanickedRunStopsTheServersAndRemovesTheRunDirectory(t *testing m, _ = integModule(t, g) func() { defer func() { recover() }() - m.integration(context.Background(), "ws1", filepath.Join(m.Work, "ws1", "tree"), nil, "") + m.integration(context.Background(), "ws1", filepath.Join(m.Work, "ws1", "tree"), nil, "", m.integrationBounds()) }() checkCleaned(g, m) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/isolate_test.go b/modules/mesh-build-go/cmd/mesh-build-go/isolate_test.go index 4ef09ae75..c3e9920df 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/isolate_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/isolate_test.go @@ -167,7 +167,7 @@ func TestABuildRunsShutOffAndOnlyATrunkBuildWritesTheCaches(t *testing.T) { var seen []shutOff m.Run = throughBubblewrap(t, m.Run, &seen) run := stepTool(t, m, "build_go_build") - args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": "tools"} + args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": "tools", "version": askedVersion} if publish { args["publish"] = true } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go b/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go index 8a996b309..fc8ed61e9 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go @@ -3,12 +3,17 @@ package main import ( "context" "encoding/json" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" - "git.novox.be/novox/mesh-sdk/go/forgekey" + "errors" + "os" + "path/filepath" "strings" "testing" "time" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/buscalls" + "git.novox.be/novox/mesh-sdk/go/forgekey" + buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance" @@ -40,6 +45,30 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // ADR 0664 §1 (issue 1748): the module's own paths from a failed fetch or download to its step's error say a network that did // not answer as a transport fault, and a failure of the source (an unknown revision, a checksum) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { + // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its + // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + t.Run("again-delays is declared and read", func(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + var m struct { + Config map[string]json.RawMessage `json:"config"` + } + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + var c struct { + Default string `json:"default"` + Runtime bool `json:"runtime"` + } + decl, ok := m.Config[steprun.AgainDelaysSetting] + _ = json.Unmarshal(decl, &c) + delay, err := steprun.AgainDelays(c.Default) + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) + } + }) conformance.Passing(t, []string{conformance.GitFetch, conformance.GoDownload}, func(runner, words string) error { switch runner { case conformance.GitFetch: @@ -56,3 +85,39 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { } }) } + +// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or +// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met. +func TestTheStepsCanSayAStepsEnd(t *testing.T) { + conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil)) + // Design 47 H2 §791, §801, H-A-412, H-A-421: the seat's verbs current, output and answer keep the build-step part's form 2, + // and a pipeline step's run output is kept in the module's outputs objects and read back through output. + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }, Outputs: kitObjects{}} + conformance.SeatVerbs(t, Seat, m.SeatTools(m.Puller(nil, steprun.NewFakeAsks())), m.askSteps(nil)) +} + +// kitObjects is an outputs store in memory, for the kit's SeatVerbs. +type kitObjects map[string][]byte + +func (k kitObjects) Put(name string, data []byte, _ string) (buscalls.ObjectInfo, error) { + k[name] = data + return buscalls.ObjectInfo{Name: name}, nil +} + +func (k kitObjects) Get(name string) (buscalls.ObjectData, error) { + d, ok := k[name] + if !ok { + return buscalls.ObjectData{}, errors.New("object not found") + } + return buscalls.ObjectData{Data: d}, nil +} + +// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before +// it ran is no run), so the poison rule never ends an ask that never ran. +func TestThePullerCountsRunsThatStarted(t *testing.T) { + conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller { + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }} + m.ReadSteps = StateRead{Get: read} + return m.Puller(nil, steprun.NewFakeAsks()) + }) +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/level.go b/modules/mesh-build-go/cmd/mesh-build-go/level.go index 1c50743f4..5a1e66b3e 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/level.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/level.go @@ -65,13 +65,12 @@ func (m *Module) executable() (string, error) { return filepath.EvalSymlinks(exe) } -// integrationShutOff runs the integration level in one shut-off process of this program and reads its answer. -func (m *Module) integrationShutOff(ctx context.Context, workspace string, packages []string, pattern string) (*TestResult, error) { +// integrationShutOff runs the integration level, judged by b, in one shut-off process of this program and reads its answer. +func (m *Module) integrationShutOff(ctx context.Context, workspace string, packages []string, pattern string, b Bounds) (*TestResult, error) { exe, err := m.executable() if err != nil { return nil, fmt.Errorf("the integration level's program: %w", err) } - b := m.integrationBounds() a, err := m.shutOff(ctx, exe, levelSpec{Step: stepIntegration, Workspace: workspace, Packages: packages, Run: pattern, Setup: b.Setup, Bound: b.Run}) if err != nil { return nil, err @@ -239,7 +238,7 @@ func (m *Module) answer(ctx context.Context, spec levelSpec) levelAnswer { if err != nil { return levelAnswer{Error: err.Error()} } - res, err := m.integrationHere(ctx, spec.Workspace, tree, spec.Packages, spec.Run, major) + res, err := m.integrationHere(ctx, spec.Workspace, tree, spec.Packages, spec.Run, major, m.integrationBounds()) if err != nil { return levelAnswer{Error: err.Error()} } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/levels.go b/modules/mesh-build-go/cmd/mesh-build-go/levels.go index 1233b5d0c..13662ffe9 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/levels.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/levels.go @@ -6,6 +6,7 @@ package main // step that could not run. import ( + "encoding/json" "fmt" "sort" "strings" @@ -31,6 +32,11 @@ type Bounds struct { Setup, Run time.Duration } +// times is the bounds of a level run while n steps are in hand (design 47 H2 H-A-488): each its default n times. +func (b Bounds) times(n int) Bounds { + return Bounds{Setup: b.Setup * time.Duration(n), Run: b.Run * time.Duration(n)} +} + // PackageResult, TestTime and Failure are the SDK's failure contract (buildstep, issue 1901), with the JSON names this // module always sent: a Failure names its test, its file, its cause (never empty, never a passing line) and its own // output up to 4096 bytes, cause first. @@ -59,6 +65,14 @@ type TestResult struct { SetupBound float64 `json:"setup_bound,omitempty"` Slowest []TestTime `json:"slowest,omitempty"` Failed []Failure `json:"failed,omitempty"` + // NotRun are the tests that said they did not run (`t.Skip("NOT RUN: ")`), each with its reason (design 47 H2 + // §800, H-A-294): counted apart from passed and failed, they leave the level passing, listed here, where the delivery + // SDK's test step reads them into the step's end. + NotRun []sdkstep.NotRun `json:"not-run,omitempty"` + // Output is the level's text (design 47 H2 §791, H-A-412 second addendum (a)): the Output lines of test2json, of + // every go.mod directory in the order they were tested. The delivery SDK's step run takes it out of the answer and + // keeps it as the run's output in the outputs objects; it is never part of a check's answer. + Output string `json:"output,omitempty"` // Store and Bus are what the integration level ran against: the postgres major version and the nats-server // version (ADR 0470 §4). // OverBound says a bound was kept no longer, and OverWhich which: setup, run or both. The level's verdict, Passed, is @@ -78,6 +92,21 @@ type TestResult struct { By string `json:"by,omitempty"` } +// goTestText is the text of `go test -json`'s output out: the Output of each of its events, in order (H-A-412 (a)); a line +// that is no event is none of it. +func goTestText(out string) string { + var text strings.Builder + for line := range strings.Lines(out) { + var ev struct { + Output string `json:"Output"` + } + if json.Unmarshal([]byte(line), &ev) == nil { + text.WriteString(ev.Output) + } + } + return text.String() +} + // readGoTest reads one go.mod directory's `go test -json` into res through the SDK's reader (issue 1901: one failure // contract for every build module, sdkstep.Failure), and answers the lines that were no event and how many packages // it named. @@ -86,6 +115,7 @@ func readGoTest(res *TestResult, dir, out string) (noise []string, packages int) res.Tests += read.Tests res.Skipped += read.Skipped res.Failed = append(res.Failed, read.Failed...) + res.NotRun = append(res.NotRun, read.NotRun...) res.Packages = append(res.Packages, read.Packages...) res.Slowest = append(res.Slowest, read.Times...) res.Elapsed = max(res.Elapsed, read.Elapsed) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/main.go b/modules/mesh-build-go/cmd/mesh-build-go/main.go index 7886aaca6..6fe0401ab 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/main.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/main.go @@ -44,7 +44,7 @@ func main() { Toolchains: stdio.State(seat.StateToolchains).Put, SayToolchain: stdio.SeatPublish, Steps: stdio.State(seat.StateSteps).Put, - Detected: stdio.State(seat.StateDetectedSteps).Put, + Detected: prunedDetected().Put, ReadDetected: readOf(stdio.State(seat.StateDetectedSteps)).Get, ForgetDetected: stdio.State(seat.StateDetectedSteps).Delete, RecordAct: handActRecorder, @@ -70,7 +70,7 @@ func main() { m.ReadEntry = askEntry m.AskInput = stdio.Ask m.KeptBuilds = busstate.ObjectsOf(KeptBuildsStore) - m.Outputs = busstate.ObjectsOf(steprun.OutputsStore) + m.Answers = busstate.ObjectsOf(steprun.AnswersStore) m.Self = strings.TrimSpace(os.Getenv("MESH_MODULE")) m.Probe = ProbeGo(m.Home, m.Cache) m.Bubblewrap = ProbeBubblewrap @@ -102,6 +102,14 @@ func main() { steps := m.StepTools() booted := time.Now() puller := m.Puller(steps, nil) + // A step whose fetch or publish met its holder away is given again after again-delays (design 47 H2 §799; H-A-390). + againSetting, _ := stdio.Setting(steprun.AgainDelaysSetting) + againDelay, againErr := steprun.AgainDelays(againSetting) + if againErr != nil { + logf("the setting %s: %v", steprun.AgainDelaysSetting, againErr) + os.Exit(1) + } + puller.Delay = againDelay m.Held = puller if m.Node != "" { // A step a previous process left running is ended (issue 1890): one that names another owner, or none and diff --git a/modules/mesh-build-go/cmd/mesh-build-go/manifest_test.go b/modules/mesh-build-go/cmd/mesh-build-go/manifest_test.go index dd8db4984..a9a75d265 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/manifest_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/manifest_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -157,6 +158,16 @@ func TestGiteaReadsTheBuildModulesKeys(t *testing.T) { t.Errorf("gitea reads %v, lacks %s", gitea.Reads, want) } } + // H-A-453 (2): the forge module's internal/seatgit, which no Go artifact's from holds, takes the manifest's own + // check-needs, so its whole test is asked of a node with the Node build seat and given the Node build module's install. + root, err := filepath.Abs(catalogueRoot) + if err != nil { + t.Fatal(err) + } + if needs, err := readNeeds(root, filepath.Join(root, "modules", "gitea", "internal", "seatgit")); err != nil || + !slices.Equal(needs, []string{sdkstep.NeedNodeBuildNode}) { + t.Errorf("the forge module's seatgit package needs %v (%v), want %s", needs, err, sdkstep.NeedNodeBuildNode) + } } // 1309-S1: every run step runs in bubblewrap, so the module declares its package (the lead's decision: each build module @@ -195,6 +206,16 @@ func TestTheModuleInvokesTheArtifactSeatsVerbsAndWritesNoStore(t *testing.T) { if !slices.Contains(m.Consumes, "mesh-conditions.findings-asked") { t.Errorf("consumes %v lack mesh-conditions.findings-asked", m.Consumes) } + // Design 47 G A-488a, A-488b: its runtime follows the seat list, so the module consumes the seat's two events (which makes its + // durable consumer) and invokes the verb that reads the list. + for _, ev := range []string{"mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed"} { + if !slices.Contains(m.Consumes, ev) { + t.Errorf("consumes %v lack %s", m.Consumes, ev) + } + } + if !slices.Contains(m.Invokes, "seat:mesh-catalog.seat-definitions") { + t.Errorf("invokes %v lack seat:mesh-catalog.seat-definitions", m.Invokes) + } // Not a foundation part, it asks its finding stream in requires, by the template events (design 47 G §529, A-30), and // declares no stream of that name. for _, st := range m.Streams { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/module.go b/modules/mesh-build-go/cmd/mesh-build-go/module.go index 38329cb9a..7fa2380dd 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/module.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/module.go @@ -25,9 +25,6 @@ const CheckRound = 10 * time.Minute // Module is the Go build module's one running state: the node it runs on, its recipe, the toolchain guard and the // states it writes (toolchains, steps). type Module struct { - // Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when - // the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163. - Callers func(kind string) ([]string, bool) // SayEvent publishes an event of the go build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the // puller's ask-taken, step-progress and step-ended (design 47 G §496, §602). SayEvent func(subject string, body any, id string) error @@ -86,9 +83,9 @@ type Module struct { // Inside is the integration level's own process, started shut off in bubblewrap by a test step (level.go): its // commands run as they are, never shut off a second time. Inside bool - // GoSeatFile is the binding of the provision go-package-registry, the Go seat's read side (design 51 *Go - // packages*): bound, the mesh's Go modules are fetched through it first, Go's public proxy second, and the forge's - // git over the account's ssh last (Go's direct, kept for this milestone only); unbound, as before, directly. + // GoSeatFile is the binding of the provision go-package-registry, the Go package registry seat's read side (design + // 51 *Go packages*): the mesh's Go packages are fetched through it alone (design 47 H, H-A-494); unbound, a fetch + // that needs one refuses (errNoRegistry). GoSeatFile string // ArtifactStoreFile is the binding of the provision artifact-store, read for a group run's package members (§465). ArtifactStoreFile string @@ -113,13 +110,15 @@ type Module struct { // when set, answers it instead (a test). Settings string Capacity func() int + // inHand answers how many steps the seat has in hand in place of Held's (a test's; design 47 H2 H-A-488). + inHand func() int // SayStep says a pipeline step's end (steprun.AskSteps.SayStep); the seat's publish on this node when nil. SayStep func(sdkstep.StepEnded) error // ReadEntry asks the seat mesh-catalog's verb entry for the catalog graph entry of one fingerprint, which a compose ask's // request names each manifest it gives by digest with (compose.go, design 47 G §615); GoModCache, when set, is the Go module cache in place of Cache's (a test). ReadEntry func(fingerprint string) (meshcat.CatalogEntry, error) // AskInput asks a seat verb the module invokes (module.json) as the runtime calls it (stdio.Ask): the verb a run ask's - // input names, answering the input by its digest (meshdeliverycheckerclient.ReadInput). + // input names, answering the input by its digest (the seat mesh-wants' verb input). AskInput func(key string, body any) (json.RawMessage, error) // PlaceHead, when set, lays a run's head at a directory instead of fetching it (a test). PlaceHead func(ctx context.Context, h sdkstep.RunHead, dir string) error @@ -127,7 +126,11 @@ type Module struct { // KeptBuilds is the object store of the builds kept for the artifact store's holder (keptbuilds.go); nil keeps none. // Self is this module's name as the runtime launched it (MESH_MODULE), the first part of the store's name on the bus. KeptBuilds KeptObjects - // Outputs is the object store of a run's answers over what step-ended carries inline (steprun.OutputsStore); nil keeps none. + // Answers is the steps state's objects (steprun.AnswersStore), where a step's end over what its key or step-ended + // carries is kept and the seat's verb answer reads it (design 47 H2 H-A-412 addendum); nil keeps none. + Answers steprun.OutputObjects + // Outputs are the outputs objects (steprun.OutputsStore) a test step keeps a run's output in, which the verb output + // reads (design 47 H2 §791); nil is the module's own on the bus (outputs), a test sets its own. Outputs steprun.OutputObjects Self string diff --git a/modules/mesh-build-go/cmd/mesh-build-go/module_test.go b/modules/mesh-build-go/cmd/mesh-build-go/module_test.go index fa17102e2..94e7d4549 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/module_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/module_test.go @@ -116,7 +116,7 @@ func TestAGoThatCannotBeRunRefusesEveryStepAndHealthIsUnhealthy(t *testing.T) { {Name: "short_probe", Run: run}, }, m.StepTools()...) for _, tool := range m.Tools(steps) { - if tool.Name == StatusTool || tool.Name == HealthTool || tool.Name == StepReadTool || tool.Name == StepsReadTool || tool.Name == ToolchainsReadTool || tool.Name == ReleaseTool || tool.Name == KeptTool || tool.Name == KeptDropTool || tool.Name == StepEndTool { + if strings.HasPrefix(tool.Name, ModuleName+"_state_") || tool.Name == StatusTool || tool.Name == HealthTool || tool.Name == StepReadTool || tool.Name == StepsReadTool || tool.Name == ToolchainsReadTool || tool.Name == ReleaseTool || tool.Name == KeptTool || tool.Name == KeptDropTool || tool.Name == StepEndTool { continue } var reason string diff --git a/modules/mesh-build-go/cmd/mesh-build-go/narrow.go b/modules/mesh-build-go/cmd/mesh-build-go/narrow.go new file mode 100644 index 000000000..0cfcbcf6b --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/narrow.go @@ -0,0 +1,252 @@ +package main + +import ( + "io/fs" + "maps" + "os" + "path" + "path/filepath" + "slices" + "strings" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// narrowedKeptAtRoot are what steprun.Narrow keeps beside the named paths, read from the request's directory: the +// manifest and its lock files. A request narrowed from the repository's root (narrowTree) keeps them at the root too, +// where the asked module's build names none of them; they are removed again. +var narrowedKeptAtRoot = []string{"module.json", "go.sum", "package-lock.json"} + +// narrowTree narrows the fetched tree for a build of an artifact that names its paths (ADR 0499 clause 4, +// steprun.Narrow). Beside the artifact's paths and the module's manifest, the workspace holds every generated-from +// directory an artifact of the module names, and the directory (with its go.mod) of every package of the same repository +// the artifact's go.mod requires at any version (S31), found by the manifests of that repository's modules; nothing else +// (design 47 H, lead answer H-A-136). A package of another repository comes published, as before (ADR 0573 §4). +func narrowTree(tree, repository string, req sdkstep.FetchRequest) error { + dir := cleanDir(req.Dir) + if dir == "" { + return steprun.Narrow(tree, req) // refused there: named paths without the module's directory + } + extra := generatedFromDirs(tree, dir) + extra = append(extra, ownPackageDirs(tree, repository, dir, req.Paths)...) + var outside []string + inside := slices.Clone(req.Paths) + for _, e := range extra { + if rel, ok := under(dir, e); ok { + if !slices.Contains(inside, rel) { + inside = append(inside, rel) + } + } else if !slices.Contains(outside, e) { + outside = append(outside, e) + } + } + if len(outside) == 0 { + r := req + r.Paths = inside + return steprun.Narrow(tree, r) + } + // A directory outside the module's own: the request is narrowed from the root, with every path the module's + // narrowing keeps named by its path from the root (the manifest and lock files only where the module has them). + all := []string{} + for _, p := range inside { + all = append(all, path.Join(dir, p)) + } + for _, f := range narrowedKeptAtRoot { + if _, err := os.Lstat(filepath.Join(tree, filepath.FromSlash(path.Join(dir, f)))); err == nil { + all = append(all, path.Join(dir, f)) + } + } + all = append(all, outside...) + if err := steprun.Narrow(tree, sdkstep.FetchRequest{Repository: req.Repository, Commit: req.Commit, Paths: all}); err != nil { + return err + } + for _, f := range narrowedKeptAtRoot { + if !slices.Contains(all, f) { + if err := os.RemoveAll(filepath.Join(tree, f)); err != nil { + return err + } + } + } + return nil +} + +// under answers p's path relative to dir when p is dir or lies under it. +func under(dir, p string) (string, bool) { + if dir == "." { + return p, true + } + if p == dir { + return ".", true + } + if rel, ok := strings.CutPrefix(p, dir+"/"); ok { + return rel, true + } + return "", false +} + +// generatedFromDirs are the generated-from directories (from the tree's root) the artifacts of the module in dir name +// (H-A-136): the seat definitions a generated package is compared against. A module at the repository's root keeps not +// its generated-from directory, which would be the whole repository, but the generator's inputs and outputs: the seats/ +// directory of each generated-from directory and the paths of every artifact of the module naming generated-from, as +// the generator's check reads every generated package (H-A-137). A manifest that is absent or unreadable names none; +// the steps that read it say so. +func generatedFromDirs(tree, dir string) []string { + raw, err := os.ReadFile(filepath.Join(tree, filepath.FromSlash(dir), "module.json")) + if err != nil { + return nil + } + man, err := catalogue.Decode(raw) + if err != nil || man.Build == nil { + return nil + } + var out []string + add := func(p string) { + if p == ".." || strings.HasPrefix(p, "../") || slices.Contains(out, p) { + return + } + if _, err := os.Lstat(filepath.Join(tree, filepath.FromSlash(p))); err == nil { // steprun.Narrow refuses a path the tree lacks + out = append(out, p) + } + } + for _, a := range man.Build.Artifacts { + g := strings.TrimSpace(a.GeneratedFrom) + if g == "" { + continue + } + if dir != "." { + add(path.Join(dir, filepath.ToSlash(g))) + continue + } + add(path.Join(filepath.ToSlash(g), "seats")) + for _, p := range a.Paths { + add(path.Clean(filepath.ToSlash(p))) + } + } + return out +} + +// ownPackageDirs are the directories (from the tree's root) of the packages of the checked repository (the fetch's +// repository, sameRepository) that a go.mod under the artifact's named paths requires, at whatever version it names them +// (H-A-136; ADR 0573 §2; design 47 H, S31), transitively: the go.mod of each such directory is read in turn for the +// packages of the repository it requires, each directory once (design 47 H, H-A-202, H-A-198). Each is found by the manifests of the repository's modules: a module's directory +// or the directory of one of its artifacts' paths whose go.mod declares the required module path. One no manifest leads +// to is left to the fetch's resolution, which fails naming it. +func ownPackageDirs(tree, repository, dir string, paths []string) []string { + want := map[string]bool{} + addReqs := func(raw []byte) { + required, _ := goModRequirements(string(raw)) + for module := range required { + if sameRepository(module, repository) { + want[module] = true + } + } + } + for _, p := range paths { + root := filepath.Join(tree, filepath.FromSlash(path.Join(dir, p))) + filepath.WalkDir(root, func(file string, e fs.DirEntry, err error) error { + if err != nil { + return nil + } + if e.IsDir() { + if n := e.Name(); n == ".git" || n == "vendor" || n == "node_modules" || n == "testdata" { + return filepath.SkipDir + } + return nil + } + if e.Name() != "go.mod" { + return nil + } + if raw, err := os.ReadFile(file); err == nil { + addReqs(raw) + } + return nil + }) + } + if len(want) == 0 { + return nil + } + byModule := map[string][]string{} // a module path and the manifest-named directories whose go.mod declares it + for _, cand := range manifestDirs(tree) { + if mod := goModulePath(filepath.Join(tree, filepath.FromSlash(cand), "go.mod")); mod != "" && !slices.Contains(byModule[mod], cand) { + byModule[mod] = append(byModule[mod], cand) + } + } + var out []string + done := map[string]bool{} + for len(want) > len(done) { + for _, mod := range slices.Sorted(maps.Keys(want)) { + if done[mod] { + continue + } + done[mod] = true + for _, cand := range byModule[mod] { + if slices.Contains(out, cand) { + continue + } + out = append(out, cand) + if raw, err := os.ReadFile(filepath.Join(tree, filepath.FromSlash(cand), "go.mod")); err == nil { + addReqs(raw) // what this package requires of the repository comes along (H-A-202) + } + } + } + } + slices.Sort(out) + return out +} + +// manifestDirs are the directories the manifests of the tree name, from its root: each module's directory and the +// directory of each of its artifacts' named paths. +func manifestDirs(tree string) []string { + var out []string + filepath.WalkDir(tree, func(file string, e fs.DirEntry, err error) error { + if err != nil { + return nil + } + if e.IsDir() { + if n := e.Name(); n == ".git" || n == "vendor" || n == "node_modules" || n == "testdata" { + return filepath.SkipDir + } + return nil + } + if e.Name() != "module.json" { + return nil + } + rel, err := filepath.Rel(tree, filepath.Dir(file)) + if err != nil { + return nil + } + mdir := filepath.ToSlash(rel) + out = append(out, mdir) + raw, err := os.ReadFile(file) + if err != nil { + return nil + } + man, err := catalogue.Decode(raw) + if err != nil || man.Build == nil { + return nil + } + for _, a := range man.Build.Artifacts { + for _, p := range a.Paths { + out = append(out, path.Join(mdir, filepath.ToSlash(p))) + } + } + return nil + }) + return out +} + +// goModulePath is the module path the go.mod file declares, "" when there is none. +func goModulePath(file string) string { + raw, err := os.ReadFile(file) + if err != nil { + return "" + } + for _, line := range strings.Split(string(raw), "\n") { + if f := strings.Fields(line); len(f) == 2 && f[0] == "module" { + return strings.Trim(f[1], `"`) + } + } + return "" +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/narrow_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/narrow_integration_test.go index e7ef09577..a976ccc1a 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/narrow_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/narrow_integration_test.go @@ -45,6 +45,28 @@ func TestAFetchWithNamedPathsNarrowsTheWorkspace(t *testing.T) { if strings.Join(res.Modules, ",") != "lib" { t.Errorf("the fetch answered the modules %v, want lib alone", res.Modules) } + // A tree shaped like mesh-delivery's: the narrowed artifact requires another module of its repository at the zero + // version: the narrowed workspace keeps its directory, found by its manifest, and the fetch resolves it there (design + // 47 H, H-A-136; live 2026-11-20, pipeline main.3). + const sdk = "git.novox.be/novox/narrowown/modules/sdk" + _, ownHead := f.repo("novox/narrowown", map[string]string{ + "modules/sdk/go.mod": "module " + sdk + "\n\ngo 1.25.0\n", + "modules/sdk/module.json": `{"module":"sdk","version":"1"}`, + "modules/sdk/s.go": "package sdk\n\nconst S = 1\n", + "modules/c/module.json": `{"module":"c","version":"1"}`, + "modules/c/go/x/go.mod": "module git.novox.be/novox/narrowown/modules/c/go/x\n\ngo 1.25.0\n\nrequire " + sdk + " v0.0.0-00010101000000-000000000000\n", + "modules/c/go/x/x.go": "package x\n\nimport \"" + sdk + "\"\n\nconst X = sdk.S\n", + }) + res, st = fetched(t, m, states, map[string]any{"repository": "novox/narrowown", "commit": ownHead, "dir": "modules/c", "paths": []any{"go/x"}}) + if st.State != sdkstep.StepPassed { + t.Fatalf("the fetch of an artifact requiring its repository's other module ended %s: %s", st.State, st.Reason) + } + if _, err := os.Stat(filepath.Join(m.Work, res.Workspace, "tree", "modules", "sdk", "s.go")); err != nil { + t.Errorf("the narrowed workspace lacks the required package of its repository: %v", err) + } + if strings.Join(res.Modules, ",") != "modules/c/go/x" { + t.Errorf("the fetch answered the modules %v, want modules/c/go/x alone", res.Modules) + } _, st = fetched(t, m, states, map[string]any{"repository": "novox/narrow", "commit": head, "dir": "", "paths": []any{"cmd"}}) if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "no module directory") { t.Errorf("paths without a directory: %s %q", st.State, st.Reason) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/narrow_test.go b/modules/mesh-build-go/cmd/mesh-build-go/narrow_test.go new file mode 100644 index 000000000..1a0b46928 --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/narrow_test.go @@ -0,0 +1,221 @@ +package main + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/seatgen" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" +) + +func writeFile(t *testing.T, file, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// Design 47 H, lead answer H-A-136 (live 2026-11-20, the first pipeline main.3): a workspace narrowed to an artifact's +// named paths also holds every generated-from directory an artifact of its module names (the seat definitions the +// generated package is compared against) and the directory, with its go.mod, of every package of the same repository the +// artifact's go.mod requires at the zero version, found by that repository's manifests; nothing else. The fetch's Go +// modules stay the artifact's own (A-447a): neither the generated-from directory's nor the sibling package's. +func TestANarrowedWorkspaceHoldsTheGeneratedFromDirectoriesAndItsRepositorysZeroVersionPackages(t *testing.T) { + const sdk = "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk" + const repo = "git.novox.be/novox/mesh-delivery" + zero := " v0.0.0-00010101000000-" + zeroShort + for _, tc := range []struct { + name, dir string + repository string // the fetch's repository, novox/mesh-delivery when empty + paths []string + files map[string]string + kept, gone []string + modules []string + seats []string // generated into the tree by the seat generator, its out-of-step check then finding nothing + refused string // the narrowing fails naming this + }{ + {name: "a generated-from directory", dir: "modules/c", paths: []string{"go/seats/a"}, + files: map[string]string{ + "modules/c/module.json": `{"module":"c","build":{"artifacts":[{"name":"go-a","kind":"package","language":"go","paths":["go/seats/a"],"generated-from":"seats"},{"name":"go-b","kind":"package","language":"go","paths":["go/seats/b"],"generated-from":"seats"}]}}`, + "modules/c/seats/a.json": "{}\n", + "modules/c/go/seats/a/go.mod": "module git.novox.be/novox/mesh-delivery/modules/c/go/seats/a\n\ngo 1.26\n", + "modules/c/go/seats/b/go.mod": "module git.novox.be/novox/mesh-delivery/modules/c/go/seats/b\n\ngo 1.26\n", + "modules/c/docs/x.md": "not named\n", + "modules/d/module.json": `{"module":"d"}`, + }, + kept: []string{"modules/c/module.json", "modules/c/seats/a.json", "modules/c/go/seats/a/go.mod"}, + gone: []string{"modules/c/go/seats/b", "modules/c/docs", "modules/d"}, + modules: []string{"modules/c/go/seats/a"}}, + {name: "the module's own directory as generated-from", dir: "modules/c", paths: []string{"go/seats/a"}, + files: map[string]string{ + "modules/c/module.json": `{"module":"c","build":{"artifacts":[{"name":"go-a","kind":"package","language":"go","paths":["go/seats/a"],"generated-from":"."}]}}`, + "modules/c/seats/a.json": "{}\n", + "modules/c/go/seats/a/go.mod": "module git.novox.be/novox/mesh-delivery/modules/c/go/seats/a\n\ngo 1.26\n", + "modules/c/go/seats/b/go.mod": "module git.novox.be/novox/mesh-delivery/modules/c/go/seats/b\n\ngo 1.26\n", + "modules/d/module.json": `{"module":"d"}`, + }, + kept: []string{"modules/c/seats/a.json", "modules/c/go/seats/b/go.mod"}, + gone: []string{"modules/d"}, + modules: []string{"modules/c/go/seats/a"}}, + {name: "a module at the repository's root with generated-from \".\"", dir: ".", paths: []string{"go/seats/onestore"}, + files: map[string]string{ + "module.json": `{"module":"mesh-contracts","build":{"artifacts":[{"name":"go-onestore","kind":"package","language":"go","paths":["go/seats/onestore"],"generated-from":"."},{"name":"go-twostore","kind":"package","language":"go","paths":["go/seats/twostore"],"generated-from":"."},{"name":"ts-onestore","kind":"package","language":"typescript","paths":["ts/seats/onestore"],"generated-from":"."},{"name":"ts-twostore","kind":"package","language":"typescript","paths":["ts/seats/twostore"],"generated-from":"."},{"name":"go-other","kind":"package","language":"go","paths":["go/other"]}]}}`, + "README.md": "the repository\n", + "docs/a.md": "not named\n", + "go/other/go.mod": "module git.novox.be/novox/mesh-contracts/go/other\n\ngo 1.26\n", + "modules/x/module.json": `{"module":"x"}`, + }, + seats: []string{"one-store", "two-store"}, + kept: []string{"module.json", "seats/one-store/seat.json", "seats/two-store/seat.json", "go/seats/onestore/go.mod", "go/seats/twostore/contract.go", "ts/seats/twostore/package.json"}, + gone: []string{"README.md", "docs", "go/other", "modules"}, + modules: []string{"go/seats/onestore"}}, + {name: "a package of the same repository at the zero version", dir: "modules/mesh-delivery-contracts", + paths: []string{"go/clients/meshcatalogclient"}, + files: map[string]string{ + "module.json": `{"module":"root"}`, + "go.sum": "root\n", + "modules/mesh-delivery-contracts/module.json": `{"module":"mesh-delivery-contracts","build":{"artifacts":[{"name":"go-meshcatalogclient","kind":"package","language":"go","paths":["go/clients/meshcatalogclient"]}]}}`, + "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient\n\ngo 1.26\n\nrequire (\n\t" + sdk + zero + "\n\tgit.novox.be/novox/mesh-sdk/go" + zero + "\n)\n", + "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/c.go": "package meshcatalogclient\n", + "modules/mesh-delivery-contracts/go/clients/other/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/other\n\ngo 1.26\n", + "modules/mesh-delivery-sdk/module.json": `{"module":"mesh-delivery-sdk","build":{"artifacts":[{"name":"go-sdk","kind":"package","language":"go"}]}}`, + "modules/mesh-delivery-sdk/go.mod": "module " + sdk + "\n\ngo 1.26\n", + "modules/mesh-delivery-sdk/steprun/s.go": "package steprun\n", + "modules/mesh-delivery-view/module.json": `{"module":"mesh-delivery-view"}`, + "modules/mesh-delivery-view/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view\n\ngo 1.26\n", + }, + kept: []string{"modules/mesh-delivery-contracts/module.json", "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/c.go", + "modules/mesh-delivery-sdk/go.mod", "modules/mesh-delivery-sdk/steprun/s.go"}, + gone: []string{"module.json", "go.sum", "modules/mesh-delivery-view", "modules/mesh-delivery-contracts/go/clients/other"}, + modules: []string{"modules/mesh-delivery-contracts/go/clients/meshcatalogclient"}}, + // H-A-202, H-A-198: the packages of the repository a required one requires at the zero version come along too, + // transitively (state -> builds -> client), each found by its manifest. + {name: "the repository's packages a required package requires, transitively", dir: "modules/a", paths: []string{"state"}, + files: map[string]string{ + "modules/a/module.json": `{"module":"a","build":{"artifacts":[{"name":"state","kind":"package","language":"go","paths":["state"]}]}}`, + "modules/a/state/go.mod": "module " + repo + "/modules/a/state\n\ngo 1.26\n\nrequire " + repo + "/modules/b/builds" + zero + "\n", + "modules/a/state/s.go": "package state\n", + "modules/b/module.json": `{"module":"b","build":{"artifacts":[{"name":"builds","kind":"package","language":"go","paths":["builds"]}]}}`, + "modules/b/builds/go.mod": "module " + repo + "/modules/b/builds\n\ngo 1.26\n\nrequire (\n\t" + repo + "/modules/c/client" + zero + "\n\tgit.novox.be/novox/mesh-sdk/go" + zero + "\n)\n", + "modules/b/builds/b.go": "package builds\n", + "modules/b/other/o.go": "package other\n", + "modules/c/module.json": `{"module":"c","build":{"artifacts":[{"name":"client","kind":"package","language":"go","paths":["client"]}]}}`, + "modules/c/client/go.mod": "module " + repo + "/modules/c/client\n\ngo 1.26\n\nrequire " + repo + "/modules/b/builds" + zero + "\n", + "modules/c/client/c.go": "package client\n", + "modules/c/other/o.go": "package other\n", + "modules/d/module.json": `{"module":"d"}`, + }, + kept: []string{"modules/a/state/s.go", "modules/b/builds/b.go", "modules/c/client/c.go"}, + gone: []string{"modules/b/other", "modules/c/other", "modules/d"}, + modules: []string{"modules/a/state"}}, + // S31, L8: a package of the repository required at a real version comes along too, transitively, and "the + // repository" is the fetch's, under any owner; a package of another repository at a real version does not. + {name: "the repository's packages at a real version, under another owner", repository: "kin/app", dir: "modules/a", paths: []string{"state"}, + files: map[string]string{ + "modules/a/module.json": `{"module":"a","build":{"artifacts":[{"name":"state","kind":"package","language":"go","paths":["state"]}]}}`, + "modules/a/state/go.mod": "module git.novox.be/kin/app/modules/a/state\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/kin/app/modules/b/builds v0.1.3\n\tgit.novox.be/novox/app/modules/d/x v0.1.3\n)\n", + "modules/a/state/s.go": "package state\n", + "modules/b/module.json": `{"module":"b","build":{"artifacts":[{"name":"builds","kind":"package","language":"go","paths":["builds"]}]}}`, + "modules/b/builds/go.mod": "module git.novox.be/kin/app/modules/b/builds\n\ngo 1.26\n\nrequire git.novox.be/kin/app/modules/c/client v0.2.0\n", + "modules/b/builds/b.go": "package builds\n", + "modules/c/module.json": `{"module":"c","build":{"artifacts":[{"name":"client","kind":"package","language":"go","paths":["client"]}]}}`, + "modules/c/client/go.mod": "module git.novox.be/kin/app/modules/c/client\n\ngo 1.26\n", + "modules/c/client/c.go": "package client\n", + "modules/d/module.json": `{"module":"d","build":{"artifacts":[{"name":"x","kind":"package","language":"go","paths":["x"]}]}}`, + "modules/d/x/go.mod": "module git.novox.be/novox/app/modules/d/x\n\ngo 1.26\n", + }, + kept: []string{"modules/a/state/s.go", "modules/b/builds/b.go", "modules/c/client/c.go"}, + gone: []string{"modules/d"}, + modules: []string{"modules/a/state"}}, + // A named path that leaves the repository is refused. + {name: "a named path that leaves the repository", dir: "mesh-grants", paths: []string{".", "../../outside"}, + files: map[string]string{"mesh-grants/module.json": `{"module":"mesh-grants"}`, "mesh-grants/go.mod": "module mesh-grants\n\ngo 1.26\n"}, + refused: `"../../outside" leaves`}, + {name: "a named path that leaves the repository from a nested module", dir: "modules/mesh-grants", paths: []string{"../../../outside"}, + files: map[string]string{"modules/mesh-grants/module.json": `{"module":"mesh-grants"}`, "modules/mesh-grants/go.mod": "module mesh-grants\n\ngo 1.26\n"}, + refused: `"../../../outside" leaves`}, + } { + t.Run(tc.name, func(t *testing.T) { + tree := t.TempDir() + var all []string + for f, body := range tc.files { + os.MkdirAll(filepath.Join(tree, filepath.Dir(f)), 0o755) + if err := os.WriteFile(filepath.Join(tree, f), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + if filepath.Base(f) == "go.mod" { + all = append(all, filepath.Dir(f)) + } + } + if len(tc.seats) > 0 { + for _, seat := range tc.seats { + writeFile(t, filepath.Join(tree, "seats", seat, "seat.json"), `{"format":1,"seat":"`+seat+`","scope":"mesh","grain":"whole","domain":"Module","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"},"answer":{"type":"object"}}]}`) + } + g, err := seatgen.Load(tree, "git.novox.be/novox/mesh-contracts/go", "@novox/mesh-contracts") + if err != nil { + t.Fatal(err) + } + files, err := seatgen.Generate(g) + if err != nil { + t.Fatal(err) + } + for f, b := range files { + writeFile(t, filepath.Join(tree, f), string(b)) + if filepath.Base(f) == "go.mod" { + all = append(all, filepath.Dir(f)) + } + } + } + repository := tc.repository + if repository == "" { + repository = "novox/mesh-delivery" + } + req := sdkstep.FetchRequest{Repository: repository, Commit: commitSHA, Dir: tc.dir, Paths: tc.paths} + err := narrowTree(tree, req.Repository, req) + if tc.refused != "" { + if err == nil || !strings.Contains(err.Error(), tc.refused) { + t.Fatalf("the narrowing answered %v, want it refused naming %s", err, tc.refused) + } + return + } + if err != nil { + t.Fatal(err) + } + for _, k := range tc.kept { + if _, err := os.Stat(filepath.Join(tree, k)); err != nil { + t.Errorf("%s was narrowed away: %v", k, err) + } + } + for _, g := range tc.gone { + if _, err := os.Stat(filepath.Join(tree, g)); err == nil { + t.Errorf("%s is still in the workspace", g) + } + } + if len(tc.seats) > 0 { + for _, root := range []string{steprun.GeneratedRootGo, steprun.GeneratedRootTS} { + if out, err := steprun.OutOfStep(filepath.Join(tree, tc.dir), root); err != nil || len(out) != 0 { + t.Errorf("the seat generator's check in the narrowed workspace, root %s: %v %v, want nothing out of step", root, out, err) + } + } + } + var left []string + for _, d := range all { + if _, err := os.Stat(filepath.Join(tree, d, "go.mod")); err == nil { + left = append(left, d) + } + } + slices.Sort(left) + got, err := scopedDirs(tree, tc.dir, tc.paths, left) + if err != nil || strings.Join(got, ",") != strings.Join(tc.modules, ",") { + t.Errorf("the fetch's Go modules = %v (%v), want %v", got, err, tc.modules) + } + }) + } +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/packages_shape_test.go b/modules/mesh-build-go/cmd/mesh-build-go/packages_shape_test.go index 62e813fb2..80154656b 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/packages_shape_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/packages_shape_test.go @@ -63,7 +63,7 @@ func TestACheckAskReachesTheTestStepPastItsPackages(t *testing.T) { } } } - a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker", + a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner", At: time.Now(), Check: &sdkstep.CheckJob{Fetch: sdkstep.Fetch{Repository: "novox/x", Commit: askCommit}, Levels: []string{sdkstep.LevelUnit}}} out, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a) got := "" diff --git a/modules/mesh-build-go/cmd/mesh-build-go/pins.go b/modules/mesh-build-go/cmd/mesh-build-go/pins.go index 00c5e900c..6f6e92514 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/pins.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/pins.go @@ -1,12 +1,13 @@ package main -// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2; issue 1148): a group's Go members pin the head of -// the group's mesh-sdk pull request, a commit that only refs/pull//head of the forge carries until the merge. Go -// cannot fetch it by its pseudo-version, so a fetch that meets "unknown revision" for such a pin finds the commit among -// the forge's pull request heads, places that repository beside the workspace as a plain directory, and hands it to -// Go through a temporary -modfile, a copy of the directory's go.mod that replaces the module by that directory. The -// fetch's go commands and the build use the same modfile, and the build still runs with GOPROXY=off. A pin Go can -// fetch is not touched, and a directory that vendors is never resolved. +// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2, ADR 0573 §4; issue 1148): a group's check asks a +// mesh package at the head of the group's pull request, a commit that only refs/pull//head of the forge carries until +// the merge. The Go package registry does not hold it, so the fetch finds the commit among the forge's pull request +// heads, places that repository beside the workspace as a plain directory, and hands it to Go through a temporary +// -modfile, a copy of the directory's go.mod that replaces the module by that directory. The fetch's go commands and +// the build use the same modfile, and the build still runs with GOPROXY=off. Only a pin the ask gives as a commit is +// placed; a version a go.mod names is refused, never placed (design 47 H, H-A-494 second and third addenda), and a +// directory that vendors is never resolved. import ( "context" @@ -25,7 +26,19 @@ import ( dforgekey "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/forgekey" ) -const forgePrefix = "git.novox.be/novox/" +// goHost is the host the forge's Go modules are named under: a module of the repository / has the path +// goHost+"/" or one under it. +const goHost = "git.novox.be/" + +const forgePrefix = goHost + "novox/" + +// sameRepository says whether the Go module path lies in the repository the fetch is of (its owner/name, as the ask +// names it): the repository's root module or one nested in it (design 47 H, S31, L8: read from the fetch, never from an +// owner name written into the code). +func sameRepository(module, repository string) bool { + prefix := goHost + repository + return repository != "" && (module == prefix || strings.HasPrefix(module, prefix+"/")) +} // zeroShort is the 12 digits a requirement at the zero version v0.0.0-00010101000000-000000000000 ends in: no commit. const zeroShort = "000000000000" @@ -99,44 +112,6 @@ func (m *Module) pinModfile(dir string) (string, bool) { return p, err == nil } -// resolvePins resolves the pins of dir that a go command failed on: those whose commit the failure names. It answers -// false when there is none, and the failure is then the caller's. -func (m *Module) resolvePins(ctx context.Context, root, dir, failure string) (bool, error) { - raw, err := os.ReadFile(filepath.Join(dir, "go.mod")) - if err != nil { - return false, nil - } - modfile, _ := m.pinModfile(dir) - done := "" - if modfile != "" { - if b, err := os.ReadFile(modfile); err == nil { - done = string(b) - } - } - progress := false - for _, p := range forgePins(string(raw)) { - if p.short == zeroShort { - continue // takeZeroPins': a requirement at the zero version names no commit to look for - } - if !strings.Contains(failure, p.short) || strings.Contains(done, "replace "+p.module+" =>") { - continue - } - where, err := m.placePin(ctx, root, p, failure) - if errors.Is(err, errNotAHead) { - // On no pull request head: go's failure is the caller's, in go's own words (issue 1748). - continue - } - if err != nil { - return false, err - } - if err := m.replaceInModfile(dir, p.module, where); err != nil { - return false, err - } - progress = true - } - return progress, nil -} - // errNotAHead is a pin whose commit no pull request head of the forge carries, when go's failure was not go knowing no // such revision: the failure is the network's or the forge's, and the caller says it in go's words (issue 1748). var errNotAHead = errors.New("on no pull request head") @@ -347,27 +322,78 @@ func (m *Module) takeZeroPins(ctx context.Context, root, repository, dir, d, fai return m.takeZeroRequirements(ctx, root, repository, dir, d, zeroRequirementsOf(dir), asked, pins) } -// takeReplacedZeroPins takes, before anything is downloaded, the requirements at the zero version that only a module -// dir replaces by a directory names (zeroRequirementsOf): go mod download loads only what dir's own go.mod names, so it -// passes without them, and the shut-off steps would look them up on the network (issue 1966). One the asked versions -// took (before, takeVersions) is left as it is. -func (m *Module) takeReplacedZeroPins(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) { - var replaced []zeroRequirement +// takeZeroPinsFirst takes or refuses, before anything else is downloaded, every requirement at the zero version of +// dir's module graph (zeroRequirementsOf) the asked versions did not take (before, takeVersions): dir's own, and those +// only a module dir replaces by a directory names, which go mod download would not miss and the shut-off steps would +// look up on the network (issue 1966). So no forge path reaches the second download, the public proxy's, first (design +// 47 H, H-A-494 third addendum). +func (m *Module) takeZeroPinsFirst(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) { + raw, _ := os.ReadFile(filepath.Join(dir, "go.mod")) + _, replaced := goModRequirements(string(raw)) + var reqs []zeroRequirement for _, r := range zeroRequirementsOf(dir) { - if r.by != "" && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) { - replaced = append(replaced, r) + // One dir's go.mod replaces is decided by its replace. + if !replaced[r.module] && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) { + reqs = append(reqs, r) } } - if len(replaced) == 0 { + if len(reqs) == 0 { return nil, nil } - return m.takeZeroRequirements(ctx, root, repository, dir, d, replaced, asked, pins) + return m.takeZeroRequirements(ctx, root, repository, dir, d, reqs, asked, pins) +} + +// namedForgeVersion refuses a mesh package (a module of the forge) that dir's module graph names at a version other +// than the zero version (ADR 0573 §4; design 47 H, H-A-494 second addendum), in the graph zeroRequirementsOf reads: dir's +// go.mod, then each module it replaces by a directory. A module of the checked repository (built from its tree) and one +// dir's go.mod replaces are left out. The first such requirement is named, before either download. +func namedForgeVersion(repository, dir string) error { + raw, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil { + return nil + } + _, replaced := goModRequirements(string(raw)) + check := func(gomod string) error { + required, _ := goModRequirements(gomod) + for _, pkg := range slices.Sorted(maps.Keys(required)) { + v := required[pkg] + if !strings.HasPrefix(pkg, forgePrefix) || v == zeroVersion || replaced[pkg] || sameRepository(pkg, repository) { + continue + } + return fmt.Errorf("%s names %s@%s; a mesh package is required at the zero version", modulePathOf(gomod), pkg, v) + } + return nil + } + if err := check(string(raw)); err != nil { + return err + } + local := localReplaces(string(raw)) + for _, module := range slices.Sorted(maps.Keys(local)) { + b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(local[module]), "go.mod")) + if err != nil { + continue // a replace to a directory with no go.mod: Go says so in its own words + } + if err := check(string(b)); err != nil { + return err + } + } + return nil +} + +// modulePathOf is the module path a go.mod declares, "" when it declares none. +func modulePathOf(gomod string) string { + for _, line := range strings.Split(gomod, "\n") { + if f := strings.Fields(line); len(f) >= 2 && f[0] == "module" { + return strings.Trim(f[1], `"`) + } + } + return "" } // takeZeroRequirements takes, for each requirement at the zero version, the version it is built against (ADR 0573 §2, -// §4: whatever go.mod names): the commit the ask names for the package; else the head of the package's repository among -// the asked versions (the check's or try's members: another package of the same repository names it); else the latest -// published version, the trunk's head. It never looks for the commit 000000000000 among the pull request heads. One +// §4: whatever go.mod names): a module of the checked repository from the fetched tree (H-A-198); any other at the pin +// the ask names for that package path, and with no pin it refuses the build, never taking another path's version or +// the latest (design 47 H, H-A-192). It never looks for the commit 000000000000 among the pull request heads. One // taken before (dir's modfile requires or replaces it) is left as it is. func (m *Module) takeZeroRequirements(ctx context.Context, root, repository, dir, d string, reqs []zeroRequirement, asked sdkstep.PackageVersions, pins *sync.Mutex) ([]TakenVersion, error) { resolved := map[string]string{} @@ -381,10 +407,16 @@ func (m *Module) takeZeroRequirements(ctx context.Context, root, repository, dir } } } + replacedBefore := "" + if modfile, ok := m.pinModfile(dir); ok { + if b, err := os.ReadFile(modfile); err == nil { + replacedBefore = string(b) + } + } var taken []TakenVersion for _, r := range reqs { p := r.pin - if v := resolved[p.module]; v != "" && !strings.HasSuffix(v, zeroShort) { + if v := resolved[p.module]; (v != "" && !strings.HasSuffix(v, zeroShort)) || strings.Contains(replacedBefore, "replace "+p.module+" =>") { continue // taken before } named := "v0.0.0-00010101000000-" + zeroShort @@ -392,10 +424,10 @@ func (m *Module) takeZeroRequirements(ctx context.Context, root, repository, dir if r.by != "" { namedBy = "; " + namedBySaid(r.by) } - if "novox/"+p.repo == repository { + if sameRepository(p.module, repository) { // A module of the checked repository itself: it is in the fetched tree and nowhere else, since nothing of the // repository is published before its merge. Every module of the tree goes in, as one may require another. - own, err := m.useOwnModules(dir, root, p.repo) + own, err := m.useOwnModules(dir, root, repository) if err != nil { return taken, fmt.Errorf("the requirement of %s at the zero version: %w", p.module, err) } @@ -409,13 +441,13 @@ func (m *Module) takeZeroRequirements(ctx context.Context, root, repository, dir taken = append(taken, tv) continue } - tv := TakenVersion{Dir: d, Package: p.module, Asked: askedFor(asked, p), Named: named} - why := "the ask names it" + // The ask's pin for this path alone: a build module given no pin refuses the build, loud, and never takes another + // path's version nor the latest (design 47 H, H-A-192). + tv := TakenVersion{Dir: d, Package: p.module, Asked: asked[p.module], Named: named} if tv.Asked == "" { - tv.Asked, why = "latest", "the ask names no commit of its repository, so its latest published version" - } else if _, ok := asked[p.module]; !ok { - why = "the head of its repository among the asked versions" + return taken, fmt.Errorf("no pin for %s: the builder pins or waits (H-A-192)", p.module) } + why := "the ask names it" if err := m.takeVersion(ctx, root, dir, &tv, pins); err != nil { return taken, fmt.Errorf("the requirement of %s at the zero version: %w", p.module, err) } @@ -431,26 +463,79 @@ func (m *Module) takeZeroRequirements(ctx context.Context, root, repository, dir // namedBySaid says that a module dir replaces by the directory by names a package, and dir's go.mod does not. func namedBySaid(by string) string { return "named by " + by + ", not by this go.mod" } -// askedFor is the commit the ask names for the package p: its own, else that of the first package of the same repository -// in order (the members' heads are by repository), else none. -func askedFor(asked sdkstep.PackageVersions, p pin) string { - if c := asked[p.module]; c != "" { - return c +// ownRequirement is a requirement of a module of the checked repository in the module graph of a directory, at the +// version its go.mod names (any version): by as in zeroRequirement. +type ownRequirement struct { + module, named, by string +} + +// ownRequirementsOf are the requirements of dir's module graph (its go.mod, then the go.mod of each module it replaces by +// a directory, as zeroRequirementsOf reads them) that lie in the repository the fetch is of, at whatever version they are +// named, each once, own first. One dir's go.mod replaces is left out, since its replace decides it. +func ownRequirementsOf(dir, repository string) []ownRequirement { + raw, err := os.ReadFile(filepath.Join(dir, "go.mod")) + if err != nil { + return nil } - for _, pkg := range slices.Sorted(maps.Keys(asked)) { - if pkg == forgePrefix+p.repo || strings.HasPrefix(pkg, forgePrefix+p.repo+"/") { - return asked[pkg] + _, replaced := goModRequirements(string(raw)) + seen := map[string]bool{} + var out []ownRequirement + add := func(gomod, by string) { + required, _ := goModRequirements(gomod) + for _, module := range slices.Sorted(maps.Keys(required)) { + if !sameRepository(module, repository) || seen[module] || replaced[module] { + continue + } + seen[module] = true + out = append(out, ownRequirement{module: module, named: required[module], by: by}) } } - return "" + add(string(raw), "") + local := localReplaces(string(raw)) + for _, module := range slices.Sorted(maps.Keys(local)) { + if b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(local[module]), "go.mod")); err == nil { + add(string(b), local[module]) + } + } + return out +} + +// takeOwnRequirements takes, before anything is downloaded, every requirement of dir's module graph that lies in the +// checked repository from the fetched tree, at whatever version go.mod names it, the zero version or a real one (design +// 47 H, S3, S31; H-A-198, H-A-202): the indexer never pins it and its fingerprint takes the tree's objects, so the build +// takes the tree too and never the Go seat's published version. One no module of the tree declares fails the fetch, +// naming it. +func (m *Module) takeOwnRequirements(root, repository, dir, d string) ([]TakenVersion, error) { + reqs := ownRequirementsOf(dir, repository) + if len(reqs) == 0 { + return nil, nil + } + own, err := m.useOwnModules(dir, root, repository) + if err != nil { + return nil, fmt.Errorf("the requirements of %s: %w", repository, err) + } + var taken []TakenVersion + for _, r := range reqs { + if !slices.Contains(own, r.module) { + return taken, fmt.Errorf("the requirement of %s at %s: no module of that path is in the fetched tree of %s, and a module of the checked repository is built from its tree", r.module, r.named, repository) + } + said := "a module of the checked repository: built from its tree" + if r.by != "" { + said += "; " + namedBySaid(r.by) + } + if m.Say != nil { + m.Say("%s: %s (go.mod names %s) is built from the fetched tree of %s", d, r.module, r.named, repository) + } + taken = append(taken, TakenVersion{Dir: d, Package: r.module, Named: r.named, Built: "the fetched tree", Said: said}) + } + return taken, nil } // useOwnModules replaces, in dir's temporary modfile, every module of the fetched tree whose path lies in the repository -// repo by its directory in the tree (once), and answers the paths of those modules. A replace of a module dir does not -// require is harmless to Go; one module of a repository requires another of it at the zero version. -func (m *Module) useOwnModules(dir, root, repo string) ([]string, error) { +// the fetch is of (sameRepository) by its directory in the tree (once), and answers the paths of those modules. A +// replace of a module dir does not require is harmless to Go; one module of a repository requires another of it. +func (m *Module) useOwnModules(dir, root, repository string) ([]string, error) { tree := filepath.Join(root, "tree") - prefix := forgePrefix + repo type found struct{ module, where string } var mods []found err := filepath.WalkDir(tree, func(path string, e fs.DirEntry, err error) error { @@ -472,7 +557,7 @@ func (m *Module) useOwnModules(dir, root, repo string) ([]string, error) { } for _, line := range strings.Split(string(raw), "\n") { if f := strings.Fields(line); len(f) == 2 && f[0] == "module" { - if mod := strings.Trim(f[1], `"`); (mod == prefix || strings.HasPrefix(mod, prefix+"/")) && filepath.Dir(path) != dir { + if mod := strings.Trim(f[1], `"`); sameRepository(mod, repository) && filepath.Dir(path) != dir { mods = append(mods, found{mod, filepath.Dir(path)}) } break diff --git a/modules/mesh-build-go/cmd/mesh-build-go/pins_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/pins_integration_test.go index 1e2e79b36..f39b98be0 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/pins_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/pins_integration_test.go @@ -17,9 +17,9 @@ import ( ) // 1148/AC2 as issue 1585 S15 has it (novox/hq ADR 0573 §4): given a forge with a mesh-sdk-like pull request whose branch -// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names an older commit of it, when +// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names it at the zero version, when // build_go_fetch is asked that head as the package's version and build_go_build runs on the member, then both pass, the -// build with GOPROXY=off against the head: the older commit holds no Go package at all. +// build with GOPROXY=off against the head (a go.mod names a mesh package at the zero version only, design 47 H, H-A-494). func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.T) { t.Parallel() // Not skipped when a tool is missing: a pass of the check must mean this test ran (the check prints no test log). @@ -36,7 +36,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing. }, "refs/pull/7/head") git(t, work, "checkout", "-q", "main") // no branch of the repository carries the head member := map[string]string{ - "go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go v0.0.0-20261021120000-" + fork[:12] + "\n", + "go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go " + zeroVersion + "\n", "cmd/prog/main.go": "package main\n\nimport (\n\t\"fmt\"\n\n\tdep \"git.novox.be/novox/dep/go\"\n)\n\n" + "func main() { fmt.Println(dep.Name) }\n", "module.json": `{"module":"fixture-member","version":"1","build":{"artifacts":[{"name":"tools","kind":"bundle","language":"go","system":"arch","from":"cmd/prog","binary":"prog-bin","loads":["prog-bin"]}]}}`, @@ -50,7 +50,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing. if st.State != sdkstep.StepPassed { t.Fatalf("the fetch ended %s: %s", st.State, st.Reason) } - if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != "v0.0.0-20261021120000-"+fork[:12] { + if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != zeroVersion { t.Errorf("the fetch names what it built against: %+v, want the asked head %s", res.Packages, head) } if _, err := os.Stat(filepath.Join(m.Work, res.Workspace, "pinned", "dep@"+head, "beside", "dep", "go", "dep.go")); err != nil { @@ -59,7 +59,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing. // The build runs shut off in bubblewrap (1309), which a build node has and build-agent's check container has not: // there the build half is not run, said loudly; the fetch half above, the pin's own part (issue 1148), always is. needTools(t, "the shut-off build of a member pinning a pull head", "bwrap") - built, err := m.build(context.Background(), map[string]any{"workspace": res.Workspace, "module": ".", "artifact": "tools"}) + built, err := m.build(context.Background(), map[string]any{"workspace": res.Workspace, "module": ".", "artifact": "tools", "version": askedVersion}) if err != nil { t.Fatal(fmt.Errorf("the build: %w", err)) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/pins_test.go b/modules/mesh-build-go/cmd/mesh-build-go/pins_test.go index 8d16b996f..105f302ca 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/pins_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/pins_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "sync" "testing" @@ -17,7 +18,11 @@ import ( // pinShort is the 12 digits of commitSHA a pseudo-version ends in. const pinShort = "0123456789ab" -const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.1.15-0.20261022120000-" + pinShort + "\n)\n" +// pinnedGoMod requires mesh-sdk at the zero version (ADR 0573 §4); the ask pins it (pinAsk). +const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-" + zeroShort + "\n)\n" + +// pinAsk asks mesh-sdk at the head of a group's pull request, commitSHA: only refs/pull/7/head of pullList carries it. +var pinAsk = map[string]any{"git.novox.be/novox/mesh-sdk/go": commitSHA} // pinHarness runs a fetch of a tree whose only go.mod is gomod (a vendoring one when vendor is set) against a runner // that stands for the forge and for go: a pull request's head is listed by ls-remote when pulls says so, and go mod @@ -81,7 +86,9 @@ func newPinHarness(t *testing.T, gomod string, vendor bool, pulls string) (*pinH func (h *pinHarness) fetch(states *keptStates) (FetchResult, sdkstep.Step) { h.t.Helper() - if _, err := fetchTool(h.t, h.m)(fetchArgs); err != nil { + // A member of a repository other than mesh-sdk's, whose packages it pins: one of its own repository is built from the + // tree (S31). + if _, err := fetchTool(h.t, h.m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA, "packages": pinAsk}); err != nil { h.t.Fatal(err) } st := states.waitEnd(h.t) @@ -146,26 +153,40 @@ func TestAPinOnAPullHeadIsPlacedBesideAndHandedToGoByAModfile(t *testing.T) { } } -// 1148/AC3: a pin go downloads as it is (on the trunk or a tag) behaves as today: no listing of pull requests, no -// repository placed, no -modfile in the fetch or the build. -func TestAPinGoCanDownloadIsLeftAsToday(t *testing.T) { - h, states := newPinHarness(t, pinnedGoMod, false, pullList) - h.onTrunk = true - res, st := h.fetch(states) - if st.State != sdkstep.StepPassed { - t.Fatalf("the step ended %s: %s", st.State, st.Reason) +// H-A-494 second addendum: a go.mod naming a mesh package at a version other than the zero version (a pseudo-version, a +// release) is refused before either download, naming the module and the version, whether its own go.mod names it or a +// module it replaces by a directory; a module of the checked repository, and one the go.mod replaces, are not refused. +func TestAMeshPackageNamedAtARealVersionIsRefusedBeforeEitherDownload(t *testing.T) { + const sdk = "git.novox.be/novox/mesh-sdk/go" + for _, c := range []struct{ name, gomod, sib, refused string }{ + {name: "a pseudo-version", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.15-0.20261022120000-" + pinShort + "\n", + refused: "fixture/member names " + sdk + "@v0.1.15-0.20261022120000-" + pinShort + "; a mesh package is required at the zero version"}, + {name: "a release named by a module it replaces", gomod: "module fixture/member\n\nrequire fixture/sib " + zeroVersion + "\n\nreplace fixture/sib => ./sib\n", + sib: "module fixture/sib\n\nrequire " + sdk + " v0.1.85\n", refused: "fixture/sib names " + sdk + "@v0.1.85"}, + {name: "replaced by the go.mod", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.85\n\nreplace " + sdk + " => ./sdk\n"}, + {name: "of the checked repository", gomod: "module fixture/member\n\nrequire git.novox.be/novox/mesh-member/go v0.1.85\n"}, + } { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "go.mod"), []byte(c.gomod), 0o644) + if c.sib != "" { + os.MkdirAll(filepath.Join(dir, "sib"), 0o755) + os.WriteFile(filepath.Join(dir, "sib", "go.mod"), []byte(c.sib), 0o644) + } + err := namedForgeVersion("novox/mesh-member", dir) + if (err != nil) != (c.refused != "") || (err != nil && !strings.Contains(err.Error(), c.refused)) { + t.Fatalf("refused: %v, want %q", err, c.refused) + } + }) } - if h.ran("ls-remote") || h.ran("pinned") { - t.Errorf("a pin on the trunk made the fetch look for a pull request or place a repository:\n%s", strings.Join(h.f.lines(), "\n")) + // In a fetch: the step fails so, and runs no download at all. + h, states := newPinHarness(t, "module fixture/member\n\nrequire "+sdk+" v0.1.85\n", false, pullList) + _, st := h.fetch(states) + if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "fixture/member names "+sdk+"@v0.1.85; a mesh package is required at the zero version") { + t.Fatalf("the step ended %s: %q", st.State, st.Reason) } - dir := filepath.Join(h.m.Work, res.Workspace, "tree") - for _, e := range append(h.m.goEnvFor(dir), h.m.buildEnv(dir)...) { - if strings.Contains(e, "-modfile") { - t.Errorf("a -modfile is handed to go: %s", e) - } - } - if !h.ran(" mod download") || !h.ran(" mod verify") { - t.Errorf("go mod download and verify did not run as before") + if h.ran(" mod download") || h.ran("ls-remote") { + t.Errorf("a download or a listing ran before the refusal:\n%s", strings.Join(h.f.lines(), "\n")) } } @@ -222,42 +243,6 @@ func TestTwoDirectoriesPinningOneHeadShareOneCopy(t *testing.T) { } } -// 1148/AC1: two directories pinning two different commits of one repository get two copies, each its own. -func TestTwoCommitsOfOneRepositoryGetTwoCopies(t *testing.T) { - other := "fedcba9876543210fedcba9876543210fedcba98" - h, states := newPinHarness(t, pinnedGoMod, false, commitSHA+"\trefs/pull/7/head\n"+other+"\trefs/pull/8/head\n") - h.f.gomods = "go.mod\nsub/go.mod\n" - base := h.m.Run - h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { - if name == "git" && strings.Contains(strings.Join(args, " "), "pinned/mesh-sdk@"+other+"/") && strings.Contains(strings.Join(args, " "), " rev-parse HEAD") { - return forgekey.Ran{Stdout: other + "\n"} - } - // the second directory pins the other commit - if name == "git" && strings.Contains(strings.Join(args, " "), " checkout ") && !strings.Contains(strings.Join(args, " "), "pinned") { - r := base(ctx, env, name, args...) - for i, a := range args { - if a == "-C" { - os.WriteFile(filepath.Join(args[i+1], "sub", "go.mod"), []byte(strings.ReplaceAll(pinnedGoMod, pinShort, other[:12])), 0o644) - } - } - return r - } - if name == "go" && strings.Contains(strings.Join(args, " "), "/sub mod download") && !strings.Contains(strings.Join(env, " "), "-modfile=") { - return forgekey.Ran{Status: 1, Stderr: "go: git.novox.be/novox/mesh-sdk/go@v0.1.15-0.20261022120000-" + other[:12] + ": invalid version: unknown revision " + other[:12] + "\n"} - } - return base(ctx, env, name, args...) - } - _, st := h.fetch(states) - if st.State != sdkstep.StepPassed { - t.Fatalf("the step ended %s: %s", st.State, st.Reason) - } - for _, c := range []string{commitSHA, other} { - if !h.ran("pinned/mesh-sdk@" + c) { - t.Errorf("no copy of mesh-sdk at %s", c) - } - } -} - // A relative replace of a go.mod (a package of the module's own repository in a sibling directory, ADR 0593 §1) must still // resolve in the temporary modfile, which `go mod verify` runs in its own directory: every relative target is made absolute // under the tree it came from. The route-proxy failure of 2026-11-02 13:53 was a ./ replace met there; this takes real go. @@ -300,10 +285,10 @@ func TestARelativeReplaceStillResolvesInTheTemporaryModfile(t *testing.T) { } // A go.mod requirement at the zero version v0.0.0-00010101000000-000000000000 names no commit (ADR 0573 §2, §4: whatever -// go.mod names): it is taken from the commit the ask names for the package, else from the head of its repository among -// the asked versions, else from the trunk's latest published version, and never looked for as the commit 000000000000 -// among the pull request heads. -func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { +// go.mod names): it is taken from the pin the ask names for that package path alone, and never looked for as the commit +// 000000000000 among the pull request heads. With no pin of its own the build is refused, loud, naming the path: never +// built at another package's pin of the same repository nor at the latest (design 47 H, H-A-192). +func TestARequirementAtTheZeroVersionIsTakenFromItsPinOrRefused(t *testing.T) { t.Parallel() const sdk = "git.novox.be/novox/mesh-sdk/go" zeroMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + sdk + " v0.0.0-00010101000000-" + zeroShort + "\n)\n" @@ -313,6 +298,7 @@ func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { packages map[string]any download string // what go mod download -json answers want string // the version asked of go + refused bool // the step fails, naming the path: the ask carries no pin for it (H-A-192) head bool // the asked commit is on no trunk: only a pull request head carries it // replaced: the directory's go.mod names no mesh package; a module it replaces by a directory of the tree requires // it at the zero version, so go mod download passes and only a shut-off package load would look it up (1966/AC178-1) @@ -320,18 +306,14 @@ func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { }{ {name: "the ask names the package", packages: map[string]any{sdk: trunk}, want: sdk + "@" + trunk, download: `{"Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip="}`}, - {name: "the ask names another package of its repository", packages: map[string]any{"git.novox.be/novox/mesh-sdk/other": trunk}, want: sdk + "@" + trunk, - download: `{"Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip="}`}, - {name: "the ask names the root of its repository, which no package of is published", packages: map[string]any{"git.novox.be/novox/mesh-sdk": trunk}, want: sdk + "@" + trunk, - download: `{"Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip="}`}, + {name: "the ask pins only another package of its repository", packages: map[string]any{"git.novox.be/novox/mesh-sdk/other": trunk}, refused: true}, + {name: "the ask pins only the root of its repository", packages: map[string]any{"git.novox.be/novox/mesh-sdk": trunk}, refused: true}, {name: "the ask names the head of a pull request", packages: map[string]any{sdk: commitSHA}, want: sdk + "@" + commitSHA, head: true}, - {name: "the ask names nothing of its repository", packages: map[string]any{"git.novox.be/novox/mesh-tools/go": trunk}, want: sdk + "@latest", - download: `{"Version":"v0.1.20-0.20261104000000-bbbbbbbbbbbb","Sum":"h1:zip="}`}, - {name: "no ask", want: sdk + "@latest", download: `{"Version":"v0.1.20-0.20261104000000-bbbbbbbbbbbb","Sum":"h1:zip="}`}, + {name: "the ask names nothing of its repository", packages: map[string]any{"git.novox.be/novox/mesh-tools/go": trunk}, refused: true}, + {name: "no ask", refused: true}, {name: "named only by a module the directory replaces, the ask names it", packages: map[string]any{sdk: trunk}, want: sdk + "@" + trunk, replaced: true, download: `{"Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip="}`}, - {name: "named only by a module the directory replaces, no ask", want: sdk + "@latest", replaced: true, - download: `{"Version":"v0.1.20-0.20261104000000-bbbbbbbbbbbb","Sum":"h1:zip="}`}, + {name: "named only by a module the directory replaces, no ask", replaced: true, refused: true}, } { t.Run(c.name, func(t *testing.T) { gomod := zeroMod @@ -340,8 +322,13 @@ func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { } h, states := newPinHarness(t, gomod, false, pullList) base := h.m.Run + var mu sync.Mutex + var ran []string // every command, in order h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { line := name + " " + strings.Join(args, " ") + mu.Lock() + ran = append(ran, line) + mu.Unlock() switch { case c.replaced && name == "git" && strings.Contains(line, " checkout "): r := base(ctx, env, name, args...) @@ -374,6 +361,21 @@ func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { t.Fatal(err) } st := states.waitEnd(t) + if c.refused { + if st.State == sdkstep.StepPassed || !strings.Contains(st.Reason, "no pin for "+sdk) { + t.Fatalf("the step ended %s (%s), want it failed naming no pin for %s", st.State, st.Reason, sdk) + } + if h.ran(" mod download -json " + sdk + "@") { + t.Errorf("go was asked for a version of %s with no pin:\n%s", sdk, strings.Join(h.f.lines(), "\n")) + } + // H-A-494 third addendum: refused before any download of the rest, so no forge path reaches the public proxy. + for _, line := range ran { + if strings.HasSuffix(line, " mod download") { + t.Errorf("the rest was downloaded before the refusal: %s", line) + } + } + return + } if st.State != sdkstep.StepPassed { t.Fatalf("the step ended %s: %s", st.State, st.Reason) } @@ -398,41 +400,100 @@ func TestARequirementAtTheZeroVersionIsTakenFromTheAskOrTheTrunk(t *testing.T) { } } -// A requirement at the zero version of a module of the checked repository itself (a nested module not yet published, which -// another module of the repository requires) is built from the fetched tree, and never asked of Go or the forge (issue 1921). -func TestARequirementAtTheZeroVersionOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testing.T) { - const own = "git.novox.be/novox/mesh-delivery/nested/go" - zeroMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + own + " v0.0.0-00010101000000-" + zeroShort + "\n)\n" - h, states := newPinHarness(t, zeroMod, false, pullList) - base := h.m.Run - h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { - line := name + " " + strings.Join(args, " ") - if name == "go" && strings.Contains(line, " mod download") && !strings.Contains(strings.Join(env, " "), "-modfile=") { - trees, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "tree")) - for _, tree := range trees { - os.MkdirAll(filepath.Join(tree, "nested", "go"), 0o755) - os.WriteFile(filepath.Join(tree, "nested", "go", "go.mod"), []byte("module "+own+"\n\ngo 1.26\n"), 0o644) +// A requirement of a module of the checked repository itself (a nested module not yet published, which another module of +// the repository requires) is built from the fetched tree, and never asked of Go or the forge (issue 1921), at whatever +// version go.mod names it: the zero version or a real one, which the Go seat would otherwise serve while the indexer's +// fingerprint takes the tree (design 47 H, S31; H-A-198, H-A-202). "The checked repository" is the fetch's repository as +// the ask names it, under any owner, never an owner written into the code (L8). +// Narrowed: a fetch of one artifact of a tree shaped like mesh-delivery's (modules/mesh-delivery-contracts/go/clients/ +// requiring modules/mesh-delivery-sdk), asked with the module's directory and the artifact's paths, keeps the sdk's +// directory, found by its manifest, and resolves it there (design 47 H, H-A-136; live 2026-11-20, pipeline main.3: "no +// module of that path is in the fetched tree of novox/mesh-delivery"). +func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testing.T) { + zero := "v0.0.0-00010101000000-" + zeroShort + for _, tc := range []struct { + name, own, ownDir, gomods, version string + args map[string]any + narrowed bool + }{ + {name: "whole tree", own: "git.novox.be/novox/mesh-delivery/nested/go", ownDir: "nested/go", gomods: "go.mod\n", version: zero, + args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}}, + {name: "whole tree, at a real version", own: "git.novox.be/novox/mesh-delivery/nested/go", ownDir: "nested/go", gomods: "go.mod\n", + version: "v0.1.3", args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}}, + {name: "a repository of another owner, judged by the ask's repository", own: "git.novox.be/kin/app/nested/go", ownDir: "nested/go", + gomods: "go.mod\n", version: zero, args: map[string]any{"repository": "kin/app", "commit": commitSHA}}, + {name: "narrowed to an artifact's paths", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk", + ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod\n", version: zero, + args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-contracts", + "paths": []any{"go/clients/meshcatalogclient"}}, narrowed: true}, + {name: "narrowed to an artifact's paths, at a real version", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk", + ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod\n", version: "v0.1.3", + args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-contracts", + "paths": []any{"go/clients/meshcatalogclient"}}, narrowed: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ownMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + tc.own + " " + tc.version + "\n)\n" + h, states := newPinHarness(t, ownMod, false, pullList) + h.f.gomods = tc.gomods + base := h.m.Run + h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { + line := name + " " + strings.Join(args, " ") + if name == "git" && strings.Contains(line, " checkout ") { + r := base(ctx, env, name, args...) + tree := args[slices.Index(args, "-C")+1] + files := map[string]string{tc.ownDir + "/go.mod": "module " + tc.own + "\n\ngo 1.26\n"} + if tc.narrowed { + files["modules/mesh-delivery-sdk/module.json"] = `{"module":"mesh-delivery-sdk","build":{"artifacts":[{"name":"go-sdk","kind":"package","language":"go"}]}}` + files["modules/mesh-delivery-contracts/module.json"] = `{"module":"mesh-delivery-contracts","build":{"artifacts":[{"name":"go-meshcatalogclient","kind":"package","language":"go","paths":["go/clients/meshcatalogclient"]}]}}` + files["modules/mesh-delivery-view/go.mod"] = "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view\n\ngo 1.26\n" + } + for f, body := range files { + os.MkdirAll(filepath.Join(tree, filepath.Dir(f)), 0o755) + os.WriteFile(filepath.Join(tree, f), []byte(body), 0o644) + } + return r + } + if name == "go" && strings.Contains(line, " mod download") && !strings.Contains(strings.Join(env, " "), "-modfile=") { + if tc.version != zero { + return forgekey.Ran{} // the Go seat serves the published version: what a build of the tree must never take + } + return forgekey.Ran{Status: 1, Stderr: "go: " + tc.own + "@" + zero + ": invalid version: unknown revision " + zeroShort + "\n"} + } + return base(ctx, env, name, args...) } - return forgekey.Ran{Status: 1, Stderr: "go: " + own + "@v0.0.0-00010101000000-" + zeroShort + ": invalid version: unknown revision " + zeroShort + "\n"} - } - return base(ctx, env, name, args...) - } - if _, err := fetchTool(t, h.m)(map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}); err != nil { - t.Fatal(err) - } - st := states.waitEnd(t) - if st.State != sdkstep.StepPassed { - t.Fatalf("the step ended %s: %s", st.State, st.Reason) - } - modfiles, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "pins", "*", "go.mod")) - if len(modfiles) != 1 { - t.Fatalf("modfiles = %v", modfiles) - } - body, _ := os.ReadFile(modfiles[0]) - if !strings.Contains(string(body), "replace "+own+" => "+filepath.Join(filepath.Dir(filepath.Dir(filepath.Dir(modfiles[0]))), "tree", "nested", "go")) { - t.Errorf("the module of the tree was not replaced into the modfile:\n%s", body) - } - if h.ran(" mod download -json ") || h.ran("ls-remote") { - t.Error("a module of the checked repository was asked of Go or looked for among the pull request heads") + if _, err := fetchTool(t, h.m)(tc.args); err != nil { + t.Fatal(err) + } + st := states.waitEnd(t) + if st.State != sdkstep.StepPassed { + t.Fatalf("the step ended %s: %s", st.State, st.Reason) + } + modfiles, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "pins", "*", "go.mod")) + if len(modfiles) != 1 { + t.Fatalf("modfiles = %v", modfiles) + } + root := filepath.Dir(filepath.Dir(filepath.Dir(modfiles[0]))) + where := filepath.Join(root, "tree", filepath.FromSlash(tc.ownDir)) + if tc.narrowed { + if _, err := os.Stat(filepath.Join(root, "tree", "modules", "mesh-delivery-view")); err == nil { + t.Error("the narrowed tree holds a module the artifact does not require") + } + } + body, _ := os.ReadFile(modfiles[0]) + if !strings.Contains(string(body), "replace "+tc.own+" => "+where+"\n") { + t.Errorf("the module of the repository was not replaced into the modfile by %s:\n%s", where, body) + } + if strings.Count(string(body), "replace ") != 1 { + t.Errorf("the modfile replaces more than the one other module (its own directory again?):\n%s", body) + } + if h.ran(" mod download -json ") || h.ran("ls-remote") { + t.Error("a module of the checked repository was asked of Go or looked for among the pull request heads") + } + var res FetchResult + json.Unmarshal(st.Result, &res) + if len(res.Packages) != 1 || res.Packages[0].Package != tc.own || res.Packages[0].Built != "the fetched tree" || res.Packages[0].Named != tc.version { + t.Errorf("the taken versions = %+v, want %s named %s, built from the fetched tree", res.Packages, tc.own, tc.version) + } + }) } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/publish.go b/modules/mesh-build-go/cmd/mesh-build-go/publish.go index 43fbdd9f2..b7e469ae8 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/publish.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/publish.go @@ -23,9 +23,10 @@ func transferName(module, artifact, digest string) string { return steprun.TransferName(module, artifact, digest) } -// publishArchive publishes body, of digest, as / of kind (bundle or archive) on the artifact seat. -func (m *Module) publishArchive(ctx context.Context, module, artifact, kind, digest string, body []byte) error { - return m.publishOn(ctx, ArtifactSeat, module+"/"+artifact, kind, "", digest, transferName(module, artifact, digest), body) +// publishArchive publishes body, of digest, as / of kind (bundle or archive) on the artifact seat, under +// the version the ask reserved, so the builder marks it against its reservation (design 47 H, H-A-373). +func (m *Module) publishArchive(ctx context.Context, module, artifact, kind, version, digest string, body []byte) error { + return m.publishOn(ctx, ArtifactSeat, module+"/"+artifact, kind, version, digest, transferName(module, artifact, digest), body) } // publishOn publishes body through steprun.PublishOne: through Call when a test set it, else the runtime's request diff --git a/modules/mesh-build-go/cmd/mesh-build-go/publish_test.go b/modules/mesh-build-go/cmd/mesh-build-go/publish_test.go index 0bd446c43..72850b9fd 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/publish_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/publish_test.go @@ -17,7 +17,6 @@ import ( builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" registry "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) // pushed are the blobs the fake artifact store took, by digest, for the tests that read an archive back. @@ -102,11 +101,12 @@ func archiveOf(t *testing.T, res BuildResult) []byte { } // 1587-S2 (ADR 0498 §1): a done build answers a reference of the stated form whose tail is the build's digest, and the -// store holds the archive there; a bundle and an archive alike. +// store holds the archive there; a bundle and an archive alike. Each publish names the version the ask reserved, so the +// builder marks it against its reservation (design 47 H, H-A-373). func TestADoneBuildAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) { m, states, _ := buildModule(t, manifestWith(goBundle), "the program") store := withStore(t, m) - res, st := runBuild(t, m, states, "tools") + res, st := runBuildArgs(t, m, states, map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": "tools", "version": "1.4.3"}) if st.State != sdkstep.StepPassed { t.Fatalf("the step ended %s: %s", st.State, st.Reason) } @@ -116,12 +116,18 @@ func TestADoneBuildAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) { if store.blobs["demo/tools@"+res.Digest] == nil || store.asked[0] != "seat:oci-artifact-registry.publish" { t.Errorf("the seat was asked %v and holds %d blobs, not demo/tools@%s", store.asked, len(store.blobs), res.Digest) } + if len(store.published) != 1 || store.published[0].Version != "1.4.3" { + t.Errorf("the bundle was published as %+v, want the ask's version 1.4.3", store.published) + } a, states2, _ := archiveModule(t, "") - withStore(t, a) - arch, st := runBuild(t, a, states2, "files") + astore := withStore(t, a) + arch, st := runBuildArgs(t, a, states2, map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": "files", "version": "1.4.3"}) if st.State != sdkstep.StepPassed || arch.Reference != "oci-artifact-registry/demo/files@"+arch.Digest { t.Errorf("the archive artifact: %s %q, reference %q", st.State, st.Reason, arch.Reference) } + if len(astore.published) != 1 || astore.published[0].Version != "1.4.3" { + t.Errorf("the archive was published as %+v, want the ask's version 1.4.3", astore.published) + } } // 1587-S3 (ADR 0498 §2), CAT-BG1: a publish the seat's holder refuses fails the step `not stored: : ..`) as well as `.` (design 47 + // H2 §801): the tool is never empty while asks run. Ordered by the id, newest first. + own, ids := keys[:0:0], map[string]string{} for _, k := range keys { - if strings.HasPrefix(k, m.Node+".") { - if _, node, _, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { - own = append(own, k) - } + if _, node, id, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { + own, ids[k] = append(own, k), id } } - sort.Sort(sort.Reverse(sort.StringSlice(own))) + sort.SliceStable(own, func(i, j int) bool { return ids[own[i]] > ids[own[j]] }) if n := min(max(limit*4, 100), MaxStateReads); len(own) > n { own, cut = own[:n], true } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/read_test.go b/modules/mesh-build-go/cmd/mesh-build-go/read_test.go index 880fa8962..8b5d2776a 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/read_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/read_test.go @@ -157,10 +157,12 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { reads int64 steps int cut bool + asked bool // design 47 H2 §801: the newest step is an ask's, keyed under its asker }{ - {20, 0, 20, 10, false}, - {600, 0, 100, 10, true}, - {1500, 300, MaxStateReads, 300, true}, + {20, 0, 20, 10, false, false}, + {600, 0, 100, 10, true, false}, + {1500, 300, MaxStateReads, 300, true, false}, + {19, 0, 20, 10, false, true}, } { var reads, inFlight, maxFlight atomic.Int64 stored := map[string][]byte{} @@ -170,6 +172,10 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { stored[n+".s"+fmt.Sprintf("%04d", i)] = b } } + if row.asked { + b, _ := sdkstep.EncodeStep(sdkstep.Step{ID: "s9999", Tool: "t", Node: "shanks", State: sdkstep.StepRunning, Started: t0.Add(time.Hour)}) + stored["mesh-pipeline-runner.shanks.s9999"] = b + } m := &Module{Node: "shanks"} m.ReadSteps = StateRead{ Keys: func() ([]string, error) { @@ -186,7 +192,7 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { } time.Sleep(time.Millisecond) inFlight.Add(-1) - if !strings.HasPrefix(key, "shanks.") { + if _, node, _, err := sdkstep.ParseStepKey(key); err != nil || node != "shanks" { t.Errorf("read %s, a key of another node", key) } return stored[key], nil @@ -200,6 +206,9 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { if row.cut && len(lines) > 0 && lines[0].ID != fmt.Sprintf("s%04d", row.perNode-1) { t.Errorf("%d a node: newest answered %s", row.perNode, lines[0].ID) } + if row.asked && (len(lines) == 0 || lines[0].ID != "s9999") { + t.Errorf("an ask's step under its asker is not the newest line: %+v", lines) + } if maxFlight.Load() < 2 { t.Errorf("%d a node: values read one at a time", row.perNode) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/run.go b/modules/mesh-build-go/cmd/mesh-build-go/run.go index 24c9e50eb..d89976cf1 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/run.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/run.go @@ -19,7 +19,7 @@ import ( "path/filepath" "strings" - checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker" + meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) @@ -50,22 +50,21 @@ func (m *Module) run(ctx context.Context, fetch steprun.StepFunc, a sdkstep.Step } // inputOf is the input a run names, asked of the seat verb the ask names (module.json invokes it) and checked against -// its digest and size: bytes that are not the input named refuse the ask. A verb marked chunks (the seat mesh-catalog's +// its digest and size: bytes that are not the input named refuse the ask. A verb marked chunks (the seats mesh-catalog's and mesh-wants' // input, of any size) is asked by the plain seat call: the tool runner receives the chunks and hands this module the -// whole file in the member `file` (design 47 G A-237, A-249); another seat's input answers its bytes in `input`. +// whole file in the member `file` (design 47 G A-237, A-249). func (m *Module) inputOf(in sdkstep.RunInput) ([]byte, error) { if m.AskInput == nil { return nil, errors.New("this module asks no seat verb for a run's input") } // A verb that does not answer fails the step; an answer that is not the input named refuses the ask. - raw, err := m.AskInput(in.Verb, checker.InputInput{Digest: in.Digest}) + raw, err := m.AskInput(in.Verb, meshwants.InputInput{Digest: in.Digest}) if err != nil { return nil, fmt.Errorf("asking %s for the input %s: %w", in.Verb, in.Digest, err) } var a struct { Digest string `json:"digest"` File string `json:"file"` - Input string `json:"input"` } if err := json.Unmarshal(raw, &a); err != nil { return nil, steprun.Refuse("%s answered no input for %s: %v", in.Verb, in.Digest, err) @@ -73,11 +72,7 @@ func (m *Module) inputOf(in sdkstep.RunInput) ([]byte, error) { if a.Digest != in.Digest { return nil, steprun.Refuse("%s answered the input %q, asked %s", in.Verb, a.Digest, in.Digest) } - text := a.File - if text == "" { - text = a.Input - } - body, err := base64.StdEncoding.DecodeString(text) + body, err := base64.StdEncoding.DecodeString(a.File) if err != nil { return nil, steprun.Refuse("%s answered the input %s in no base64: %v", in.Verb, in.Digest, err) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/run_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/run_integration_test.go index e09f87c49..369d93599 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/run_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/run_integration_test.go @@ -16,8 +16,7 @@ import ( "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" - checkerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient" - checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker" + meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" "git.novox.be/novox/mesh-sdk/go/testbus" @@ -25,7 +24,7 @@ import ( // 1921/C3: a run ask put on the Go build seat's check stream is pulled by the module started whole on the real bus and // answered on its step key .: the program, run shut off over its heads and its input (asked by digest of the -// seat verb the ask names, which a fake checker answers on the bus as the checker's verb input does), answers its last +// seat verb the ask names, which a fake assigner answers on the bus as the seat's verb input does), answers its last // line and exit; a program cannot write under its heads, and one // that dials the machine's network is shut off, and its key ends failed, the answer kept (design 47 G A-290). func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) { @@ -63,13 +62,13 @@ func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) { } m.PlaceHead = func(_ context.Context, h sdkstep.RunHead, dir string) error { return os.MkdirAll(dir, 0o700) } body := `{"v":1}` - // The checker's verb input on the bus, and the module asking it as the runtime calls a seat verb it invokes. + // The wants seat's verb input on the bus, and the module asking it as the runtime calls a seat verb it invokes. asked := make(chan string, 4) - sub, err := nc.Subscribe("mesh.seat.mesh-delivery-checker.tool.input", func(msg *nats.Msg) { - var ask checker.InputInput + sub, err := nc.Subscribe("mesh.seat.mesh-wants.tool.input", func(msg *nats.Msg) { + var ask meshwants.InputInput _ = json.Unmarshal(msg.Data, &ask) asked <- ask.Digest - reply, _ := json.Marshal(map[string]any{"result": checkerclient.InputAnswerOf([]byte(body))}) + reply, _ := json.Marshal(map[string]any{"result": inputAnswerOf([]byte(body))}) _ = msg.Respond(reply) }) if err != nil { @@ -81,7 +80,7 @@ func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) { return nil, errors.New("asked " + key) } data, _ := json.Marshal(b) - msg, err := nc.Request("mesh.seat.mesh-delivery-checker.tool.input", data, 5*time.Second) + msg, err := nc.Request("mesh.seat.mesh-wants.tool.input", data, 5*time.Second) if err != nil { return nil, err } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/run_test.go b/modules/mesh-build-go/cmd/mesh-build-go/run_test.go index 599c796c8..c88ca5284 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/run_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/run_test.go @@ -15,8 +15,7 @@ import ( "testing" "time" - checkerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient" - checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker" + meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" @@ -25,17 +24,24 @@ import ( const runCommit = "5555555555555555555555555555555555555555" -// runInputVerb is the seat verb a run ask's input is served on, as the checker names it in the ask. -const runInputVerb = checkerclient.InputVerb +// runInputVerb is the seat verb a run ask's input is served on, as the ask names it. +const runInputVerb = "seat:mesh-wants.input" -// answersInput is a seat verb serving body by its digest, as the checker's verb input answers (sdkstep.RunInputAnswer). +// inputAnswerOf is the seat mesh-wants's answer of the input body as the tool runner hands it over: the digest and +// the whole file. +func inputAnswerOf(body []byte) map[string]any { + sum := sha256.Sum256(body) + return map[string]any{"digest": hex.EncodeToString(sum[:]), "chunks": 1, "file": base64.StdEncoding.EncodeToString(body)} +} + +// answersInput is a seat verb serving body by its digest, as the seat mesh-wants' verb input answers. func answersInput(body string) func(key string, b any) (json.RawMessage, error) { return func(key string, b any) (json.RawMessage, error) { - ask, _ := b.(checker.InputInput) + ask, _ := b.(meshwants.InputInput) if sum := sha256.Sum256([]byte(body)); key != runInputVerb || ask.Digest != hex.EncodeToString(sum[:]) { - return nil, fmt.Errorf("the checker keeps no input %s", ask.Digest) + return nil, fmt.Errorf("the assigner keeps no input %s", ask.Digest) } - return json.Marshal(checkerclient.InputAnswerOf([]byte(body))) + return json.Marshal(inputAnswerOf([]byte(body))) } } @@ -45,7 +51,7 @@ func runAskOf(t *testing.T, body string) sdkstep.StepAsk { if err != nil { t.Fatal(err) } - return sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker", At: time.Now(), + return sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner", At: time.Now(), Run: &sdkstep.RunJob{Program: sdkstep.RunProgram{Repository: "novox/mesh-delivery", Commit: runCommit, Dir: ".", Package: "./cmd/prog"}, Heads: []sdkstep.RunHead{{Repository: "novox/mesh-sdk", Commit: runCommit}, {Repository: "novox/mesh-host", Commit: runCommit}}, Input: in, Args: []string{"-seats"}}} @@ -112,7 +118,7 @@ func TestAKeptProgramIsRunOverItsHeadsAndInput(t *testing.T) { m.Inside, m.Run = true, StepRunner(t.TempDir()) // An input other than the one named is refused, naming it; one the verb does not answer fails the step, saying why. m.AskInput = func(_ string, b any) (json.RawMessage, error) { - return json.Marshal(checker.InputAnswer{Digest: b.(checker.InputInput).Digest, Input: base64.StdEncoding.EncodeToString([]byte(`{"other":1}`))}) + return json.Marshal(map[string]any{"digest": b.(meshwants.InputInput).Digest, "chunks": 1, "file": base64.StdEncoding.EncodeToString([]byte(`{"other":1}`))}) } if _, err := m.run(context.Background(), fetch, a); err == nil || !strings.Contains(err.Error(), "is not the one the ask names") || !errors.As(err, new(*steprun.Refusal)) { t.Errorf("a wrong input: %v", err) @@ -182,22 +188,22 @@ func TestARunsInputIsAskedOfTheVerbTheAskNames(t *testing.T) { // answersInputOn is answersInput for the seat verb wanted. func answersInputOn(wanted, body string) func(key string, b any) (json.RawMessage, error) { return func(key string, b any) (json.RawMessage, error) { - ask, _ := b.(checker.InputInput) + ask, _ := b.(meshwants.InputInput) if sum := sha256.Sum256([]byte(body)); key != wanted || ask.Digest != hex.EncodeToString(sum[:]) { return nil, fmt.Errorf("%s keeps no input %s", key, ask.Digest) } - return json.Marshal(checkerclient.InputAnswerOf([]byte(body))) + return json.Marshal(inputAnswerOf([]byte(body))) } } -// Design 47 G A-237, A-249: the input of a run is of any size: the mesh-catalog seat's verb input, marked chunks, is asked by the +// Design 47 G A-237, A-249: the input of a run is of any size: the mesh-wants seat's verb input, marked chunks, is asked by the // plain seat call and answers {digest, chunks, file}, the file whole as the tool runner received it; the bytes are checked. func TestARunsInputOfAnySizeIsTakenFromTheChunkedVerb(t *testing.T) { body := strings.Repeat("0123456789", 300000) // 3 MB sum := sha256.Sum256([]byte(body)) in := sdkstep.RunInput{Verb: "seat:mesh-catalog.input", Digest: hex.EncodeToString(sum[:]), Size: len(body)} m := &Module{AskInput: func(key string, b any) (json.RawMessage, error) { - if ask, _ := b.(checker.InputInput); key != in.Verb || ask.Digest != in.Digest { + if ask, _ := b.(meshwants.InputInput); key != in.Verb || ask.Digest != in.Digest { return nil, fmt.Errorf("%s keeps no input %v", key, b) } return json.Marshal(map[string]any{"digest": in.Digest, "chunks": 6, "file": base64.StdEncoding.EncodeToString([]byte(body))}) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/steps.go b/modules/mesh-build-go/cmd/mesh-build-go/steps.go index c1aac6760..7f97be58d 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/steps.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/steps.go @@ -172,7 +172,7 @@ func (m *Module) steps(ctx context.Context, args map[string]any) (any, error) { // and by again (§326). if again, _ := args["again"].(bool); !again && fp != "" && m.ReadDetected != nil { if raw, err := m.ReadDetected(key); err == nil && len(raw) > 0 { - if kept, err := seat.DecodeDetectedStepsByModuleArtifactValue(raw); err == nil && kept.Fingerprint == fp { + if kept, _, err := seat.DecodeDetectedStepsByModuleArtifactValue(raw); err == nil && kept.Fingerprint == fp { return StepsAnswer{Artifact: artifact, Fingerprint: fp, Steps: kept.Steps, Kept: true}, nil } } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/store_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/store_integration_test.go index f33613e2d..402f2e463 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/store_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/store_integration_test.go @@ -139,8 +139,13 @@ func TestADoneBuildsArtifactsResolveInARealArtifactStore(t *testing.T) { m.Run = StepRunner(home) addr := realStore(t, m) done := builds.BuilderBuild{V: 1, State: builds.BuildDone, Manifest: strings.Repeat("0", 64)} - for _, a := range []struct{ name, kind string }{{"tools", "bundle"}, {"files", "archive"}} { - out, err := m.build(context.Background(), map[string]any{"workspace": "ws1", "module": ".", "artifact": a.name}) + // The bundle publishes under the ask's version, the archive by its digest alone (H-A-373 and its addendum). + for _, a := range []struct{ name, kind, version string }{{"tools", "bundle", askedVersion}, {"files", "archive", ""}} { + args := map[string]any{"workspace": "ws1", "module": ".", "artifact": a.name} + if a.version != "" { + args["version"] = a.version + } + out, err := m.build(context.Background(), args) if err != nil { t.Fatalf("%s: %v", a.name, err) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/test.go b/modules/mesh-build-go/cmd/mesh-build-go/test.go index e76b9b2c5..acc11705c 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/test.go @@ -42,7 +42,8 @@ func (m *Module) testTool() StepTool { "run": map[string]any{"type": "string", "description": "optional go test -run pattern: only the tests it matches run (a try's tests)"}, sdkstep.NodeNamesArg: map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "optional, the names of the mesh's nodes: the tests get them comma-separated in " + sdkstep.NodeNamesEnv + " (a check that keeps node names out of the repository reads them there)"}, - "runner": runnerProperty, + "runner": runnerProperty, + "archive": map[string]any{"type": "string", "description": "optional, at the integration level: the reference of the install archive in the artifact store (oci-artifact-registry//@), unpacked into the workspace's tree before the tests run (a package whose module's Go artifact names check-needs)"}, }, "required": []string{"workspace", "level"}, }, @@ -59,6 +60,21 @@ func (m *Module) unitBound() time.Duration { return UnitBound } +// stepsInHand is how many steps the seat has in hand at a step's start, this one counted, at least 1 (design 47 H2 +// H-A-488): a level's bounds are their defaults that many times, so a level set up slowly on a build node running +// several steps at once is not a failure. In the shut-off process, which holds no puller, it is 1: its spec carries +// the bounds already multiplied. +func (m *Module) stepsInHand() int { + n := 0 + switch { + case m.inHand != nil: + n = m.inHand() + case m.Held != nil: + n = m.Held.InHand() + } + return max(1, n) +} + func (m *Module) test(ctx context.Context, args map[string]any) (any, error) { workspace, _ := args["workspace"].(string) level, _ := args["level"].(string) @@ -85,14 +101,22 @@ func (m *Module) test(ctx context.Context, args map[string]any) (any, error) { if err != nil { return nil, err } + if archive, _ := args["archive"].(string); archive != "" { + // Design 47 H2 §800: the step's install archive is laid into the tree before go test. + if err := m.layInstall(ctx, workspace, tree, archive); err != nil { + return nil, err + } + } var res *TestResult + // The level's bounds, read once at the step's start (H-A-488): the result's bound and setup_bound name them. + inHand := m.stepsInHand() switch { case runner == RunnerWorkspace && (level == LevelUnit || level == LevelIntegration): - return m.testAsCandidate(ctx, workspace, level, packages, pattern, names) + return m.testAsCandidate(ctx, workspace, level, packages, pattern, names, inHand) case level == LevelUnit: - res, err = m.runLevel(ctx, tree, levelOpts{workspace: workspace, level: LevelUnit, packages: packages, run: pattern, bounds: Bounds{Run: m.unitBound()}, env: m.checkEnv(workspace, names)}) + res, err = m.runLevel(ctx, tree, levelOpts{workspace: workspace, level: LevelUnit, packages: packages, run: pattern, bounds: Bounds{Run: m.unitBound()}.times(inHand), env: m.checkEnv(workspace, names)}) case level == LevelIntegration: - res, err = m.integration(ctx, workspace, tree, packages, pattern) + res, err = m.integration(ctx, workspace, tree, packages, pattern, m.integrationBounds().times(inHand)) default: return nil, fmt.Errorf("the level %q is neither unit nor integration", level) } @@ -141,13 +165,13 @@ func compareGenerated(tree string, res *TestResult) error { // testAsCandidate runs a level as the candidate's program (ADR 0535 §1): the integration level is refused first as the // installed program would refuse it (no postgres), then the whole level runs in the candidate's one shut-off process. -func (m *Module) testAsCandidate(ctx context.Context, workspace, level string, packages []string, pattern string, names []string) (*TestResult, error) { - spec := levelSpec{Step: stepUnit, Workspace: workspace, Packages: packages, Run: pattern, Bound: m.unitBound(), NodeNames: names} +func (m *Module) testAsCandidate(ctx context.Context, workspace, level string, packages []string, pattern string, names []string, inHand int) (*TestResult, error) { + spec := levelSpec{Step: stepUnit, Workspace: workspace, Packages: packages, Run: pattern, Bound: m.unitBound() * time.Duration(inHand), NodeNames: names} if level == LevelIntegration { if _, err := m.checkPostgres(ctx); err != nil { return nil, err // a *steprun.Refusal: this level only } - b := m.integrationBounds() + b := m.integrationBounds().times(inHand) spec = levelSpec{Step: stepIntegration, Workspace: workspace, Packages: packages, Run: pattern, Setup: b.Setup, Bound: b.Run, NodeNames: names} } a, judged, err := m.asCandidate(ctx, spec) @@ -277,6 +301,7 @@ func (m *Module) runLevel(ctx context.Context, tree string, o levelOpts) (*TestR r runAnswer noise []string packages int + text string } var todo []string for _, d := range dirs { @@ -312,8 +337,9 @@ func (m *Module) runLevel(ctx context.Context, tree string, o levelOpts) (*TestR args = append(args, byDir[d]...) dr := &runs[i] dr.res = &TestResult{} - dr.r = run(ctx, append(m.goEnvFor(filepath.Join(tree, d)), o.env...), "go", args...) + dr.r = run(ctx, append(append(m.goEnvFor(filepath.Join(tree, d)), o.env...), levelBoundEnv(o.bounds)...), "go", args...) dr.noise, dr.packages = readGoTest(dr.res, d, dr.r.Stdout) + dr.text = goTestText(dr.r.Stdout) }() } wg.Wait() @@ -329,8 +355,10 @@ func (m *Module) runLevel(ctx context.Context, tree string, o levelOpts) (*TestR res.Tests += dr.res.Tests res.Skipped += dr.res.Skipped res.Failed = append(res.Failed, dr.res.Failed...) + res.NotRun = append(res.NotRun, dr.res.NotRun...) res.Packages = append(res.Packages, dr.res.Packages...) res.Slowest = append(res.Slowest, dr.res.Slowest...) + res.Output += dr.text if dr.res.Elapsed > res.Elapsed { res.Elapsed = dr.res.Elapsed } @@ -342,6 +370,18 @@ func (m *Module) runLevel(ctx context.Context, tree string, o levelOpts) (*TestR return res, nil } +// LevelBoundEnv is the word each level's tests get its bound in, as a duration ("10m0s"; design 47 H2 §800): mesh-sdk's +// test helpers take a setup bound of half of it, never a value in the test (testbus.SetupBound). +const LevelBoundEnv = "MESH_TEST_LEVEL_BOUND" + +// levelBoundEnv is the level's run bound as LevelBoundEnv, nothing when the level has none. +func levelBoundEnv(b Bounds) []string { + if b.Run <= 0 { + return nil + } + return []string{LevelBoundEnv + "=" + b.Run.String()} +} + // runAnswer is what a step runner answers. type runAnswer = forgekey.Ran diff --git a/modules/mesh-build-go/cmd/mesh-build-go/test_real_integration_test.go b/modules/mesh-build-go/cmd/mesh-build-go/test_real_integration_test.go index 7645d90bb..f5543591d 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/test_real_integration_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/test_real_integration_test.go @@ -166,7 +166,7 @@ func TestIntegrationLevelRunsAgainstARealStoreAndBusAndLeavesNothing(t *testing. home := t.TempDir() m := &Module{Recipe: Current(), Home: home, Work: work, Cache: t.TempDir()} m.Run = StepRunner(home) - res, err := m.integration(context.Background(), "ws1", filepath.Join(work, "ws1", "tree"), nil, "") + res, err := m.integration(context.Background(), "ws1", filepath.Join(work, "ws1", "tree"), nil, "", m.integrationBounds()) if err != nil { t.Fatalf("the integration level: %v", err) } @@ -206,7 +206,7 @@ func TestBuildTwiceGivesOneDigestAndOneExecutable(t *testing.T) { m := &Module{Home: home, Work: work, Cache: t.TempDir()} m.Run = StepRunner(home) withStore(t, m) - args := map[string]any{"workspace": "ws1", "module": ".", "artifact": "tools"} + args := map[string]any{"workspace": "ws1", "module": ".", "artifact": "tools", "version": askedVersion} // a bundle publishes under the ask's version (H-A-373) first, err := m.build(context.Background(), args) if err != nil { t.Fatal(err) diff --git a/modules/mesh-build-go/cmd/mesh-build-go/test_test.go b/modules/mesh-build-go/cmd/mesh-build-go/test_test.go index 779b4dba5..84bb0856e 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/test_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/test_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -101,6 +102,18 @@ func TestUnitLevelNamesTheFailingTestAndFailsTheLevel(t *testing.T) { if !good || res.Tests != 2 { t.Errorf("packages = %+v, tests = %d; want the good package passed with its test, 2 tests", res.Packages, res.Tests) } + + // Design 47 H2 §800: a test that says NOT RUN leaves its level passing, listed in the result's not-run with its reason. + m, states, ws, _ = workspaceFor(t, "notrun") + res, st = runUnit(t, m, states, ws) + want := []sdkstep.NotRun{{Test: "fixture/notrun/npm TestWithNpm", Reason: "npm is not on this node"}} + if st.State != sdkstep.StepPassed || !res.Passed || !slices.Equal(res.NotRun, want) { + t.Errorf("step %s, passed %v, not run %+v; want the level passing with not run %+v", st.State, res.Passed, res.NotRun, want) + } + // Design 47 H2 §791, H-A-412 (a): the level's answer carries its text in output, test2json's Output lines in order. + if !strings.HasPrefix(res.Output, "=== RUN TestTwo\n--- PASS: TestTwo (0.00s)\n") || !strings.Contains(res.Output, "NOT RUN: npm is not on this node") || strings.Contains(res.Output, `"Action"`) { + t.Errorf("the level's output is %q, want test2json's Output lines", res.Output) + } } // Issue 1921: a fixture with a failing test in each of two packages: one level's run names both, each with its own @@ -256,24 +269,35 @@ func TestUnitLevelOfAPackageThatDoesNotBuildFailsWithTheCompilersLine(t *testing } // The command is go test -json in the module's directory of the workspace, with the toolchain pinned to the installed -// one and the module's caches. +// one and the module's caches; the level's bound is its default times the steps in hand at the step's start, at least +// once (design 47 H2 H-A-488), and the result names it. func TestUnitLevelRunsGoTestJsonInTheModulesDirectoryWithTheStepsEnvironment(t *testing.T) { - m, states, ws, calls := workspaceFor(t, "empty") - runUnit(t, m, states, ws) - var line string - var env string - for _, c := range *calls { - if strings.HasPrefix(c.line, "go ") && strings.Contains(c.line, " test ") { - line, env = c.line, strings.Join(c.env, " ") + for _, row := range []struct { + inHand int + bound time.Duration + }{{0, UnitBound}, {1, UnitBound}, {4, 4 * UnitBound}} { + m, states, ws, calls := workspaceFor(t, "empty") + m.inHand = func() int { return row.inHand } + res, _ := runUnit(t, m, states, ws) + var line string + var env string + for _, c := range *calls { + if strings.HasPrefix(c.line, "go ") && strings.Contains(c.line, " test ") { + line, env = c.line, strings.Join(c.env, " ") + } } - } - want := "go -C " + filepath.Join(m.Work, ws, "tree", ".") + " test -json -count=1 -timeout 10m ./..." - if line != want { - t.Errorf("command = %q, want %q", line, want) - } - for _, w := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod")} { - if !strings.Contains(env, w) { - t.Errorf("environment %s lacks %s", env, w) + want := "go -C " + filepath.Join(m.Work, ws, "tree", ".") + " test -json -count=1 -timeout 10m ./..." + if line != want { + t.Errorf("command = %q, want %q", line, want) + } + // Design 47 H2 §800: the level's bound reaches the tests as MESH_TEST_LEVEL_BOUND, a duration. + for _, w := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "MESH_TEST_LEVEL_BOUND=" + row.bound.String()} { + if !strings.Contains(env, w) { + t.Errorf("%d in hand: environment %s lacks %s", row.inHand, env, w) + } + } + if res.Bound != row.bound.Seconds() { + t.Errorf("%d in hand: the result's bound is %v s, want %v", row.inHand, res.Bound, row.bound.Seconds()) } } } @@ -310,6 +334,7 @@ func TestATestOfAnUnknownWorkspaceOrAnotherLevelIsRefused(t *testing.T) { {"workspace": "ws1", "level": "stress"}, {"workspace": "ws1", "level": "unit", "packages": []any{"-run=x"}}, {"workspace": "ws1", "level": "unit", "packages": []any{"../x"}}, + {"workspace": "ws1", "level": "integration", "archive": "gitea/node-modules"}, // §800: an install archive the store does not name } { run(args) if st := states.waitEnd(t); st.State != sdkstep.StepFailed { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/README b/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/README index c2bebf153..f7331934c 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/README +++ b/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/README @@ -29,3 +29,6 @@ other digests; the tests therefore compare the stream always and the digest only The go-test-json-*.jsonl captures of issue 1901 (2026-10-23 and 2026-10-25) moved to mesh-sdk's conformance kit (go/buildstep/conformance/captured/go, with their description) on 2026-10-26, with the reader they test: the build module reads go test -json through buildstep.ReadGoTest and runs the kit (kit_test.go). + +notrun.json was captured the same way on 2026-11-22 (go1.27.3) for design 47 H2 §800 in repos/notrun: a passing test +beside one that skips with "NOT RUN: ". diff --git a/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/notrun.json b/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/notrun.json new file mode 100644 index 000000000..fcf6e370e --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/testdata/captured/notrun.json @@ -0,0 +1,13 @@ +{"Time":"2026-11-22T01:01:16.828741416+01:00","Action":"start","Package":"fixture/notrun/npm"} +{"Time":"2026-11-22T01:01:16.830715274+01:00","Action":"run","Package":"fixture/notrun/npm","Test":"TestTwo"} +{"Time":"2026-11-22T01:01:16.830773544+01:00","Action":"output","Package":"fixture/notrun/npm","Test":"TestTwo","Output":"=== RUN TestTwo\n","OutputType":"frame"} +{"Time":"2026-11-22T01:01:16.830797205+01:00","Action":"output","Package":"fixture/notrun/npm","Test":"TestTwo","Output":"--- PASS: TestTwo (0.00s)\n","OutputType":"frame"} +{"Time":"2026-11-22T01:01:16.830801905+01:00","Action":"pass","Package":"fixture/notrun/npm","Test":"TestTwo","Elapsed":0} +{"Time":"2026-11-22T01:01:16.830807995+01:00","Action":"run","Package":"fixture/notrun/npm","Test":"TestWithNpm"} +{"Time":"2026-11-22T01:01:16.830811005+01:00","Action":"output","Package":"fixture/notrun/npm","Test":"TestWithNpm","Output":"=== RUN TestWithNpm\n","OutputType":"frame"} +{"Time":"2026-11-22T01:01:16.830814835+01:00","Action":"output","Package":"fixture/notrun/npm","Test":"TestWithNpm","Output":" npm_test.go:12: NOT RUN: npm is not on this node\n"} +{"Time":"2026-11-22T01:01:16.830822885+01:00","Action":"output","Package":"fixture/notrun/npm","Test":"TestWithNpm","Output":"--- SKIP: TestWithNpm (0.00s)\n","OutputType":"frame"} +{"Time":"2026-11-22T01:01:16.830826595+01:00","Action":"skip","Package":"fixture/notrun/npm","Test":"TestWithNpm","Elapsed":0} +{"Time":"2026-11-22T01:01:16.830830225+01:00","Action":"output","Package":"fixture/notrun/npm","Output":"PASS\n","OutputType":"frame"} +{"Time":"2026-11-22T01:01:16.831057928+01:00","Action":"output","Package":"fixture/notrun/npm","Output":"ok \tfixture/notrun/npm\t0.002s\n"} +{"Time":"2026-11-22T01:01:16.831077789+01:00","Action":"pass","Package":"fixture/notrun/npm","Elapsed":0.002} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/go.mod b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/go.mod new file mode 100644 index 000000000..d8e47ef9a --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/go.mod @@ -0,0 +1,3 @@ +module fixture/notrun + +go 1.25.0 diff --git a/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm.go b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm.go new file mode 100644 index 000000000..187f97ac0 --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm.go @@ -0,0 +1,5 @@ +// Package npm is a fixture whose one test lacks the tooling its step gives. +package npm + +// Two is two. +func Two() int { return 2 } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm_test.go b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm_test.go new file mode 100644 index 000000000..faef1086e --- /dev/null +++ b/modules/mesh-build-go/cmd/mesh-build-go/testdata/repos/notrun/npm/npm_test.go @@ -0,0 +1,13 @@ +package npm + +import "testing" + +func TestTwo(t *testing.T) { + if Two() != 2 { + t.Errorf("Two() = %d, want 2", Two()) + } +} + +func TestWithNpm(t *testing.T) { + t.Skip("NOT RUN: npm is not on this node") +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/tools.go b/modules/mesh-build-go/cmd/mesh-build-go/tools.go index 73047dc8d..9a5ef62c8 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/tools.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/tools.go @@ -45,6 +45,7 @@ func (m *Module) Tools(steps []StepTool) []stdio.Tool { tools = append(tools, m.ReadTools()...) tools = append(tools, steprun.StepEndTool(StepEndTool, m.Node, m.stepScan(), m.Held)) tools = append(tools, m.releaseTool()) + tools = append(tools, pruneTools()...) tools = append(tools, m.keptTools()...) return append(tools, stdio.Tool{Name: StatusTool, diff --git a/modules/mesh-build-go/cmd/mesh-build-go/versions.go b/modules/mesh-build-go/cmd/mesh-build-go/versions.go index b54f52c96..cdb6ca864 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/versions.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/versions.go @@ -58,10 +58,10 @@ type downloadInfo struct { } // takeVersions writes the asked versions into the modfile of dir (d in the tree) and answers what it took, one entry per -// asked package its go.mod requires. A package go.mod replaces is built as go.mod says, and said. A version that can be +// asked package its go.mod requires that is not of the checked repository repository. A package go.mod replaces is built as go.mod says, and said. A version that can be // neither fetched nor found among the forge's pull request heads fails the fetch, naming it. pins serialises the // laid copies a workspace's directories share. -func (m *Module) takeVersions(ctx context.Context, root, dir, d string, asked sdkstep.PackageVersions, pins *sync.Mutex) ([]TakenVersion, error) { +func (m *Module) takeVersions(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, pins *sync.Mutex) ([]TakenVersion, error) { raw, err := os.ReadFile(filepath.Join(dir, "go.mod")) if err != nil { return nil, nil @@ -77,8 +77,8 @@ func (m *Module) takeVersions(ctx context.Context, root, dir, d string, asked sd var taken []TakenVersion for _, pkg := range slices.Sorted(maps.Keys(asked)) { named, ok := required[pkg] - if !ok { - continue // the module does not use it + if !ok || sameRepository(pkg, repository) { + continue // the module does not use it, or it is of the checked repository: built from its tree (takeOwnRequirements) } tv := TakenVersion{Dir: d, Package: pkg, Asked: asked[pkg], Named: named} switch { @@ -127,9 +127,18 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer tagged := sdkstep.PackageSemver.MatchString(tv.Asked) var r forgekey.Ran var info downloadInfo - r = m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked) + // The first download: a mesh package from the Go package registry seat alone (design 47 H, H-A-494 and its addendum). + env, err := m.registryEnv(m.goEnv()) + if err != nil { + return fmt.Errorf("%s@%s: %w", tv.Package, tv.Asked, err) + } + r = m.Run(ctx, env, "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked) _ = json.Unmarshal([]byte(r.Stdout), &info) failed := r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != "" + if failed && registryMiss(info.Error+"\n"+r.Err+"\n"+r.Stderr) && !commitOK.MatchString(tv.Asked) { + // Only a commit may still be a pull request's head (placePin); any other version the seat does not hold is its miss. + return registryMissed(tv.Package, tv.Asked, info.Error+"\n"+r.Err+"\n"+r.Stderr) + } if failed && tagged { failure := strings.TrimSpace(info.Error + "\n" + r.Err + "\n" + r.Stderr) return downloadFailure(failure, "downloading the group's tagged version %s of %s through the Go seat failed", tv.Asked, tv.Package) @@ -148,6 +157,9 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer where, err := m.placePin(ctx, root, p, failure) if errors.Is(err, errNotAHead) { pins.Unlock() + if registryMiss(failure) { + return registryMissed(tv.Package, tv.Asked, failure) + } // On no head, and go failed for another cause (the forge or the resolver did not answer): it fails with go's own // words, and not as a kind the builder holds until the module changes (issue 1748). return downloadFailure(failure, "downloading the asked version %s of %s failed", tv.Asked, tv.Package) @@ -188,6 +200,12 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer return m.takeRequirementsOf(ctx, pinsDir, info.GoMod) } +// registryMissed is the first download's miss: the Go package registry seat holds no such version of the package, said +// in the module's words with Go's beside them (design 47 H, H-A-494: a missing version fails loudly as the registry's miss). +func registryMissed(pkg, version, failure string) error { + return fmt.Errorf("the Go package registry holds no %s@%s: %s", pkg, version, causeLine(strings.TrimSpace(failure))) +} + // appendSums writes the checksums of one download (the module's and its go.mod's) into the go.sum in pinsDir. func appendSums(pinsDir, module string, info downloadInfo) error { sums := "" @@ -232,7 +250,8 @@ func (m *Module) takeRequirementsOf(ctx context.Context, pinsDir, gomodPath stri if strings.HasPrefix(module, forgePrefix) || (named[module] != "" && compareVersions(named[module], version) >= 0) { continue } - r := m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version) + // Never a module of the forge (above): the rest of the build list, through Go's public proxy alone (publicEnv). + r := m.Run(ctx, publicEnv(m.goEnv()), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version) var info downloadInfo _ = json.Unmarshal([]byte(r.Stdout), &info) if r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != "" { diff --git a/modules/mesh-build-go/cmd/mesh-build-go/versions_test.go b/modules/mesh-build-go/cmd/mesh-build-go/versions_test.go index cabcbe84d..82285d33c 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/versions_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/versions_test.go @@ -32,6 +32,7 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) { passing bool // the step ends failed as a transport fault, which the bus gives again (ADR 0664 §1) downloads int // the downloads asked in all (0: not counted) requires string // the go.mod of the version taken, its requirements to be taken too + unbound bool // the module holds no binding of the Go package registry seat }{ {name: "a trunk commit newer than go.mod's", asked: trunk, answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`, @@ -42,9 +43,6 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) { answer: `{"Path":"` + sdk + `","Version":"v0.1.16-0.20261116170327-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod=","GoMod":"GOMOD"}`, built: "v0.1.16-0.20261116170327-aaaaaaaaaaaa", edit: "-require=" + sdk + "@v0.1.16-0.20261116170327-aaaaaaaaaaaa", requires: "module " + sdk + "\n\ngo 1.26\n\nrequire (\n\tgithub.com/nats-io/nats.go v1.54.0\n\tgithub.com/klauspost/compress v1.20.0\n\tgit.novox.be/novox/mesh-contracts/go/x v0.1.0\n)\n"}, - {name: "go.mod names a newer one", asked: trunk, - answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261001000000-aaaaaaaaaaaa","Sum":"h1:zip="}`, - built: "v0.1.15-0.20261022120000-" + pinShort, said: "newer than the asked"}, {name: "a group's head Go cannot fetch", asked: commitSHA, failing: true, answer: `{"Path":"` + sdk + `","Error":"invalid version: unknown revision ` + pinShort + `"}`, built: commitSHA, said: "placed from the pull request's head"}, @@ -70,11 +68,17 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) { {name: "a group's tagged version", asked: "v0.1.15-feat-x.2", answer: `{"Path":"` + sdk + `","Version":"v0.1.15-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`, built: "v0.1.15-feat-x.2", edit: "-require=" + sdk + "@v0.1.15-feat-x.2"}, - {name: "a group's tagged version older than go.mod's", asked: "v0.1.14-feat-x.2", - answer: `{"Path":"` + sdk + `","Version":"v0.1.14-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`, - built: "v0.1.14-feat-x.2", said: "the group's tagged version", edit: "-require=" + sdk + "@v0.1.14-feat-x.2"}, - {name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the group's tagged version v0.1.15-feat-x.3", + // H-A-494: a version the Go package registry seat does not hold fails as its miss, naming @: the seat's 404, + // or, as Go words it with off behind the seat, the lookup off; a commit only once no pull request head carries it. + {name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.15-feat-x.3", answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.15-feat-x.3: reading https://seat/go/@v/v0.1.15-feat-x.3.info: 404 Not Found"}`}, + {name: "a release the Go seat lacks", asked: "v0.1.85", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.85", downloads: 1, + answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.85: module lookup disabled by GOPROXY=off"}`}, + {name: "a commit the Go seat lacks on no head", asked: offHead, failing: true, failsWith: "the Go package registry holds no " + sdk + "@" + offHead, downloads: 1, + answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@` + offHead + `: module lookup disabled by GOPROXY=off"}`}, + // H-A-494: with no binding of the seat, a mesh package is fetched from nowhere else: the fetch refuses. + {name: "no Go package registry bound", asked: trunk, unbound: true, failsWith: "no Go package registry bound", + answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`}, // ADR 0664 §1 (issue 1748): one download; a failure of the network is a transport fault the bus gives the ask again for after a // delay, no retry here; another failure is not one. {name: "an unknown revision is not taken again", asked: offHead, failing: true, failsWith: "on no pull request head", downloads: 1, @@ -85,6 +89,9 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) { t.Run(c.name, func(t *testing.T) { h, states := newPinHarness(t, pinnedGoMod, false, pullList) h.f.gomods = "go.mod\nother/go.mod\n" + if c.unbound { + h.m.GoSeatFile = "" + } downloads := 0 base := h.m.Run h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { @@ -130,6 +137,14 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) { t.Fatal(err) } st := states.waitEnd(t) + // H-A-494 addendum: a mesh package is downloaded from the Go package registry seat alone, off behind it. + for _, cmd := range h.cmds { + if strings.Contains(cmd.line, " mod download -json "+sdk+"@") { + if got := proxyValues(cmd.env); len(got) != 1 || got[0] != "GOPROXY="+testRegistry+",off" { + t.Errorf("%s: GOPROXY settings %v, want the seat alone and off", cmd.line, got) + } + } + } if c.downloads != 0 && downloads != c.downloads { t.Errorf("go downloaded %d times, want %d: no retry here", downloads, c.downloads) } diff --git a/modules/mesh-build-go/cmd/mesh-build-go/workspace.go b/modules/mesh-build-go/cmd/mesh-build-go/workspace.go index 2afd8fd14..c7ff57717 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/workspace.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/workspace.go @@ -167,7 +167,8 @@ func (m *Module) downloadBeside(ctx context.Context, root, tree string, dirs []s if err := os.WriteFile(file, []byte(work), 0o600); err != nil { return err } - env := append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly") // a workspace takes no -mod=mod + // The rest of a build list: through Go's public proxy alone (publicEnv; design 47 H, H-A-494 addendum). + env := publicEnv(append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly")) // a workspace takes no -mod=mod if res := m.Run(ctx, env, "go", "-C", r, "mod", "download"); res.Status != 0 || res.Err != "" { return fmt.Errorf("go mod download of the graph of %s beside: %s", filepath.Base(r), causeLine(res.Err+"\n"+res.Stdout+"\n"+res.Stderr)) } diff --git a/modules/mesh-build-go/go.mod b/modules/mesh-build-go/go.mod index c1a5aeead..51cca3973 100644 --- a/modules/mesh-build-go/go.mod +++ b/modules/mesh-build-go/go.mod @@ -9,10 +9,9 @@ require ( git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000 - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 diff --git a/modules/mesh-build-go/module.json b/modules/mesh-build-go/module.json index acc49284d..2de4a290b 100644 --- a/modules/mesh-build-go/module.json +++ b/modules/mesh-build-go/module.json @@ -1,6 +1,7 @@ { "module": "mesh-build-go", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds": "0.1", "git.novox.be/novox/mesh-catalog/modules/ssh-client/sshkeys": "0.1" @@ -13,9 +14,18 @@ "user-namespaces" ], "state": [ - "toolchains", - "keys", - "pauses" + { + "name": "toolchains", + "max-mib": 8 + }, + { + "name": "keys", + "max-mib": 8 + }, + { + "name": "pauses", + "max-mib": 8 + } ], "claims": [ { @@ -28,12 +38,15 @@ "resume", "steps", "kept-artifact", - "output" + "output", + "answer" ] } ], "consumes": [ - "mesh-conditions.findings-asked" + "mesh-conditions.findings-asked", + "mesh-catalog.seat-definition-changed", + "mesh-catalog.seat-definition-removed" ], "invokes": [ "seat:mesh-hand-acts.hand-act", @@ -41,11 +54,10 @@ "seat:oci-artifact-registry.publish-part", "seat:go-package-registry.publish", "seat:go-package-registry.publish-part", - "seat:mesh-delivery-checker.input", "seat:mesh-catalog.input", "seat:mesh-wants.input", - "seat:mesh-module-assigner.assignments", "seat:mesh-catalog.module", + "seat:mesh-catalog.seat-definitions", "seat:mesh-catalog.entry" ], "config": { @@ -66,6 +78,31 @@ "description": "How many processors one Go step of this module needs (a full check of a large repository takes what it is given: three at about 4 cores each ran past the 30-minute step bound on 2026-10-26). The capacity above is an upper bound: on each node the module runs at most floor(the cores of its build slice's CPU quota / this) steps at once, the quota read live from its cgroup (issue 1806), so a lowered build CPU share never starves its steps. Above 0.", "minimum": 0.1, "default": 6 + }, + "again-delays": { + "type": "string", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "trusted": false, + "runtime": true, + "default": "15s,60s" + }, + "prune-mark": { + "type": "number", + "description": "The fill of mesh-build-go's state detected-steps, in percent of its cap, past which the module prunes it at its own write, oldest first (design 47 H2 §812): below the bus module's raise mark of 75 %.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 70 + }, + "prune-target": { + "type": "number", + "description": "The fill, in percent of the cap, a prune of mesh-build-go's state detected-steps takes it down to (design 47 H2 §812); below prune-mark.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 50 } }, "tools": [ @@ -82,7 +119,9 @@ "build_go_step_end", "build_go_toolchains", "build_go_status", - "build_go_health" + "build_go_health", + "mesh-build-go_state_keep", + "mesh-build-go_state_prune_now" ], "requires": [ { @@ -91,7 +130,8 @@ "template": "state", "options": { "ttl-seconds": 172800, - "objects-max-mib": 256 + "objects-max-mib": 256, + "max-mib": 128 } }, { @@ -99,7 +139,17 @@ "storage": "key-value", "template": "state", "options": { - "history": 1 + "history": 1, + "max-mib": 8 + } + }, + { + "name": "outputs", + "storage": "object-store", + "template": "objects", + "options": { + "max-mib": 1024, + "max-age-days": 7 } }, { @@ -118,7 +168,10 @@ { "name": "findings", "storage": "key-value", - "template": "state" + "template": "state", + "options": { + "max-mib": 8 + } }, { "name": "finding-events", @@ -131,7 +184,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ], diff --git a/modules/mesh-build-image/cmd/mesh-build-image/asks.go b/modules/mesh-build-image/cmd/mesh-build-image/asks.go index 7872621cb..3c0c74a48 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/asks.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/asks.go @@ -9,6 +9,7 @@ import ( sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/busstate" ) // **The module pulls its seat's asks** (novox/hq ADR 0525 §2-§6; issue 1887 A3image), as mesh-build-go does: the seat @@ -31,16 +32,34 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps { Fetch: byName["build_image_fetch"], Build: byName["build_image_build"], Copy: byName["build_image_copy"], Release: func(ws string) error { return m.spaces().Release(ws) }, Logf: m.Say, + Node: m.Node, + SayStep: m.sayStep(), + Outputs: m.outputs(), } } +// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791, +// §820): Outputs when a test sets it, else the module's own objects store on the bus. +func (m *Module) outputs() steprun.OutputObjects { + if m.Outputs != nil { + return m.Outputs + } + return busstate.ObjectsOf(steprun.OutputsStore) +} + +// sayStep says a step ask's end on this node's subject of the seat (design 47 G §24): an image has no lint, unit or integration +// step (§328), so none is asked of this seat, but the steps of every build module can say their ends, which the kit holds. +func (m *Module) sayStep() func(sdkstep.StepEnded) error { + if m.SayStep != nil { + return m.SayStep + } + return steprun.SayStepOn(sdkstep.AskImage, m.Node, stdio.SeatPublish) +} + // Puller is the module's pull of its seat's asks, on source (the runtime's seat pull when nil). func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller { if source == nil { source = &steprun.SeatAsks{Language: sdkstep.AskImage, Logf: m.Say} - if m.Callers == nil { - m.Callers = steprun.SeatListCallers(sdkstep.AskImage, m.Say) - } } capacity := m.Capacity // The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config @@ -69,7 +88,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul if m.SayEvent != nil { say = steprun.SayOn(sdkstep.AskImage, m.Node, m.SayEvent) } - return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskImage, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, + return &steprun.Puller{KeepAnswer: steprun.KeepAnswerIn(m.Answers), Source: source, Language: sdkstep.AskImage, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Eligible: m.Eligible, Logf: m.Say, Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) { if err := m.Check(ctx); err != nil { @@ -84,7 +103,8 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul // SeatTools are the seat's verbs on this node (ADR 0525 §10). func (m *Module) SeatTools(p *steprun.Puller) []stdio.Tool { - return append(steprun.SeatTools(Seat, "image", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, steprun.ReadOutputFrom(m.Outputs))) + return append(steprun.SeatTools(Seat, "image", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, m.Node, m.outputs(), steprun.EndedHere(m.Node, m.ReadSteps.Keys, m.ReadSteps.Get)), + steprun.AnswerTool(Seat, steprun.ReadAnswerFrom(m.Answers))) } // StepEndTool ends one step left running (issue 1890); the module's steps state is the one it reads and writes. diff --git a/modules/mesh-build-image/cmd/mesh-build-image/asks_say_test.go b/modules/mesh-build-image/cmd/mesh-build-image/asks_say_test.go index dd42d4a9a..afe9e94e5 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/asks_say_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/asks_say_test.go @@ -11,15 +11,11 @@ import ( func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) { var subjects []string m := &Module{Node: "ace", Capacity: func() int { return 0 }, - Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" }, SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }} p := m.Puller(nil, steprun.NewFakeAsks()) if p.Say == nil { t.Fatal("the puller says no event") } - if got, ok := p.Callers("step"); !ok || len(got) != 1 { - t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok) - } seat, _ := sdkstep.BuildSeat(sdkstep.AskImage) for _, event := range []string{"ask-taken", "step-progress", "step-ended"} { if err := p.Say(event, nil, "id"); err != nil { diff --git a/modules/mesh-build-image/cmd/mesh-build-image/build_test.go b/modules/mesh-build-image/cmd/mesh-build-image/build_test.go index b110cc5ba..b8a6cdf14 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/build_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/build_test.go @@ -160,7 +160,7 @@ func TestBuildContextIsTheModulesDirectoryForADockerfileInASubdirectory(t *testi } // 1703c, issue 1703: a failing Dockerfile step fails the step, its reason saying buildah's error from stderr, never the -// last STEP line buildah writes on stdout; nothing is pushed. +// last STEP line buildah writes on stdout; nothing is pushed. A long stderr keeps its head and its tail (H-A-475). func TestBuildFailsWithBuildahsError(t *testing.T) { steps := "STEP 1/3: FROM docker.io/library/alpine\nSTEP 2/3: RUN apk add --no-cache ca-certificates\nfetch https://dl-cdn.alpinelinux.org/x\n" long := strings.Repeat("x", 2*CauseBytes) @@ -174,8 +174,8 @@ func TestBuildFailsWithBuildahsError(t *testing.T) { []string{"exit status 1", "Interactive authentication required", `building at STEP "RUN apk add`}, []string{"STEP 3/3", "COPY"}}, "a failed RUN": {forgekey.Ran{Status: 1, Stdout: steps, Stderr: "Error: building at STEP \"RUN false\": exit status 1\n"}, []string{`STEP "RUN false"`}, []string{"dl-cdn"}}, - "a long stderr is bounded, its end kept": {forgekey.Ran{Status: 125, Stdout: steps, Stderr: "early noise\n" + long + "\nError: the end\n"}, - []string{"Error: the end"}, []string{"early noise", long}}, + "a long stderr is bounded, its head and its end kept (H-A-475)": {forgekey.Ran{Status: 125, Stdout: steps, Stderr: "Error: the head\n" + long + "\nError: the end\n"}, + []string{"Error: the head", "bytes left out", "Error: the end"}, []string{long}}, "nothing on stderr": {forgekey.Ran{Status: 2, Stdout: steps}, []string{"exit status 2", "nothing on stderr", "dl-cdn"}, nil}, "never ran": {forgekey.Ran{Err: "ENOENT"}, []string{"ENOENT", "wrote nothing"}, nil}, "a pull the network cut": {forgekey.Ran{Status: 125, Stdout: steps, Stderr: "Error: creating build container: initializing source docker://alpine: pinging container registry registry-1.docker.io: Get \"https://registry-1.docker.io/v2/\": dial tcp: lookup registry-1.docker.io on 10.10.0.3:53: i/o timeout\n"}, diff --git a/modules/mesh-build-image/cmd/mesh-build-image/cause.go b/modules/mesh-build-image/cmd/mesh-build-image/cause.go index f0368b766..4c959fcfe 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/cause.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/cause.go @@ -2,7 +2,8 @@ package main // Why a command failed, as the command said it (issue 1703). buildah writes its progress (STEP n/m, the RUN's own // output) on stdout and its error on stderr, so the last line of both together is a STEP line and hides the error: -// a failure's reason is stderr's last lines, never stdout's, and the whole tail of stderr is said in the journal. +// a failure's reason is stderr's lines, never stdout's, its head and its tail kept within the bound (H-A-475), and more of +// both is said in the journal. import ( "fmt" @@ -18,15 +19,16 @@ const ( TailBytes = 4096 ) -// cause says why a command failed: its exit status (or why it never ran to one) and the last lines it wrote on stderr, -// at most CauseBytes of them, joined with " | ". Only when stderr is empty does stdout's tail stand in, said as such. +// cause says why a command failed: its exit status (or why it never ran to one) and the lines it wrote on stderr, +// joined with " | ", their head and their tail within CauseBytes. Only when stderr is empty does stdout stand in, said +// as such. func cause(r forgekey.Ran) string { head := exitOf(r) - if said := tailLines(r.Stderr, CauseBytes, " | "); said != "" { + if said := keptLines(r.Stderr, CauseBytes, " | "); said != "" { return head + ": " + said } - if said := tailLines(r.Stdout, CauseBytes, " | "); said != "" { - return head + ", nothing on stderr; stdout ends: " + said + if said := keptLines(r.Stdout, CauseBytes, " | "); said != "" { + return head + ", nothing on stderr; stdout says: " + said } return head + ", and it wrote nothing" } @@ -39,32 +41,31 @@ func exitOf(r forgekey.Ran) string { return fmt.Sprintf("exit status %d", r.Status) } -// tailLines is the last non-empty lines of s, trimmed, joined with sep, at most max bytes: the lines are taken whole -// from the end while they fit, and when even the last one does not, its end is kept behind "…". -func tailLines(s string, max int, sep string) string { +// keptLines is the non-empty lines of s, trimmed, joined with sep, at most max bytes: when they do not fit, their +// first and their last part within max, with "… bytes left out …" between them (H-A-475), so a tool's error line +// at the start is never pushed out by what follows it, nor the end by what precedes it. +func keptLines(s string, max int, sep string) string { var lines []string for _, l := range strings.Split(s, "\n") { if l = strings.TrimSpace(l); l != "" { lines = append(lines, l) } } - var keep []string - n := 0 - for i := len(lines) - 1; i >= 0; i-- { - add := len(lines[i]) - if len(keep) > 0 { - add += len(sep) - } - if n+add > max { - if len(keep) == 0 { - keep = append(keep, "…"+cutFront(lines[i], max-len("…"))) - } - break - } - keep = append([]string{lines[i]}, keep...) - n += add + all := strings.Join(lines, sep) + if len(all) <= max { + return all } - return strings.Join(keep, sep) + mark := func(n int) string { return fmt.Sprintf(" … %d bytes left out … ", n) } + room := max - len(mark(len(all))) + if room < 2 { + room = 2 + } + head := all[:room/2] + for len(head) > 0 && !utf8.RuneStart(all[len(head)]) { + head = head[:len(head)-1] + } + tail := cutFront(all, room-room/2) + return head + mark(len(all)-len(head)-len(tail)) + tail } // cutFront is the last at most max bytes of s, starting on a whole character. @@ -82,9 +83,9 @@ func cutFront(s string, max int) string { return s } -// sayFailure writes the tail of a failed command's stderr (and of its stdout, where buildah's RUN output goes) to the -// journal, so what the reason had to leave out can still be read there. +// sayFailure writes the head and the tail of a failed command's stderr (and of its stdout, where buildah's RUN output +// goes) to the journal, so what the reason had to leave out can still be read there. func (m *Module) sayFailure(what string, r forgekey.Ran) { - m.say("%s failed (%s); stderr ends:\n%s\nstdout ends:\n%s", what, exitOf(r), - tailLines(r.Stderr, TailBytes, "\n"), tailLines(r.Stdout, TailBytes, "\n")) + m.say("%s failed (%s); stderr:\n%s\nstdout:\n%s", what, exitOf(r), + keptLines(r.Stderr, TailBytes, "\n"), keptLines(r.Stdout, TailBytes, "\n")) } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/compose_test.go b/modules/mesh-build-image/cmd/mesh-build-image/compose_test.go index 827f5c85f..5dd0fc2f3 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/compose_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/compose_test.go @@ -24,7 +24,7 @@ func TestTheModuleInvokesTheImageSeatAndHoldsNoRegistry(t *testing.T) { t.Fatal(err) } if want := []string{"seat:mesh-hand-acts.hand-act", "seat:container-image-registry.publish", "seat:container-image-registry.publish-part", - "seat:container-image-registry.mirror", "seat:mesh-module-assigner.assignments", "seat:mesh-catalog.module"}; !slices.Equal(m.Invokes, want) { + "seat:container-image-registry.mirror", "seat:mesh-catalog.module", "seat:mesh-catalog.seat-definitions"}; !slices.Equal(m.Invokes, want) { t.Errorf("invokes = %v, want %v", m.Invokes, want) } // The seat's outcomes a copy waits on; the version comes in the ask, so version.numbered is not heard (design 47 G §413). @@ -32,6 +32,7 @@ func TestTheModuleInvokesTheImageSeatAndHoldsNoRegistry(t *testing.T) { for _, e := range OutcomeEvents { consumes = append(consumes, "container-image-registry."+e) } + consumes = append(consumes, "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed") // the seat list, A-488a if !slices.Equal(m.Consumes, consumes) { t.Errorf("consumes = %v, want %v", m.Consumes, consumes) } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/copy.go b/modules/mesh-build-image/cmd/mesh-build-image/copy.go index 9a09ca637..48a4da86f 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/copy.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/copy.go @@ -112,8 +112,8 @@ func (m *Module) copy(ctx context.Context, args map[string]any) (any, error) { raw, err := m.call()("seat:"+steprun.ImageSeat+"."+reg.VerbMirror, reg.MirrorInput{Name: module + "/" + name, Source: from, Digest: digest}) if err != nil { said.Refused(err) - // A seat verb's "no responders" with a holder named is a transport fault (ADR 0664 §1): the seat's tool runner is replaced. - err = steprun.HolderSilentOr(m.call(), steprun.ImageSeat, err) + // A seat verb's "no responders" is a transport fault with no seat call to learn why (design 47 H2 §799, ADR 0664 §1). + err = steprun.PublishFault(err) return nil, fmt.Errorf("%s%s: %s's mirror: %w", builds.NotStored, name, steprun.ImageSeat, err) } var answer reg.MirrorAnswer diff --git a/modules/mesh-build-image/cmd/mesh-build-image/forge_test.go b/modules/mesh-build-image/cmd/mesh-build-image/forge_test.go index 7e37eedc5..84d6c2982 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/forge_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/forge_test.go @@ -145,14 +145,17 @@ func TestForgeFilesRenderFromTheBoundValuesInTheModulesOwnHome(t *testing.T) { // template in the files/ archive (novox/hq ADR 0349 §2). func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *testing.T) { m := readForgeManifest(t) - // outputs: a run's answer over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313). - outputs := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256)}} - if want := []any{outputs, "forge-account", "rootless-image-build", "node-tools"}; !reflect.DeepEqual(m.Requires, want) { + // steps: a step's end over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313). + steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(8)}} + // outputs: a run's test output, read by the verb output (design 47 H2 §791, §820: 1 GiB, 7 days). + outputs := map[string]any{"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}} + if want := []any{steps, outputs, "forge-account", "rootless-image-build", "node-tools"}; !reflect.DeepEqual(m.Requires, want) { t.Errorf("requires = %v, want %v", m.Requires, want) } keeps := false for _, s := range m.State { - if s == "keys" { + // Design 47 H2 H-A-411 (2): every state names its cap, 8 MiB. + if e, _ := s.(map[string]any); e["name"] == "keys" && e["max-mib"] == float64(8) { keeps = true } } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go b/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go index 0d3bd0b29..4fde49f59 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go @@ -2,14 +2,19 @@ package main import ( "context" + "encoding/json" "errors" - sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" - "git.novox.be/novox/mesh-sdk/go/forgekey" + "os" + "path/filepath" "strings" "testing" "time" + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/buscalls" + "git.novox.be/novox/mesh-sdk/go/forgekey" + buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance" ) @@ -26,6 +31,30 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // ADR 0664 §1 (issue 1748): the module's own paths from a failed fetch or image build to its step's error say a network that // did not answer as a transport fault, and a failure of the source (a RUN line that fails) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { + // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its + // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + t.Run("again-delays is declared and read", func(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + var m struct { + Config map[string]json.RawMessage `json:"config"` + } + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + var c struct { + Default string `json:"default"` + Runtime bool `json:"runtime"` + } + decl, ok := m.Config[steprun.AgainDelaysSetting] + _ = json.Unmarshal(decl, &c) + delay, err := steprun.AgainDelays(c.Default) + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) + } + }) conformance.Passing(t, []string{conformance.GitFetch, conformance.BuildahBud}, func(runner, words string) error { switch runner { case conformance.GitFetch: @@ -44,3 +73,39 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { } }) } + +// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or +// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met. +func TestTheStepsCanSayAStepsEnd(t *testing.T) { + conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil)) + // Design 47 H2 §791, §801, H-A-412, H-A-421: the seat's verbs current, output and answer keep the build-step part's form 2, + // and a pipeline step's run output is kept in the module's outputs objects and read back through output. + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }, Outputs: kitObjects{}} + conformance.SeatVerbs(t, Seat, m.SeatTools(m.Puller(nil, steprun.NewFakeAsks())), m.askSteps(nil)) +} + +// kitObjects is an outputs store in memory, for the kit's SeatVerbs. +type kitObjects map[string][]byte + +func (k kitObjects) Put(name string, data []byte, _ string) (buscalls.ObjectInfo, error) { + k[name] = data + return buscalls.ObjectInfo{Name: name}, nil +} + +func (k kitObjects) Get(name string) (buscalls.ObjectData, error) { + d, ok := k[name] + if !ok { + return buscalls.ObjectData{}, errors.New("object not found") + } + return buscalls.ObjectData{Data: d}, nil +} + +// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before +// it ran is no run), so the poison rule never ends an ask that never ran. +func TestThePullerCountsRunsThatStarted(t *testing.T) { + conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller { + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }} + m.ReadSteps = StateRead{Get: read} + return m.Puller(nil, steprun.NewFakeAsks()) + }) +} diff --git a/modules/mesh-build-image/cmd/mesh-build-image/main.go b/modules/mesh-build-image/cmd/mesh-build-image/main.go index 47a0bfd23..f9bbd7227 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/main.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/main.go @@ -67,10 +67,18 @@ func main() { logf("announcing the states it keeps: %v", err) os.Exit(1) } - m.Outputs = busstate.ObjectsOf(steprun.OutputsStore) + m.Answers = busstate.ObjectsOf(steprun.AnswersStore) steps := m.StepTools() booted := time.Now() puller := m.Puller(steps, nil) + // A step whose fetch or publish met its holder away is given again after again-delays (design 47 H2 §799; H-A-390). + againSetting, _ := stdio.Setting(steprun.AgainDelaysSetting) + againDelay, againErr := steprun.AgainDelays(againSetting) + if againErr != nil { + logf("the setting %s: %v", steprun.AgainDelaysSetting, againErr) + os.Exit(1) + } + puller.Delay = againDelay m.Held = puller if m.Node != "" { // A step a previous process left running is ended (issue 1890): one that names another owner, or none and diff --git a/modules/mesh-build-image/cmd/mesh-build-image/manifest_test.go b/modules/mesh-build-image/cmd/mesh-build-image/manifest_test.go index 5a8fd6111..82008d5a4 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/manifest_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/manifest_test.go @@ -113,6 +113,20 @@ func TestWorkAndStoreDirectoriesLieOutsideTheHome(t *testing.T) { // and the registry's address is bound into a file of the home that the program reads. func TestManifestKeepsItsStatesClaimsItsBuildSeatAndDeclaresItsHealthTool(t *testing.T) { m := readManifest(t) + // Design 47 H2 H-A-411 (2): a core module. + if m.Class != catalogue.ClassCore { + t.Errorf("class = %q, want %s", m.Class, catalogue.ClassCore) + } + // Design 47 G A-488a, A-488b: its runtime follows the seat list, so the module consumes the seat's two events (which makes its + // durable consumer) and invokes the verb that reads the list. + for _, ev := range []string{"mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed"} { + if !slices.Contains(m.Consumes, ev) { + t.Errorf("consumes %v lack %s", m.Consumes, ev) + } + } + if !slices.Contains(m.Invokes, "seat:mesh-catalog.seat-definitions") { + t.Errorf("invokes %v lack seat:mesh-catalog.seat-definitions", m.Invokes) + } states := []string{} for _, s := range m.State { states = append(states, s.Name) @@ -126,7 +140,7 @@ func TestManifestKeepsItsStatesClaimsItsBuildSeatAndDeclaresItsHealthTool(t *tes if want := []string{"keys", MirrorWaitsState, "pauses"}; !slices.Equal(states, want) { t.Errorf("state = %v, want %v", states, want) } - if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output"}) { + if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output", "answer"}) { t.Errorf("claims = %v, want the seat %s alone", m.Claims, Seat) } raw, _ := os.ReadFile(filepath.Join(moduleDir, "module.json")) @@ -213,8 +227,9 @@ func TestTheModuleRequiresNodeToolsItPullsThrough(t *testing.T) { } } -// Design 47 G A-254, A-313, A-314: the module keeps a run's answer over what step-ended carries inline in the steps state's own -// objects store, sized in `requires` by the state option objects-max-mib, and serves it through the verb output. +// Design 47 G A-254, A-313, A-314: the module keeps a step's end over what step-ended carries inline in the steps state's own +// objects store, sized in `requires` by the state option objects-max-mib, and serves it through the verb answer (H2 H-A-412 +// addendum); and a run's test output in its outputs objects, 1 GiB kept 7 days, read by the verb output (H2 §791, §820). func TestManifestRequiresTheStepsStateWithItsObjectsStore(t *testing.T) { raw, err := os.ReadFile(moduleDir + "/module.json") if err != nil { @@ -226,11 +241,12 @@ func TestManifestRequiresTheStepsStateWithItsObjectsStore(t *testing.T) { if err := json.Unmarshal(raw, &doc); err != nil { t.Fatal(err) } - want := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256)}} - for _, r := range doc.Requires { - if reflect.DeepEqual(r, want) { - return + for _, want := range []map[string]any{ + {"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(8)}}, + {"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}}, + } { + if !slices.ContainsFunc(doc.Requires, func(r any) bool { return reflect.DeepEqual(r, any(want)) }) { + t.Errorf("requires %v lack %v", doc.Requires, want) } } - t.Errorf("requires %v lack %v", doc.Requires, want) } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/module.go b/modules/mesh-build-image/cmd/mesh-build-image/module.go index e8dca05dc..2e24457e7 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/module.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/module.go @@ -20,14 +20,17 @@ const CheckRound = 10 * time.Minute // Module is the image build module's one running state. type Module struct { - // Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when - // the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163. - Callers func(kind string) ([]string, bool) - // Outputs is the object store of a run's answers over what step-ended carries inline (steprun.OutputsStore); nil keeps none. + // Answers is the steps state's objects (steprun.AnswersStore), where a step's end over what its key or step-ended + // carries is kept and the seat's verb answer reads it (design 47 H2 H-A-412 addendum); nil keeps none. + Answers steprun.OutputObjects + // Outputs are the outputs objects (steprun.OutputsStore) a test step keeps a run's output in, which the verb output + // reads (design 47 H2 §791); nil is the module's own on the bus (outputs), a test sets its own. Outputs steprun.OutputObjects // SayEvent publishes an event of the image build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the // puller's ask-taken, step-progress and step-ended (design 47 G §496, §602). SayEvent func(subject string, body any, id string) error + // SayStep says a step ask's end (steprun.AskSteps.SayStep); the seat's publish on this node when nil (a test's own). + SayStep func(sdkstep.StepEnded) error Node string // RecordAct writes an act in the hand-act log of the seat mesh-hand-acts (§463, §480): a drop writes it first. diff --git a/modules/mesh-build-image/cmd/mesh-build-image/read.go b/modules/mesh-build-image/cmd/mesh-build-image/read.go index d37522613..bd3402064 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/read.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/read.go @@ -146,15 +146,15 @@ func (m *Module) RecentSteps(limit int) (lines []StepLine, cut bool, err error) if err != nil { return nil, false, err } - own := keys[:0:0] + // Every key of this node's steps, an ask's under its asker (`..`) as well as `.` (design 47 + // H2 §801): the tool is never empty while asks run. Ordered by the id, newest first. + own, ids := keys[:0:0], map[string]string{} for _, k := range keys { - if strings.HasPrefix(k, m.Node+".") { - if _, node, _, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { - own = append(own, k) - } + if _, node, id, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { + own, ids[k] = append(own, k), id } } - sort.Sort(sort.Reverse(sort.StringSlice(own))) + sort.SliceStable(own, func(i, j int) bool { return ids[own[i]] > ids[own[j]] }) if n := min(max(limit*4, 100), MaxStateReads); len(own) > n { own, cut = own[:n], true } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/read_test.go b/modules/mesh-build-image/cmd/mesh-build-image/read_test.go index 9776771ce..338259e68 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/read_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/read_test.go @@ -3,7 +3,6 @@ package main import ( "encoding/json" "fmt" - "strings" "sync/atomic" "testing" "time" @@ -58,10 +57,12 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { reads int64 steps int cut bool + asked bool // design 47 H2 §801: the newest step is an ask's, keyed under its asker }{ - {20, 0, 20, 10, false}, - {600, 0, 100, 10, true}, - {1500, 300, MaxStateReads, 300, true}, + {20, 0, 20, 10, false, false}, + {600, 0, 100, 10, true, false}, + {1500, 300, MaxStateReads, 300, true, false}, + {19, 0, 20, 10, false, true}, } { var reads, inFlight, maxFlight atomic.Int64 stored := map[string][]byte{} @@ -71,6 +72,10 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { stored[n+".s"+fmt.Sprintf("%04d", i)] = b } } + if row.asked { + b, _ := sdkstep.EncodeStep(sdkstep.Step{ID: "s9999", Tool: "t", Node: "shanks", State: sdkstep.StepRunning, Started: t0.Add(time.Hour)}) + stored["mesh-pipeline-runner.shanks.s9999"] = b + } m := &Module{Node: "shanks"} m.ReadSteps = StateRead{ Keys: func() ([]string, error) { @@ -87,7 +92,7 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { } time.Sleep(time.Millisecond) inFlight.Add(-1) - if !strings.HasPrefix(key, "shanks.") { + if _, node, _, err := sdkstep.ParseStepKey(key); err != nil || node != "shanks" { t.Errorf("read %s, a key of another node", key) } return stored[key], nil @@ -101,6 +106,9 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { if row.cut && len(lines) > 0 && lines[0].ID != fmt.Sprintf("s%04d", row.perNode-1) { t.Errorf("%d a node: newest answered %s", row.perNode, lines[0].ID) } + if row.asked && (len(lines) == 0 || lines[0].ID != "s9999") { + t.Errorf("an ask's step under its asker is not the newest line: %+v", lines) + } if maxFlight.Load() < 2 { t.Errorf("%d a node: values read one at a time", row.perNode) } diff --git a/modules/mesh-build-image/module.json b/modules/mesh-build-image/module.json index 3da2c35c5..4ef6ba7b6 100644 --- a/modules/mesh-build-image/module.json +++ b/modules/mesh-build-image/module.json @@ -1,6 +1,7 @@ { "module": "mesh-build-image", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds": "0.1", "git.novox.be/novox/mesh-catalog/modules/ssh-client/sshkeys": "0.1" @@ -13,15 +14,15 @@ "user-namespaces" ], "state": [ - "keys", - "pauses", - {"name": "mirror-waits", "ttl-seconds": 172800} + {"name": "keys", "max-mib": 8}, + {"name": "pauses", "max-mib": 8}, + {"name": "mirror-waits", "ttl-seconds": 172800, "max-mib": 8} ], "claims": [ { "name": "node-build-image", "scope": "node", - "serves": ["current", "drop", "pause", "resume", "steps", "kept-artifact", "output"] + "serves": ["current", "drop", "pause", "resume", "steps", "kept-artifact", "output", "answer"] } ], "config": { @@ -42,6 +43,13 @@ "description": "How many processors one image step of this module needs (buildah, whose RUN lines are mostly fetches). The capacity above is an upper bound: on each node the module runs at most floor(the cores of its build slice's CPU quota / this) steps at once, the quota read live from its cgroup (issue 1806), so a lowered build CPU share never starves its steps. Above 0.", "minimum": 0.1, "default": 2 + }, + "again-delays": { + "type": "string", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "trusted": false, + "runtime": true, + "default": "15s,60s" } }, "tools": [ @@ -57,7 +65,8 @@ "build_image_health" ], "requires": [ - {"name": "steps", "storage": "key-value", "template": "state", "options": {"ttl-seconds": 172800, "objects-max-mib": 256}}, + {"name": "steps", "storage": "key-value", "template": "state", "options": {"ttl-seconds": 172800, "objects-max-mib": 256, "max-mib": 8}}, + {"name": "outputs", "storage": "object-store", "template": "objects", "options": {"max-mib": 1024, "max-age-days": 7}}, "forge-account", "rootless-image-build", "node-tools" @@ -67,12 +76,14 @@ "seat:container-image-registry.publish", "seat:container-image-registry.publish-part", "seat:container-image-registry.mirror", - "seat:mesh-module-assigner.assignments", - "seat:mesh-catalog.module" + "seat:mesh-catalog.module", + "seat:mesh-catalog.seat-definitions" ], "consumes": [ "container-image-registry.published", - "container-image-registry.refused" + "container-image-registry.refused", + "mesh-catalog.seat-definition-changed", + "mesh-catalog.seat-definition-removed" ], "own-secrets": { "broker": "${dir:state}/broker" diff --git a/modules/mesh-build-node/cmd/mesh-build-node/announce.go b/modules/mesh-build-node/cmd/mesh-build-node/announce.go index 642d81767..8342594ac 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/announce.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/announce.go @@ -1,7 +1,7 @@ package main // What this module keeps on the bus, announced from its code (novox/hq ADR 0495 §2 §5; issue 1790): every state it -// keeps, each readable by others, since another module reads each today (the builder, the checker and the indexer read toolchains; the builder and the checker read steps; gitea reads keys). A state of its own that it +// keeps, each readable by others, since another module reads each today (the builder and the indexer read toolchains; the builder reads steps; gitea reads keys). A state of its own that it // did not name here is refused at the call (stdio.Keeps). import ( diff --git a/modules/mesh-build-node/cmd/mesh-build-node/asks.go b/modules/mesh-build-node/cmd/mesh-build-node/asks.go index de769feeb..d8abc5872 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/asks.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/asks.go @@ -5,11 +5,13 @@ import ( "path/filepath" "time" + nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode" buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/busstate" ) // **The module pulls its seat's asks** (novox/hq ADR 0525 §2-§6, ADR 0536 §4; issue 1887 A3node), as mesh-build-go @@ -31,6 +33,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps { } return steprun.AskSteps{ Fetch: byName["build_node_fetch"], Build: byName["build_node_build"], Test: byName["build_node_test"], + // The npm packages its bundles import, read after the build and said as imports-reported (design 47 H2 H-A-523, + // H-A-532 DQ-6, H-A-539). + Imports: byName[ImportsTool], Compare: steprun.CompareStep(steprun.GeneratedRootTS, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }), Toolchain: func(ctx context.Context) (sdkstep.ToolchainUsed, error) { installed, err := m.Probe(ctx) @@ -41,16 +46,49 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps { }, Release: func(ws string) error { return m.spaces().Release(ws) }, Logf: m.Say, + Has: m.Has, + Install: m.installTreeStep, + Lint: m.lintStep, + Node: m.Node, + SayStep: m.sayStep(), + // A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517, + // H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's). + SayImports: m.sayImports(), + Outputs: m.outputs(), } } +// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with +// SayEvent; nil when the module says no event. +func (m *Module) sayImports() func(nodebuildgo.ImportsReported) error { + if m.SayEvent == nil { + return nil + } + return steprun.SayImportsOn(sdkstep.AskNode, m.Node, m.SayEvent) +} + +// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791, +// §820): Outputs when a test sets it, else the module's own objects store on the bus. +func (m *Module) outputs() steprun.OutputObjects { + if m.Outputs != nil { + return m.Outputs + } + return busstate.ObjectsOf(steprun.OutputsStore) +} + +// sayStep says a pipeline step's end on this node's subject of the seat (design 47 G §24, *Asked on a work queue, ended by an +// event*): SayStep when a test sets it, else the runtime's seat publish. +func (m *Module) sayStep() func(sdkstep.StepEnded) error { + if m.SayStep != nil { + return m.SayStep + } + return steprun.SayStepOn(sdkstep.AskNode, m.Node, stdio.SeatPublish) +} + // Puller is the module's pull of its seat's asks, on source (the runtime's seat pull when nil). func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller { if source == nil { source = &steprun.SeatAsks{Language: sdkstep.AskNode, Logf: m.Say} - if m.Callers == nil { - m.Callers = steprun.SeatListCallers(sdkstep.AskNode, m.Say) - } } capacity := m.Capacity // The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config @@ -79,7 +117,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul if m.SayEvent != nil { say = steprun.SayOn(sdkstep.AskNode, m.Node, m.SayEvent) } - return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskNode, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, + return &steprun.Puller{KeepAnswer: steprun.KeepAnswerIn(m.Answers), Source: source, Language: sdkstep.AskNode, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys, Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Logf: m.Say, Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) { if err := m.Prepare(ctx); err != nil { @@ -94,7 +132,8 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul // SeatTools are the seat's verbs on this node (ADR 0525 §10). func (m *Module) SeatTools(p *steprun.Puller) []stdio.Tool { - return append(steprun.SeatTools(Seat, "Node", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, steprun.ReadOutputFrom(m.Outputs))) + return append(steprun.SeatTools(Seat, "Node", p), m.stepsTool(), m.keptArtifactVerb(), steprun.OutputTool(Seat, m.Node, m.outputs(), steprun.EndedHere(m.Node, m.ReadSteps.Keys, m.ReadSteps.Get)), + steprun.AnswerTool(Seat, steprun.ReadAnswerFrom(m.Answers))) } // StepEndTool ends one step left running (issue 1890); the module's steps state is the one it reads and writes. diff --git a/modules/mesh-build-node/cmd/mesh-build-node/asks_say_test.go b/modules/mesh-build-node/cmd/mesh-build-node/asks_say_test.go index 3ab0b2618..29c03bcdf 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/asks_say_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/asks_say_test.go @@ -1,8 +1,12 @@ package main import ( + "context" + "errors" + "slices" "testing" + nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" ) @@ -11,15 +15,11 @@ import ( func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) { var subjects []string m := &Module{Node: "ace", Capacity: func() int { return 0 }, - Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" }, SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }} p := m.Puller(nil, steprun.NewFakeAsks()) if p.Say == nil { t.Fatal("the puller says no event") } - if got, ok := p.Callers("step"); !ok || len(got) != 1 { - t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok) - } seat, _ := sdkstep.BuildSeat(sdkstep.AskNode) for _, event := range []string{"ask-taken", "step-progress", "step-ended"} { if err := p.Say(event, nil, "id"); err != nil { @@ -32,3 +32,43 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) { } } } + +// N1/AC1, N1/AC3 (design 47 H2 H-A-517, H-A-523, H-A-534): a done build of a TypeScript module says one imports-reported +// on the Node build seat's subject of the node, naming the mesh npm packages the imports step read; a failed build says +// none. +func TestADoneNodeBuildSaysItsImportSetAndAFailedOneNone(t *testing.T) { + var said []nodebuildgo.ImportsReported + var subjects []string + m := moduleWith(newStates(), "v26.10.0") + m.Outputs = kitObjects{} // a failed build keeps its error text as an output object, never on a bus here + m.SayEvent = func(subject string, body any, _ string) error { + subjects = append(subjects, subject) + said = append(said, body.(nodebuildgo.ImportsReported)) + return nil + } + steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) { + return ImportsResult{Imports: []string{"@novox/mesh-sdk"}}, nil + }}) + a := nodeAsk(sdkstep.AskDelivery) + a.Build.Fp = "src2:0456" + if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil { + t.Fatal(err) + } + want := "mesh.seat.node-build-node.event.imports-reported.ace" + if len(said) != 1 || subjects[0] != want || said[0].Module != "gitea" || said[0].Fingerprint != "src2:0456" || + said[0].Commit != askCommit || !slices.Equal(said[0].Imports, []string{"@novox/mesh-sdk"}) { + t.Fatalf("said %v on %v, want one imports-reported of gitea naming @novox/mesh-sdk on %s", said, subjects, want) + } + said = nil + for i := range steps { + if steps[i].Name == "build_node_build" { + steps[i].Run = func(context.Context, map[string]any) (any, error) { return nil, errors.New("tsc failed") } + } + } + if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err == nil { + t.Fatal("the failed build passed") + } + if len(said) != 0 { + t.Errorf("a failed build said %v", said) + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/asks_test.go b/modules/mesh-build-node/cmd/mesh-build-node/asks_test.go index 8bafad60c..d71fbbe53 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/asks_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/asks_test.go @@ -32,7 +32,7 @@ func fakeSteps(calls *[]string) []StepTool { } func nodeAsk(kind string) sdkstep.StepAsk { - a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: kind, Language: sdkstep.AskNode, Asker: "mesh-delivery-checker", At: time.Now()} + a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: kind, Language: sdkstep.AskNode, Asker: "mesh-delivery-runner", At: time.Now()} fetch := sdkstep.Fetch{Repository: "novox/mesh-catalog", Commit: askCommit} if kind == sdkstep.AskDelivery { a.Asker = "mesh-delivery-builder" @@ -115,6 +115,10 @@ func TestManifestTakesTheBuildCapacity(t *testing.T) { if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") { t.Errorf("the build-hours description names a node pair") } + // Design 47 H2 H-A-539: no scope tells a mesh package apart, so the module declares no setting import-scope. + if _, ok := doc.Config["import-scope"]; ok { + t.Errorf("the manifest declares import-scope, which H-A-539 withdrew") + } var capacity float64 _ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity) if capacity != 0 { diff --git a/modules/mesh-build-node/cmd/mesh-build-node/build.go b/modules/mesh-build-node/cmd/mesh-build-node/build.go index 85406fb0f..91d587776 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/build.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/build.go @@ -1,5 +1,7 @@ package main +// Design 47 H1, proof 2 again: the importer half of the edge mesh-delivery-sdk to mesh-build-node. + // The build step (novox/hq ADR 0405 §3 and §7, ADR 0469 §4; issue 1490): a TypeScript bundle of a fetched workspace // compiled with the toolchain's tsc, bundled with its esbuild, given its launchers, packed with mesh-sdk's Pack and // ended with the archive's digest. No network. The commands and flags are the build agent's, copied from @@ -44,16 +46,37 @@ type artifact struct { Paths []string `json:"paths"` } +// namedPath is the one path a package artifact names, cleaned, relative to its module's directory; false when it names +// none, several, or one outside the module. +func (a artifact) namedPath() (string, bool) { + if len(a.Paths) != 1 { + return "", false + } + p := path.Clean(strings.TrimSuffix(a.Paths[0], "/")) + if p == "." || path.IsAbs(p) || p == ".." || strings.HasPrefix(p, "../") { + return "", false + } + return p, true +} + +// narrowedAway says whether the package's one named path is absent from the module's directory dir: in a workspace +// narrowed to another artifact's paths, it is not this build's. +func (a artifact) narrowedAway(dir string) bool { + p, ok := a.namedPath() + if !ok { + return false + } + _, err := os.Lstat(filepath.Join(dir, filepath.FromSlash(p))) + return os.IsNotExist(err) +} + // packageDir is the directory of a package artifact relative to its module's directory in dir: the one path it names // when that is a directory of the module holding a package.json (the contracts folders: ts/seats//, each with its // own lock, ADR 0634 section 8), else the module's directory itself (a package that names no path, or source paths // beside the module's package.json: today's form). func (a artifact) packageDir(dir string) string { - if len(a.Paths) != 1 { - return "." - } - p := path.Clean(strings.TrimSuffix(a.Paths[0], "/")) - if p == "." || path.IsAbs(p) || p == ".." || strings.HasPrefix(p, "../") { + p, ok := a.namedPath() + if !ok { return "." } if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(p), "package.json")); err != nil { @@ -175,8 +198,9 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) { return nil, fmt.Errorf("packing %s: %w", a.Name, err) } // Published from this process once the build ended, a candidate's as a trunk build's (ADR 0498 §1 §2; CAT-BN3): the - // step answers the seat's reference, or fails not stored. The packed bytes are never written to the node (L9). - if err := m.publishOn(ctx, steprun.ArtifactSeat, a.module+"/"+a.Name, "bundle", "", digest, archive); err != nil { + // step answers the seat's reference, or fails not stored. The packed bytes are never written to the node (L9). The + // publish carries the version the ask reserved, so the builder marks the bundle against its reservation (H-A-372). + if err := m.publishOn(ctx, steprun.ArtifactSeat, a.module+"/"+a.Name, "bundle", version, digest, archive); err != nil { return nil, fmt.Errorf("%s%s: %w", builds.NotStored, a.Name, err) } files := []string{} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/build_integration_test.go b/modules/mesh-build-node/cmd/mesh-build-node/build_integration_test.go index 901fc6423..d8c0545ad 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/build_integration_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/build_integration_test.go @@ -58,22 +58,39 @@ func realMachine(t *testing.T) (*Module, string) { t.Fatalf("the toolchain copied from %s cannot be used: %v", from, err) } for _, id := range []string{"w1", "w2", "w3"} { - for p, body := range map[string]string{ + files := map[string]string{ "modules/m/module.json": `{"module":"m","build":{"artifacts":[{"name":"tools","kind":"bundle","language":"typescript","entrypoints":["tools/index.js"]}]}}`, "modules/m/package.json": `{"name":"m","type":"module","scripts":{"test":"node -e \"process.exit(0)\""}}`, "modules/m/tools/index.ts": "import { serveRegisteredOverStdio } from \"@novox/mesh-sdk/stdio\";\nexport const f: () => Promise = serveRegisteredOverStdio as () => Promise;\n", - } { + } + for p, body := range fetchedSDK { + files["modules/m/node_modules/@novox/mesh-sdk/"+p] = body + } + for p, body := range files { write(t, filepath.Join(work, id, "tree", filepath.FromSlash(p)), body, 0o644) } } return m, work } +// fetchedSDK is the SDK the fixture's workspaces hold where the fetch step places it, in the module's node_modules +// (fetch.go, placeSDK: the latest published release, ADR 0573 §2; design 47 G §571), made here because the integration +// level has no registry to fetch it from. The toolchain's lock names no SDK since §571, so a fixture that leaves it out +// reads one only from a toolchain installed before (main.137 and main.155: TS2307 once a build node installed the +// lock). It holds the one export the fixture and the launchers import. +var fetchedSDK = map[string]string{ + "package.json": `{"name":"@novox/mesh-sdk","version":"9.9.9","type":"module",` + + `"exports":{"./stdio":{"types":"./dist/stdio.d.ts","default":"./dist/stdio.js"}}}`, + "dist/stdio.js": "export async function serveRegisteredOverStdio() {}\n", + "dist/stdio.d.ts": "export declare function serveRegisteredOverStdio(): Promise;\n", +} + // 1490/AC2, 1491 and issue 1869, in one test so the toolchain is copied once: the real type-check and test script of the // fixture pass the unit level; a package whose test imports its own build output (as mesh-sdk's do) passes the unit level, // the test step emitting it with the real tsc, shut off, before the test script runs; and the fixture TypeScript bundle // importing @novox/mesh-sdk, built twice by the real tsc and esbuild, has equal digests, its archive holding the bundled -// .js, the .serve.mjs launcher and package.json. The unit levels run in w3, so the two builds' workspaces stay alike. +// .js, the .serve.mjs launcher and package.json, and its imports step names the SDK. The unit levels run in w3, so the +// two builds' workspaces stay alike. func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) { m, work := realMachine(t) out, err := m.test(context.Background(), map[string]any{"workspace": "w3", "module": "modules/m", "level": "unit"}) @@ -101,7 +118,7 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) { } var digests []string for _, id := range []string{"w1", "w2"} { - out, err := m.build(context.Background(), map[string]any{"workspace": id, "module": "modules/m", "artifact": "tools"}) + out, err := m.build(context.Background(), map[string]any{"workspace": id, "module": "modules/m", "artifact": "tools", "version": askedVersion}) if err != nil { t.Fatal(err) } @@ -114,6 +131,15 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) { if digests[0] != digests[1] { t.Errorf("digests differ: %v", digests) } + // N1/AC1 (design 47 H2 H-A-523, H-A-532 DQ-6): the real esbuild's metafile of the built bundle names the SDK it + // imports, by its package name. + out, err = m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}) + if err != nil { + t.Fatal(err) + } + if got := out.(ImportsResult).Imports; !slices.Equal(got, []string{"@novox/mesh-sdk"}) { + t.Errorf("the bundle's imports = %v, want [@novox/mesh-sdk]", got) + } if links := symlinksUnder(t, work); len(links) != 0 { t.Errorf("symlinks in the workspaces: %v", links) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/build_test.go b/modules/mesh-build-node/cmd/mesh-build-node/build_test.go index b3621b268..59ac4799d 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/build_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/build_test.go @@ -5,6 +5,7 @@ import ( "bytes" "compress/gzip" "context" + "errors" "io" "maps" "os" @@ -55,8 +56,13 @@ func esbuildEffect(t *testing.T) func(c call) { } } +// askedVersion is the version a test's bundle ask reserved: every bundle publishes under the ask's version, and the +// delivery SDK refuses one that names none (design 47 H, H-A-373). +const askedVersion = "1.4.3" + +// buildArgs is a bundle's build ask, under the version the ask reserved. func buildArgs() map[string]any { - return map[string]any{"workspace": "w1", "module": "modules/m", "artifact": "tools"} + return map[string]any{"workspace": "w1", "module": "modules/m", "artifact": "tools", "version": askedVersion} } func builtMachine(t *testing.T, extra string) (*Module, *fakeMachine, string) { @@ -268,8 +274,9 @@ func TestTheLaunchersAreTheSDKsRule(t *testing.T) { } } -// issue 1703: a failed command's reason keeps stderr's end and stdout's start, each bounded, so a long stdout (npm's -// progress) never pushes npm's error out, and tsc's first error on stdout stays in. +// issue 1703: a failed command's reason keeps stderr's head and end and stdout's start, each bounded, so a long stdout +// (npm's progress) never pushes npm's error out, and tsc's first error on stdout stays in. H-A-475: esbuild's error line +// at the head of stderr stays in before its Node launcher's stack trace, the part left out said by its size. func TestRanFailedKeepsTheError(t *testing.T) { noise := strings.Repeat("npm progress line\n", 200) cases := map[string]struct { @@ -278,9 +285,11 @@ func TestRanFailedKeepsTheError(t *testing.T) { wantNot []string }{ "passed": {forgekey.Ran{Stdout: "ok"}, nil, nil}, - "npm, long stdout": {forgekey.Ran{Status: 1, Stdout: noise, Stderr: "npm ERR! early\n" + noise + "npm ERR! code E404\n"}, []string{"status 1", "npm ERR! code E404"}, []string{"npm ERR! early"}}, - "tsc on stdout": {forgekey.Ran{Status: 2, Stdout: "src/a.ts(1,7): error TS2322: wrong\n" + noise}, []string{"error TS2322"}, nil}, - "never ran": {forgekey.Ran{Err: "ENOENT"}, []string{"ENOENT"}, nil}, + "npm, long stdout": {forgekey.Ran{Status: 1, Stdout: noise, Stderr: "npm ERR! early\n" + noise + "npm ERR! code E404\n"}, []string{"status 1", "npm ERR! early", "bytes left out", "npm ERR! code E404"}, nil}, + "esbuild, a launcher's stack trace": {forgekey.Ran{Status: 1, Stderr: "✘ [ERROR] Could not resolve \"./missing\"\n" + strings.Repeat(" at Object. (/node_modules/esbuild/lib/main.js:1:1)\n", 40)}, + []string{"status 1", `[ERROR] Could not resolve "./missing"`, "bytes left out", "main.js:1:1)"}, nil}, + "tsc on stdout": {forgekey.Ran{Status: 2, Stdout: "src/a.ts(1,7): error TS2322: wrong\n" + noise}, []string{"error TS2322"}, nil}, + "never ran": {forgekey.Ran{Err: "ENOENT"}, []string{"ENOENT"}, nil}, } for name, c := range cases { got := ranFailed(c.ran) @@ -309,11 +318,13 @@ func TestTheBundleBuildGetsTheVersionTheAskCarriesAsMeshVersion(t *testing.T) { for _, version := range []string{"1.4.3", ""} { m, f, _ := builtMachine(t, "") args := buildArgs() - if version != "" { - args["version"] = version + args["version"] = version + if version == "" { + delete(args, "version") } - if _, err := m.build(context.Background(), args); err != nil { - t.Fatal(err) + // A bundle asked with no version is built with none, and its publish refused loudly (H-A-373). + if _, err := m.build(context.Background(), args); (err != nil) != (version == "") || err != nil && !strings.Contains(err.Error(), "names no version") { + t.Fatalf("ask version %q: %v", version, err) } for _, c := range f.calls { got := "" @@ -336,11 +347,13 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) { m, f, work := builtMachine(t, "") workspaceWith(t, work, map[string]string{"modules/m/package.json": `{"name":"m","version":"0.0.0"}`}) args := buildArgs() - if c.version != "" { - args["version"] = c.version + args["version"] = c.version + if c.version == "" { + delete(args, "version") } - if _, err := m.build(context.Background(), args); err != nil { - t.Fatal(err) + // A bundle asked with no version keeps the package.json's, and its publish is refused loudly (H-A-373). + if _, err := m.build(context.Background(), args); (err != nil) != (c.version == "") || err != nil && !strings.Contains(err.Error(), "names no version") { + t.Fatalf("ask version %q: %v", c.version, err) } _ = f raw, err := os.ReadFile(filepath.Join(work, "w1", "stage-tools", "modules", "module", "package.json")) @@ -349,3 +362,73 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) { } } } + +// N1/AC1, N1/AC2 (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): after a bundle's build, the imports step runs esbuild +// over the staged entrypoint and launcher with a metafile and answers every npm package among its inputs and external +// imports, each by its package name once (the SDK's stdio sub-path is the SDK), with no scope filter: a mesh package is +// told apart by the indexer, never by its scope. Node's own modules (node:module, fs) are no package; a bundle reaching +// only those answers none. Node's own modules are the probed toolchain's module.builtinModules, read at the step +// (principle 11), here holding sqlite, which no fixed list of Node 22 holds. +func TestTheImportsStepNamesTheNpmPackagesABundleReaches(t *testing.T) { + for _, c := range []struct { + name string + metafile string + want []string + }{ + {"packages", `{"inputs":{ + ".mesh-build/tools/tools/index.js":{"imports":[{"path":"../../node_modules/@novox/mesh-sdk/dist/stdio.js"},{"path":"@novox/mesh-other/x","external":true},{"path":"pg","external":true},{"path":"node:module","external":true},{"path":"fs","external":true},{"path":"sqlite","external":true}]}, + "../../node_modules/@novox/mesh-sdk/dist/stdio.js":{"imports":[]}, + "../../node_modules/@novox/mesh-sdk/dist/index.js":{"imports":[]}, + "../../node_modules/nats/lib/index.js":{"imports":[]}}}`, []string{"@novox/mesh-other", "@novox/mesh-sdk", "nats", "pg"}}, + {"none", `{"inputs":{".mesh-build/tools/tools/index.js":{"imports":[{"path":"node:module","external":true},{"path":"path","external":true}]}}}`, []string{}}, + } { + t.Run(c.name, func(t *testing.T) { + m, f, work := builtMachine(t, `,"external":["pg"]`) + m.Builtins = func(context.Context) ([]string, error) { return []string{"fs", "module", "path", "sqlite"}, nil } + bundled := f.effect + var metaRun []string + f.effect = func(cl call) { + bundled(cl) + for _, a := range cl.args { + if p, ok := strings.CutPrefix(a, "--metafile="); ok { + metaRun = cl.args + write(t, filepath.Join(cl.dir, p), c.metafile, 0o644) + } + } + } + if _, err := m.build(context.Background(), buildArgs()); err != nil { + t.Fatal(err) + } + if metaRun != nil { + t.Fatalf("the build itself ran esbuild with a metafile: %v", metaRun) + } + out, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}) + if err != nil { + t.Fatal(err) + } + if got := out.(ImportsResult).Imports; !slices.Equal(got, c.want) { + t.Errorf("imports %v, want %v", got, c.want) + } + last := f.calls[len(f.calls)-1] + if dir := filepath.Join(work, "w1", "stage-tools", "modules", "module"); last.dir != dir || + !slices.Contains(last.args, ".mesh-build/tools/tools/index.js") || !slices.Contains(last.args, ".mesh-build/tools/tools/index.serve.mjs") || + !slices.Contains(last.args, "--external:pg") || !slices.Contains(last.args, "--metafile=.mesh-build/tools.imports.json") { + t.Errorf("esbuild ran in %s as %v", last.dir, last.args) + } + }) + } +} + +// N1 (H-A-517): a workspace whose bundle was not built has no import set to read, and the step says so; a toolchain whose +// own modules cannot be read fails the step loud, never answering them as packages. +func TestTheImportsStepRefusesABundleNotBuilt(t *testing.T) { + m, _, _ := builtMachine(t, ``) + m.Builtins = func(context.Context) ([]string, error) { return nil, errors.New("no node") } + if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "Node's own modules") { + t.Errorf("imports with no builtins read: %v", err) + } + m.Builtins = func(context.Context) ([]string, error) { return []string{"fs"}, nil } + if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "was not built") { + t.Errorf("imports of an unbuilt bundle: %v", err) + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/check-needs b/modules/mesh-build-node/cmd/mesh-build-node/check-needs deleted file mode 100644 index 7d69db718..000000000 --- a/modules/mesh-build-node/cmd/mesh-build-node/check-needs +++ /dev/null @@ -1,3 +0,0 @@ -# Its integration tests copy the Node toolchain the Node build module installed on this node and run node and npm -# (realMachine, build_integration_test.go): they run only where the node holds node-build-node (issue 890). -node-build-node diff --git a/modules/mesh-build-node/cmd/mesh-build-node/check.go b/modules/mesh-build-node/cmd/mesh-build-node/check.go index 7945ba240..61f739b96 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/check.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/check.go @@ -26,13 +26,42 @@ import ( "git.novox.be/novox/mesh-sdk/go/forgekey" ) -// The bounds of a level (ADR 0445 §4). +// The bounds of a level (ADR 0445 §4). The integration level's setup bound is half of its bound, never a value of its +// own (design 47 H2 §800: the setup bound in code goes), as mesh-sdk's test helpers take theirs from LevelBoundEnv. const ( - UnitBound = 5 * time.Second - IntegrationSetupBound = 30 * time.Second - IntegrationRunBound = 60 * time.Second + UnitBound = 5 * time.Second + IntegrationRunBound = 60 * time.Second ) +// LevelBoundEnv is the word each level's tests get its bound in, as a duration ("1m0s"; design 47 H2 §800): mesh-sdk's +// test helpers take a setup bound of half of it. +const LevelBoundEnv = "MESH_TEST_LEVEL_BOUND" + +// levelBound is a level's bound while inHand steps are in hand (design 47 H2 H-A-488): its default that many times. +func levelBound(level string, inHand int) time.Duration { + if level == "unit" { + return UnitBound * time.Duration(inHand) + } + return IntegrationRunBound * time.Duration(inHand) +} + +// integrationSetupBound is the integration level's setup bound: half of its bound (§800). +func integrationSetupBound(inHand int) time.Duration { return levelBound("integration", inHand) / 2 } + +// stepsInHand is how many steps the seat has in hand at a step's start, this one counted, at least 1 (design 47 H2 +// H-A-488): a level's bounds are their defaults that many times, so a level set up slowly on a build node running +// several steps at once is not a failure. +func (m *Module) stepsInHand() int { + n := 0 + switch { + case m.inHand != nil: + n = m.inHand() + case m.Held != nil: + n = m.Held.InHand() + } + return max(1, n) +} + // TestResult is what a test step passes with, with the field names of mesh-build-go's (issue 1290). The step ends // passed whenever the level ran, whatever its verdict, and Passed is the verdict; it ends failed only when the tests // could not be run (no toolchain, a command that cannot start, a workspace that was never fetched). @@ -60,6 +89,10 @@ type TestResult struct { // By is the build module and the SDK it was built with (sdkstep.By): the checker names it when a failure hides // its cause. By string `json:"by,omitempty"` + // Output is the level's text (design 47 H2 §791, H-A-412 second addendum (a)): what each command the level ran wrote, + // its stdout then its stderr, in the order they ran. The delivery SDK's step run takes it out of the answer and keeps + // it as the run's output in the outputs objects; it is never part of a check's answer. + Output string `json:"output,omitempty"` // OutOfStep are the generated TypeScript files of a contracts module out of step with the seat generator (CAT-BN2, // steprun.OutOfStep): the unit level fails on any, Why naming each. Absent when none is. OutOfStep []string `json:"out-of-step,omitempty"` @@ -127,6 +160,8 @@ func (m *Module) testLevel(ctx context.Context, args map[string]any) (*TestResul return nil, err } res := &TestResult{Workspace: workspace, Module: module, Level: level, By: sdkstep.By("mesh-build-node")} + // The level's bounds, read once at the step's start (H-A-488): the result's bound and setup_bound name them. + inHand := m.stepsInHand() script := "test" if level == "integration" { script = "test:integration" @@ -135,12 +170,13 @@ func (m *Module) testLevel(ctx context.Context, args map[string]any) (*TestResul if where == "" { where = "." } - targets, err := testTargets(dir, where) + targets, err := testTargets(dir, where, narrowed(filepath.Join(root, "tree"))) if err != nil { return nil, err } var check, run time.Duration var failed []Failure + var text strings.Builder tested := false for _, tg := range targets { scripts, err := packageScripts(tg.dir) @@ -161,6 +197,8 @@ func (m *Module) testLevel(ctx context.Context, args map[string]any) (*TestResul } // a command that could not start is not a verdict: the step fails. One that ran and said no is. ran := func(name string, r forgekey.Ran, report string) error { + text.WriteString(r.Stdout) + text.WriteString(r.Stderr) if r.Err != "" { return fmt.Errorf("%s could not be run: status %d %s: %s", name, r.Status, r.Err, firstLine(r.Stderr)) } @@ -191,7 +229,7 @@ func (m *Module) testLevel(ctx context.Context, args map[string]any) (*TestResul report := filepath.Join(root, ".mesh-node-test-"+level+".tap") _ = os.Remove(report) env := []string{"PATH=" + binDir(root) + ":" + pathOrDefault(), "npm_config_cache=" + filepath.Join(m.Toolchain.Paths.Cache, "npm"), - "NODE_OPTIONS=" + steprun.NodeTestOptions(report)} + "NODE_OPTIONS=" + steprun.NodeTestOptions(report), LevelBoundEnv + "=" + levelBound(level, inHand).String()} r := m.runIn(ctx, root, false, tg.dir, env, "npm", scriptArgs(script)...) run += m.now().Sub(start) tap, _ := os.ReadFile(report) @@ -210,24 +248,26 @@ func (m *Module) testLevel(ctx context.Context, args map[string]any) (*TestResul } return res, nil } - res.Failed = failed + res.Failed, res.Output = failed, text.String() var why []string for _, f := range failed { why = append(why, failureWhy(f)) } if level == "unit" { - res.Elapsed, res.Bound = (check + run).Seconds(), UnitBound.Seconds() - res.OverBound = check+run > UnitBound + bound := levelBound(level, inHand) + res.Elapsed, res.Bound = (check + run).Seconds(), bound.Seconds() + res.OverBound = check+run > bound if res.OverBound { - why = append(why, fmt.Sprintf("the unit level took %.2f s, over its bound of %s", res.Elapsed, UnitBound)) + why = append(why, fmt.Sprintf("the unit level took %.2f s, over its bound of %s", res.Elapsed, bound)) } } else { res.Setup, res.Elapsed = check.Seconds(), run.Seconds() - res.SetupBound, res.Bound = IntegrationSetupBound.Seconds(), IntegrationRunBound.Seconds() - res.OverBound = check > IntegrationSetupBound || run > IntegrationRunBound + setup, bound := integrationSetupBound(inHand), levelBound(level, inHand) + res.SetupBound, res.Bound = setup.Seconds(), bound.Seconds() + res.OverBound = check > setup || run > bound if res.OverBound { why = append(why, fmt.Sprintf("the integration level took %.2f s of setup and %.2f s of running, over its bounds of %s and %s", - res.Setup, res.Elapsed, IntegrationSetupBound, IntegrationRunBound)) + res.Setup, res.Elapsed, setup, bound)) } } res.Passed = len(failed) == 0 @@ -338,8 +378,9 @@ type testTarget struct{ dir, where string } // testTargets are the directories a module's tests run in: each TypeScript package artifact's own path when every // package the module declares names one (ADR 0634 §8: its package.json, its lock, its tests), else the module's -// directory. -func testTargets(dir, where string) ([]testTarget, error) { +// directory. In a workspace narrowed to one artifact's paths (narrowedTree), a package whose path was left out is no +// target of this step (ADR 0499 clause 4; design 47 H, H-A-136). +func testTargets(dir, where string, narrowedTree bool) ([]testTarget, error) { whole := []testTarget{{dir, where}} raw, err := os.ReadFile(filepath.Join(dir, "module.json")) if err != nil { @@ -362,6 +403,9 @@ func testTargets(dir, where string) ([]testTarget, error) { if a.Kind != "package" { return whole, nil // a bundle is tested in its module's directory } + if narrowedTree && a.narrowedAway(dir) { + continue + } at := a.packageDir(dir) if at == "." { return whole, nil diff --git a/modules/mesh-build-node/cmd/mesh-build-node/check_test.go b/modules/mesh-build-node/cmd/mesh-build-node/check_test.go index ebc1ce0c3..61a196003 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/check_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/check_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" "git.novox.be/novox/mesh-sdk/go/forgekey" ) @@ -110,6 +111,7 @@ func TestTheIntegrationLevelRunsItsScriptAndReportsSetupAndRunningApart(t *testi workspaceWith(t, work, map[string]string{"index.ts": `export const a = 1;`, "tsconfig.json": `{}`, "package.json": `{"scripts":{"test":"x","test:integration":"node --test int"}}`}) f.cost["tsc"], f.cost["npm"] = 2*time.Second, 40*time.Second + f.answer["npm"] = forgekey.Ran{Stdout: "ok 1 - joins\n", Stderr: "(node) warning\n"} out, err := m.test(context.Background(), testArgs("integration")) if err != nil { t.Fatal(err) @@ -122,6 +124,14 @@ func TestTheIntegrationLevelRunsItsScriptAndReportsSetupAndRunningApart(t *testi if strings.Join(last.args, " ") != "run test:integration" { t.Errorf("ran %s, want npm run test:integration", joined(last)) } + // Design 47 H2 §800: the level's tests get its bound in the environment, the setup bound being half of it. + if !slices.Contains(last.env, "MESH_TEST_LEVEL_BOUND=1m0s") { + t.Errorf("the integration script ran with %v, not the level's bound MESH_TEST_LEVEL_BOUND=1m0s", last.env) + } + // Design 47 H2 §791, H-A-412 (a): the level's answer carries its text in output, what its commands wrote. + if !strings.HasSuffix(r.Output, "ok 1 - joins\n(node) warning\n") { + t.Errorf("the level's output is %q, want the script's stdout then its stderr", r.Output) + } if tsc := f.calls[0]; strings.Join(tsc.args[1:], " ") != "--noEmit -p ." { t.Errorf("a package with a tsconfig was checked with %s", joined(tsc)) } @@ -130,9 +140,20 @@ func TestTheIntegrationLevelRunsItsScriptAndReportsSetupAndRunningApart(t *testi if !out.(*TestResult).OverBound { t.Errorf("61 s of running is within the bound") } + // Design 47 H2 H-A-488: with four steps in hand at the step's start, the bounds are four times their defaults: the + // script gets 240 s as its level's bound, 40 s of setup is within its 120 s, and the result names both. + f.cost["tsc"], f.cost["npm"] = 40*time.Second, 61*time.Second + m.inHand = func() int { return 4 } + out, _ = m.test(context.Background(), testArgs("integration")) + if r := out.(*TestResult); r.OverBound || r.Bound != 240 || r.SetupBound != 120 { + t.Errorf("40 s of setup and 61 s of running with four steps in hand: %+v", r) + } + if last := f.calls[len(f.calls)-1]; !slices.Contains(last.env, "MESH_TEST_LEVEL_BOUND=4m0s") { + t.Errorf("with four steps in hand the integration script ran with %v, not MESH_TEST_LEVEL_BOUND=4m0s", last.env) + } } -// The commands of a step get an environment built from scratch: no word of this process's. +// The commands of a step get an environment built from scratch: no word of this process's, the level's bound alone (§800). func TestTheStepsCommandsGetAnEnvironmentOfTheirOwn(t *testing.T) { t.Setenv("MESH_SECRET_TOKEN", "hunter2") m, f, work := newMachine(t) @@ -142,7 +163,7 @@ func TestTheStepsCommandsGetAnEnvironmentOfTheirOwn(t *testing.T) { } for _, c := range f.calls { for _, e := range c.env { - if strings.Contains(e, "hunter2") || strings.HasPrefix(e, "MESH_") { + if strings.Contains(e, "hunter2") || (strings.HasPrefix(e, "MESH_") && !strings.HasPrefix(e, LevelBoundEnv+"=")) { t.Errorf("%s was given %s", joined(c), e) } } @@ -226,3 +247,54 @@ func TestTheTestScriptFindsTscAndEsbuildOnItsPath(t *testing.T) { t.Errorf("npm ran with %v, want NODE_OPTIONS naming the TAP reporter and its file", npm.env) } } + +// Design 47 G §328 (*Lint per language*: TypeScript's lint is the type-check) and §24: the pipeline step lint of a TypeScript +// artifact runs tsc without emitting over the module's directory; a type error fails it naming the file, a clean package passes, +// a tree with no .ts file has nothing to lint, and a tsc that cannot start is an error, not a verdict. +func TestTheLintStepIsTheTypeCheck(t *testing.T) { + for _, c := range []struct { + name string + files map[string]string + ran forgekey.Ran + failed int + nothing bool + err bool + }{ + {"a type error", map[string]string{"tools/bad.ts": `export const n: number = "text";`}, forgekey.Ran{Status: 2, Stdout: tscTypeError}, 1, false, false}, + {"a clean package", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{}, 0, false, false}, + {"no TypeScript", map[string]string{"package.json": `{"name":"x"}`}, forgekey.Ran{}, 0, true, false}, + {"tsc cannot start", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{Status: 127, Err: "no such file"}, 0, false, true}, + } { + t.Run(c.name, func(t *testing.T) { + m, f, work := newMachine(t) + workspaceWith(t, work, c.files) + f.answer["tsc"] = c.ran + out, err := m.lintStep(context.Background(), map[string]any{"workspace": "w1", "dir": "."}) + if (err != nil) != c.err { + t.Fatalf("error = %v, want error %v", err, c.err) + } + if err != nil { + return + } + la := out.(steprun.LintAnswer) + if len(la.Failed) != c.failed || la.Nothing != c.nothing { + t.Fatalf("answer = %+v, want %d failed, nothing %v", la, c.failed, c.nothing) + } + if c.failed > 0 && !strings.Contains(la.Failed[0].Cause+la.Failed[0].Output, "tools/bad.ts") { + t.Errorf("the failure %+v does not name tools/bad.ts", la.Failed[0]) + } + if !c.nothing && !strings.Contains(joined(f.calls[0]), "--noEmit") { + t.Errorf("the lint ran %s, want tsc --noEmit", joined(f.calls[0])) + } + }) + } +} + +// Design 47 G §24: the Node build module's steps carry what a step ask needs (its node, the lint body, the end's publisher and +// its own need), so the ask the first live pipeline sent is no longer refused as "says no step's end". +func TestTheNodeStepsCarryWhatAStepAskNeeds(t *testing.T) { + s := (&Module{Node: "shanks"}).askSteps(nil) + if s.Lint == nil || s.Node != "shanks" || s.SayStep == nil || s.Has == nil || !s.Has(sdkstep.NeedNodeBuildNode) || s.Has("other") { + t.Errorf("steps = %+v, want Lint, Node, SayStep and Has set", s) + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/detected.go b/modules/mesh-build-node/cmd/mesh-build-node/detected.go new file mode 100644 index 000000000..c295130e3 --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/detected.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "os" + "sync" + + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/stateobjects" +) + +// ModuleName is this module's name, which its prune tools are named for (stateobjects.PruneTools). +const ModuleName = "mesh-build-node" + +// prunedDetected is the state detected-steps, pruned toward its cap at this module's own writes (design 47 H2 §812; +// H-A-411 (2), (3)): past prune-mark of its 8 MiB the oldest keys go down to prune-target, in one journal line. Each key +// is an artifact's steps as detected, which the verb steps detects again when its key is gone. A setting that is no +// percentage is said, and the defaults hold. +var prunedDetected = sync.OnceValue(func() *stdio.PrunedState { + p, err := stdio.PruneSettings() + if err != nil { + fmt.Fprintf(os.Stderr, "the prune of %s keeps its defaults (%d %% to %d %%): %v\n", seat.StateDetectedSteps, stdio.PruneMarkDefault, stdio.PruneTargetDefault, err) + p = stdio.Prune{Mark: stdio.PruneMarkDefault, Target: stdio.PruneTargetDefault} + } + return stdio.State(seat.StateDetectedSteps).Pruned(p) +}) + +// pruneTools are the module's two prune tools over detected-steps, each written in the hand-act log (H-A-380 (3)). +func pruneTools() []stdio.Tool { + return stateobjects.PruneTools(ModuleName, []stateobjects.Pruning{{Name: seat.StateDetectedSteps, State: prunedDetected()}}, + meshhandactsclient.Recorder{Ask: stdio.Ask}) +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/fetch.go b/modules/mesh-build-node/cmd/mesh-build-node/fetch.go index 397da7046..9fcf4a470 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/fetch.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/fetch.go @@ -175,7 +175,7 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, group } } if len(req.Paths) > 0 { - if err := steprun.Narrow(tree, req); err != nil { + if err := narrowTree(tree, req); err != nil { // with the generated-from directories H-A-136 and H-A-137 keep return nil, err } // Said beside the tree, so the listing of the tree's modules leaves out those narrowed away. @@ -230,6 +230,10 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, group if err := m.layBuilds(dir, members); err != nil { return nil, err } + // What the mesh packages placed declare, as a registry install would (design 47 H, H-A-491 addendum). + if err := m.installPlacedDependencies(ctx, root, dir, d); err != nil { + return nil, err + } res.Installed = append(res.Installed, d) continue } @@ -245,12 +249,21 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, group return nil, err } } + // Every other mesh package it names, at the latest release (design 47 H, H-A-267); the group's and the + // members' builds are placed over them. + if err := m.placeMeshPackages(ctx, dir, d, served, members); err != nil { + return nil, err + } if err := placeGroup(dir, served); err != nil { return nil, err } if err := m.layBuilds(dir, members); err != nil { return nil, err } + // What the mesh packages placed declare, as a registry install would (design 47 H, H-A-491 addendum). + if err := m.installPlacedDependencies(ctx, root, dir, d); err != nil { + return nil, err + } if res.SDK == nil { res.SDK = map[string]string{} } @@ -300,6 +313,11 @@ func (m *Module) typeScriptModules(ctx context.Context, tree string) (dirs []str continue } d := filepath.ToSlash(filepath.Dir(l)) + if a.Kind == "package" && narrowed(tree) && a.narrowedAway(filepath.Join(tree, filepath.FromSlash(d))) { + // A package of the module whose own path the narrowing left out (ADR 0499 clause 4; design 47 H, H-A-136: + // nothing else is fetched): no module of this build, never the module's directory, which holds no lock. + continue + } if a.Kind == "package" { d = path.Join(d, a.packageDir(filepath.Join(tree, filepath.FromSlash(d)))) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/fetch_test.go b/modules/mesh-build-node/cmd/mesh-build-node/fetch_test.go index 9571a76d6..f9cb6e808 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/fetch_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/fetch_test.go @@ -1,7 +1,12 @@ package main import ( + "archive/tar" + "bytes" + "compress/gzip" "context" + "net/http" + "net/http/httptest" "os" "path/filepath" "slices" @@ -97,9 +102,17 @@ func TestAModuleNamingOnlyTheSdkAndTypesInstallsNothing(t *testing.T) { } // 47/G A-72: a module naming another @novox/mesh-* package beside the SDK has no package beyond the SDK, so it installs -// nothing and is not refused for want of a lock. +// nothing and is not refused for want of a lock. 47/H H-A-267 (ADR 0573 §2): a fetch with no group and no members' builds +// places that package at the latest release the registry holds, as it places the SDK, whatever the module's lock names. func TestAMeshPackageIsNotBeyondTheSdk(t *testing.T) { - m, f := fetchMachine(t, typeScriptModule(`{"dependencies":{"@novox/mesh-sdk":"^0.1.6","@novox/mesh-tools":"^0.1.6"}}`), nil) + const contracts = "@novox/mesh-delivery-contracts-git" + files := typeScriptModule(`{"dependencies":{"@novox/mesh-sdk":"^0.1.6","` + contracts + `":"^0.1.2"}}`) + files["modules/m/package-lock.json"] = `{"lockfileVersion":3,"packages":{"node_modules/` + contracts + `":{"version":"0.1.2","integrity":"sha512-old"}}}` + m, f := fetchMachine(t, files, nil) + fakeRegistryOf(t, m, map[string]map[string][]byte{ + sdkPackage: {"0.1.15": tgzOf(t, sdkPackage, "0.1.15")}, + contracts: {"0.1.2": tgzOf(t, contracts, "0.1.2"), "0.1.4": tgzOf(t, contracts, "0.1.4"), "0.1.5-feat.1": tgzOf(t, contracts, "0.1.5-feat.1")}, + }) out, err := m.fetch(context.Background(), fetchArgs) if err != nil { t.Fatal(err) @@ -108,6 +121,94 @@ func TestAMeshPackageIsNotBeyondTheSdk(t *testing.T) { if len(npmCalls(f)) != 0 || len(r.Installed) != 0 || len(r.Refused) != 0 { t.Errorf("result = %+v, npm calls %d, want nothing installed and nothing refused", r, len(npmCalls(f))) } + dir := filepath.Join(m.Work, r.Workspace, "tree", "modules", "m") + got, err := readPackageJSON(filepath.Join(dir, "node_modules", filepath.FromSlash(contracts))) + if err != nil || got.Version != "0.1.4" { + t.Errorf("%s placed %q (%v), want the latest release 0.1.4", contracts, got.Version, err) + } + if v := placedSDK(dir); v != "0.1.15" || r.SDK["modules/m"] != "0.1.15" { + t.Errorf("the SDK placed %q, answered %q, want the latest release 0.1.15", v, r.SDK["modules/m"]) + } + + // A member's build of a mesh package takes precedence: it is laid, and the registry, holding none of it, is not + // waited on. + const member = "@novox/mesh-tools" + m, _ = fetchMachine(t, typeScriptModule(`{"dependencies":{"@novox/mesh-sdk":"^0.1.6","`+member+`":"^0.1.6"}}`), nil) + tgz := tgzOf(t, member, "0.0.0-member") + digest := digestOf(tgz) + store := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v2/tools/pkg/blobs/"+digest { + http.NotFound(w, r) + return + } + w.Write(tgz) + })) + defer store.Close() + m.ArtifactStoreFile = filepath.Join(t.TempDir(), "artifact-store.json") + write(t, m.ArtifactStoreFile, `{"at":"`+strings.TrimPrefix(store.URL, "http://")+`"}`, 0o600) + args := map[string]any{"repository": fetchArgs["repository"], "commit": fetchArgs["commit"], + "builds": []any{map[string]any{"package": member, "module": "tools", "artifact": "pkg", "digest": digest}}} + out, err = m.fetch(context.Background(), args) + if err != nil { + t.Fatalf("a fetch with a member's build of %s: %v", member, err) + } + r = out.(FetchResult) + got, err = readPackageJSON(filepath.Join(m.Work, r.Workspace, "tree", "modules", "m", "node_modules", filepath.FromSlash(member))) + if err != nil || got.Version != "0.0.0-member" { + t.Errorf("%s placed %q (%v), want the member's build", member, got.Version, err) + } + + // Design 47 H, H-A-491 addendum: the dependencies a placed mesh package declares are installed beside it, as a + // registry install would (the SDK's seal code imports blakejs); its devDependencies, a mesh package and one the + // module's node_modules holds already are not asked. + files = typeScriptModule(`{"dependencies":{"@novox/mesh-sdk":"^0.1.6"}}`) + files["modules/m/node_modules/tweetnacl/package.json"] = `{"name":"tweetnacl","version":"1.0.3"}` + m, f = fetchMachine(t, files, map[string]string{"blakejs/package.json": `{"name":"blakejs","version":"1.2.1"}`}) + var asked []string + effect := f.effect + f.effect = func(c call) { + if c.name == "npm" { + for i, a := range c.args { + if a == "--prefix" { + raw, _ := os.ReadFile(filepath.Join(c.args[i+1], "package.json")) + asked = append(asked, strings.Join(c.args[:1], " ")+" "+string(raw)) + } + } + } + effect(c) + } + fakeRegistryOf(t, m, map[string]map[string][]byte{sdkPackage: {"0.1.15": tgzDeclaring(t, sdkPackage, "0.1.15", + `{"blakejs":"1.2.1","tweetnacl":"1.0.3","@novox/mesh-other":"^0.1.0"}`, `{"typescript":"^5","left-out":"1"}`)}}) + out, err = m.fetch(context.Background(), fetchArgs) + if err != nil { + t.Fatalf("a fetch placing an SDK that declares dependencies: %v", err) + } + r = out.(FetchResult) + if want := `install {"dependencies":{"blakejs":"1.2.1"},"name":"placed-dependencies","private":true}`; len(asked) != 1 || asked[0] != want { + t.Errorf("npm was asked %q, want once %q", asked, want) + } + nm := filepath.Join(m.Work, r.Workspace, "tree", "modules", "m", "node_modules") + if _, err := os.Stat(filepath.Join(nm, "blakejs", "package.json")); err != nil { + t.Errorf("the SDK's dependency blakejs is not installed beside it: %v", err) + } + if v := placedSDK(filepath.Join(m.Work, r.Workspace, "tree", "modules", "m")); v != "0.1.15" { + t.Errorf("the SDK placed %q after the install, want 0.1.15", v) + } +} + +// tgzDeclaring is a packed npm package of name@version whose package.json declares the dependencies and +// devDependencies given (JSON objects). +func tgzDeclaring(t *testing.T, name, version, deps, devDeps string) []byte { + t.Helper() + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + tw := tar.NewWriter(zw) + body := `{"name":"` + name + `","version":"` + version + `","dependencies":` + deps + `,"devDependencies":` + devDeps + `}` + tw.WriteHeader(&tar.Header{Name: "package/package.json", Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write([]byte(body)) + tw.Close() + zw.Close() + return buf.Bytes() } // 1489/AC2: a module naming lodash with a lock gets npm ci --omit=dev --ignore-scripts (fake runner), its install put diff --git a/modules/mesh-build-node/cmd/mesh-build-node/forge_test.go b/modules/mesh-build-node/cmd/mesh-build-node/forge_test.go index 26f8dfabb..f9ade8758 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/forge_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/forge_test.go @@ -150,7 +150,8 @@ func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *test } keeps := false for _, s := range m.State { - if s == "keys" { + // Design 47 H2 H-A-411 (2): every state names its cap, 8 MiB. + if e, _ := s.(map[string]any); e["name"] == "keys" && e["max-mib"] == float64(8) { keeps = true } } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/imports.go b/modules/mesh-build-node/cmd/mesh-build-node/imports.go new file mode 100644 index 000000000..c90031205 --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/imports.go @@ -0,0 +1,185 @@ +package main + +// The imports step (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): at a build's end the module says which npm packages +// its TypeScript bundles import, so the indexer can take the fingerprint over the ones a module of the module graph +// publishes and no other. It is what esbuild's metafile names as each bundle's inputs, read from the bundle's compiled +// entrypoints and launchers as the build step staged them: every npm package among them, each by its package name once +// (@novox/mesh-sdk, never a sub-path of it), with no scope telling a mesh package apart, and none of Node's own modules. +// A bundle's inputs are what its entrypoints reach, so no test file is among them. + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" +) + +// ImportsTool reads the npm packages a module's bundles import (design 47 H2 H-A-532 DQ-6). +const ImportsTool = "build_node_imports" + +// ImportsResult is what the imports step answers; a BuildAnswer carries Imports as it is. +type ImportsResult struct { + Imports []string `json:"imports"` +} + +func (m *Module) importsTool() StepTool { + return StepTool{ + Name: ImportsTool, + Description: "Read the npm packages the TypeScript bundles of a module of a workspace import, after its build: " + + "esbuild's inputs of each bundle's compiled entrypoints and launchers, every npm package among them but Node's own " + + "modules, each by its package name, sorted and each once. It is what a build says at its end " + + "for the fingerprint (design 47 H2 H-A-523). Writes only esbuild's scratch output in the workspace.", + Input: map[string]any{ + "type": "object", + "properties": map[string]any{ + "workspace": map[string]any{"type": "string", "description": "the workspace id build_node_fetch answered, its bundles built"}, + "module": map[string]any{"type": "string", "description": "the module's directory in the workspace, '.' when it is the root"}, + }, + "required": []string{"workspace", "module"}, + }, + Run: m.imports, + } +} + +func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) { + workspace, _ := args["workspace"].(string) + module, _ := args["module"].(string) + root, dir, err := m.moduleDirOf(workspace, module) + if err != nil { + return nil, err + } + raw, err := os.ReadFile(filepath.Join(dir, "module.json")) + if err != nil { + return nil, fmt.Errorf("the module has no module.json: %w", err) + } + var manifest struct { + Build struct { + Artifacts []artifact `json:"artifacts"` + } `json:"build"` + } + if err := json.Unmarshal(raw, &manifest); err != nil { + return nil, fmt.Errorf("module.json is not JSON: %w", err) + } + probe := m.Builtins + if probe == nil { + probe = ProbeBuiltins + } + builtins, err := probe(ctx) + if err != nil { + return nil, fmt.Errorf("the imports cannot be told from Node's own modules: %w", err) + } + seen := map[string]bool{} + for _, a := range manifest.Build.Artifacts { + if a.Kind != "bundle" || a.Language != "typescript" { + continue + } + names, err := m.bundleImports(ctx, root, a, builtins) + if err != nil { + return nil, err + } + for _, n := range names { + seen[n] = true + } + } + out := []string{} + for n := range seen { + out = append(out, n) + } + slices.Sort(out) + return ImportsResult{Imports: out}, nil +} + +// bundleImports are the npm packages esbuild names as inputs of bundle a, read in the stage its build left +// (build.go: /stage-/modules/module), from the same entries and externals the build bundled. +func (m *Module) bundleImports(ctx context.Context, root string, a artifact, builtins []string) ([]string, error) { + dir := filepath.Join(root, "stage-"+a.Name, "modules", "module") + out := Out(a.Name) + if _, err := os.Stat(filepath.Join(dir, out)); err != nil { + return nil, fmt.Errorf("the bundle %s was not built in this workspace, so its imports cannot be read: %w", a.Name, err) + } + var entries []string + for _, e := range a.Entrypoints { + if strings.HasSuffix(e, ".js") { + entries = append(entries, out+"/"+e) + } + } + for _, l := range sortedValues(sdkstep.Launchers(a.Language, a.Entrypoints)) { + entries = append(entries, out+"/"+l) + } + if len(entries) == 0 { + return nil, nil + } + meta := out + ".imports.json" + args := append(append([]string{}, entries...), "--bundle", "--platform=node", "--format=esm", "--target=node22", + "--outbase="+out, "--outdir="+out+".imports", "--log-level=warning", "--metafile="+meta) + for _, x := range a.External { + args = append(args, "--external:"+x) + } + if why := ranFailed(m.runIn(ctx, root, false, dir, nil, m.esbuild(), args...)); why != "" { + return nil, fmt.Errorf("esbuild's inputs of %s: %s", a.Name, why) + } + raw, err := os.ReadFile(filepath.Join(dir, meta)) + if err != nil { + return nil, fmt.Errorf("esbuild wrote no metafile for %s: %w", a.Name, err) + } + return packagesOf(raw, builtins) +} + +// packagesOf are the npm packages an esbuild metafile names: each input under a node_modules directory and each external +// import, by its package name, but Node's own modules. +func packagesOf(metafile []byte, builtins []string) ([]string, error) { + var meta struct { + Inputs map[string]struct { + Imports []struct { + Path string `json:"path"` + External bool `json:"external"` + } `json:"imports"` + } `json:"inputs"` + } + if err := json.Unmarshal(metafile, &meta); err != nil { + return nil, fmt.Errorf("esbuild's metafile is not JSON: %w", err) + } + var out []string + keep := func(name string) { + if name != "" && !nodeBuiltin(name, builtins) && !slices.Contains(out, name) { + out = append(out, name) + } + } + for input, in := range meta.Inputs { + filePath := filepath.ToSlash(input) + if i := strings.LastIndex(filePath, "node_modules/"); i >= 0 { + keep(packageName(filePath[i+len("node_modules/"):])) + } + for _, imp := range in.Imports { + if imp.External { + keep(packageName(imp.Path)) + } + } + } + slices.Sort(out) + return out, nil +} + +// packageName is the npm package a module specifier or a path under node_modules names: its first segment, or its +// first two for a scoped package (@novox/mesh-sdk/stdio is @novox/mesh-sdk). +func packageName(spec string) string { + parts := strings.SplitN(spec, "/", 3) + if strings.HasPrefix(spec, "@") { + if len(parts) < 2 { + return "" + } + return parts[0] + "/" + parts[1] + } + return parts[0] +} + +// nodeBuiltin says whether name is one of Node's own modules (node:, or a name of the probed toolchain's +// module.builtinModules), which is the runtime's standard library and no npm package. +func nodeBuiltin(name string, builtins []string) bool { + return strings.HasPrefix(name, "node:") || slices.Contains(builtins, name) +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/install.go b/modules/mesh-build-node/cmd/mesh-build-node/install.go new file mode 100644 index 000000000..25921b4ec --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/install.go @@ -0,0 +1,121 @@ +package main + +// **An install of a module's npm tree** (design 47 H2 §800; H-A-399 (2), H-A-403): the runner asks the seat node-build-node +// a StepAsk of the kind install, on the seat's install queue, for a module whose Go artifact's check-needs names this +// seat. The install takes the module's package lock at the commit, installs it from the npm registry seat with an +// integrity-checked install (npm ci) that runs no install script and makes no link (--ignore-scripts, --no-bin-links: the +// SDK's Pack and the unpack refuse a symlink, and the mesh creates none), packs the tree, publishes the archive to the +// artifact store as the module's artifact :node-modules under the ask's version, and answers its reference, which +// the step's end carries and the integration ask names for the Go build module to unpack. + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + + artifactref "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient/reference" + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" +) + +// installKind is the artifact kind the install archive is published as (H-A-403: kind archive). +const installKind = "archive" + +// installTree is where the installed tree lies in the archive, from the workspace's tree: the module's directory's +// node_modules, which the Go build module unpacks at the tree's root (layInstall). +func installTree(module string) string { return filepath.Join("modules", module, "node_modules") } + +// installTreeStep is AskSteps.Install: the install body of an install ask (steprun's installStep gives its arguments). +func (m *Module) installTreeStep(ctx context.Context, args map[string]any) (any, error) { + module, _ := args["module"].(string) + lock, _ := args["lock"].(string) + artifact, _ := args["artifact"].(string) + version, _ := args["version"].(string) + name, ok := strings.CutPrefix(artifact, module+":") + switch { + case module == "" || !ok || artifact != sdkstep.InstallArtifact(module): + return nil, fmt.Errorf("the install of %q names the artifact %q, not %s", module, artifact, sdkstep.InstallArtifact(module)) + case version == "": + return nil, fmt.Errorf("the install of %s names no version to publish its archive under", module) + } + pkg, err := lockRoot(lock) + if err != nil { + return nil, fmt.Errorf("the install of %s: %w", module, err) + } + if err := os.MkdirAll(m.Work, 0o755); err != nil { + return nil, err + } + root, err := os.MkdirTemp(m.Work, "install-") + if err != nil { + return nil, err + } + defer os.RemoveAll(root) + dir := filepath.Join(root, "npm") + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + if err := os.WriteFile(filepath.Join(dir, "package.json"), pkg, 0o600); err != nil { + return nil, err + } + if err := os.WriteFile(filepath.Join(dir, "package-lock.json"), []byte(lock), 0o600); err != nil { + return nil, err + } + // The registry is given through a config file of its own, outside the workspace, removed after (npmrcIn). + npmrc, err := m.npmrcIn(root) + if err != nil { + return nil, fmt.Errorf("the install of %s: %w", module, err) + } + defer os.Remove(npmrc) + env := append(m.baseEnv(), "npm_config_cache="+m.npmCache()) + r := m.Run(ctx, env, "npm", "ci", "--ignore-scripts", "--no-bin-links", "--no-audit", "--no-fund", "--prefix", dir, "--userconfig", npmrc) + if why := ranFailed(r); why != "" { + return nil, steprun.Transport(fmt.Errorf("installing the npm tree of %s: %s", module, why)) + } + // Only the tree is archived, under the module's directory: never the package.json written here from the lock, which + // would lie over the module's own when unpacked. + packed := filepath.Join(root, "packed") + into := filepath.Join(packed, installTree(module)) + if err := os.MkdirAll(filepath.Dir(into), 0o755); err != nil { + return nil, err + } + if err := os.Rename(filepath.Join(dir, "node_modules"), into); err != nil { + return nil, fmt.Errorf("the install of %s made no node_modules: %w", module, err) + } + archive, digest, err := steprun.Pack(packed) + if err != nil { + return nil, fmt.Errorf("packing the npm tree of %s: %w", module, err) + } + if err := m.publishOn(ctx, steprun.ArtifactSeat, module+"/"+name, installKind, version, digest, archive); err != nil { + return nil, fmt.Errorf("publishing the npm tree of %s: %w", module, err) + } + reference := artifactref.SeatReference(steprun.ArtifactSeat, module, name, digest) + if m.Say != nil { + m.Say("installed the npm tree of %s at %s (%d bytes) as %s", module, version, len(archive), reference) + } + return map[string]any{"archive": reference}, nil +} + +// lockRoot is the package.json npm ci needs beside a lock, written from the lock's root package (packages[""]): its +// name, version and dependency maps, never a script. A lock with no root package (lockfileVersion 1) is refused. +func lockRoot(lock string) ([]byte, error) { + var l struct { + Packages map[string]map[string]any `json:"packages"` + } + if err := json.Unmarshal([]byte(lock), &l); err != nil { + return nil, fmt.Errorf("the package lock is not JSON: %w", err) + } + root, ok := l.Packages[""] + if !ok { + return nil, fmt.Errorf("the package lock names no root package (packages[\"\"]): a lock of lockfileVersion 2 or later is needed") + } + pkg := map[string]any{} + for _, k := range []string{"name", "version", "dependencies", "devDependencies", "optionalDependencies", "peerDependencies"} { + if v, ok := root[k]; ok { + pkg[k] = v + } + } + return json.Marshal(pkg) +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go b/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go index c3ed1e426..ddadfe488 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go @@ -2,11 +2,17 @@ package main import ( "context" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "encoding/json" + "errors" + "os" + "path/filepath" "strings" "testing" "time" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/buscalls" + buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance" @@ -36,6 +42,30 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // ADR 0664 §1 (issue 1748): the module's own paths from a failed fetch or install to its step's error say a network that did // not answer as a transport fault, and a failure of the source (a package the registry lacks) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { + // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its + // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + t.Run("again-delays is declared and read", func(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + var m struct { + Config map[string]json.RawMessage `json:"config"` + } + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + var c struct { + Default string `json:"default"` + Runtime bool `json:"runtime"` + } + decl, ok := m.Config[steprun.AgainDelaysSetting] + _ = json.Unmarshal(decl, &c) + delay, err := steprun.AgainDelays(c.Default) + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) + } + }) conformance.Passing(t, []string{conformance.GitFetch, conformance.NpmCI}, func(runner, words string) error { switch runner { case conformance.GitFetch: @@ -49,3 +79,39 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { } }) } + +// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or +// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met. +func TestTheStepsCanSayAStepsEnd(t *testing.T) { + conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil)) + // Design 47 H2 §791, §801, H-A-412, H-A-421: the seat's verbs current, output and answer keep the build-step part's form 2, + // and a pipeline step's run output is kept in the module's outputs objects and read back through output. + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }, Outputs: kitObjects{}} + conformance.SeatVerbs(t, Seat, m.SeatTools(m.Puller(nil, steprun.NewFakeAsks())), m.askSteps(nil)) +} + +// kitObjects is an outputs store in memory, for the kit's SeatVerbs. +type kitObjects map[string][]byte + +func (k kitObjects) Put(name string, data []byte, _ string) (buscalls.ObjectInfo, error) { + k[name] = data + return buscalls.ObjectInfo{Name: name}, nil +} + +func (k kitObjects) Get(name string) (buscalls.ObjectData, error) { + d, ok := k[name] + if !ok { + return buscalls.ObjectData{}, errors.New("object not found") + } + return buscalls.ObjectData{Data: d}, nil +} + +// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before +// it ran is no run), so the poison rule never ends an ask that never ran. +func TestThePullerCountsRunsThatStarted(t *testing.T) { + conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller { + m := &Module{Node: "kitnode", Capacity: func() int { return 1 }} + m.ReadSteps = StateRead{Get: read} + return m.Puller(nil, steprun.NewFakeAsks()) + }) +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/lint.go b/modules/mesh-build-node/cmd/mesh-build-node/lint.go new file mode 100644 index 000000000..67c90ccee --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/lint.go @@ -0,0 +1,56 @@ +package main + +import ( + "context" + "fmt" + "path/filepath" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" +) + +// **The type-check is a TypeScript artifact's pipeline step lint** (design 47 G §328 *Lint per language*: Go's lint is the Go +// build module's linter, TypeScript's the type-check; §22: lint is a step the build seats serve; §24: asked on a work queue, +// its end said as an event). It takes {"workspace", "dir"} as the lint step of mesh-build-go does and runs tsc over each +// TypeScript package of the module's directory (testTargets, the way the unit level finds them), without emitting: a package +// with no .ts file has nothing to lint, and nothing at all ends the step `nothing to run`. A failure is the step's, naming +// the tsc output as the unit level names it; a tsc that could not start is an error, never a verdict. +func (m *Module) lintStep(ctx context.Context, args map[string]any) (any, error) { + workspace, _ := args["workspace"].(string) + dir, _ := args["dir"].(string) + root, mdir, err := m.moduleDirOf(workspace, dir) + if err != nil { + return nil, err + } + targets, err := testTargets(mdir, filepath.ToSlash(filepath.Clean(dir)), narrowed(filepath.Join(root, "tree"))) + if err != nil { + return nil, err + } + var failed []Failure + linted := false + for _, tg := range targets { + sources, err := typeScriptFiles(tg.dir) + if err != nil { + return nil, err + } + if len(sources) == 0 { + continue + } + linted = true + if err := m.provide(root); err != nil { + return nil, fmt.Errorf("providing the toolchain's packages to the workspace: %w", err) + } + r := m.runIn(ctx, root, false, tg.dir, nil, "node", m.typeCheck(tg.dir, sources)...) + if r.Err != "" { + return nil, fmt.Errorf("type-check could not be run: status %d %s: %s", r.Status, r.Err, firstLine(r.Stderr)) + } + if r.Status != 0 { + failed = append(failed, testFailures(tg.where, "type-check", tg.dir, r, "")...) + } + } + return steprun.LintAnswer{Failed: failed, Nothing: !linted}, nil +} + +// A-489b: Has says whether this node has a need a package's tests name (sdkstep.AskNeeds): the need node-build-node is this module's own +// (a TypeScript package's tests run through it); any other it lacks. +func (m *Module) Has(need string) bool { return need == sdkstep.NeedNodeBuildNode } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/main.go b/modules/mesh-build-node/cmd/mesh-build-node/main.go index 18752e4d7..920a97dc8 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/main.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/main.go @@ -51,7 +51,7 @@ func main() { SayToolchain: stdio.SeatPublish, Steps: stdio.State(seat.StateSteps).Put, ReadSteps: readOf(stdio.State(seat.StateSteps)), - Detected: stdio.State(seat.StateDetectedSteps).Put, + Detected: prunedDetected().Put, ReadDetected: readOf(stdio.State(seat.StateDetectedSteps)).Get, ForgetDetected: stdio.State(seat.StateDetectedSteps).Delete, RecordAct: handActRecorder, @@ -79,10 +79,18 @@ func main() { logf("announcing the states it keeps: %v", err) os.Exit(1) } - m.Outputs = busstate.ObjectsOf(steprun.OutputsStore) + m.Answers = busstate.ObjectsOf(steprun.AnswersStore) steps := m.StepTools() booted := time.Now() puller := m.Puller(steps, nil) + // A step whose fetch or publish met its holder away is given again after again-delays (design 47 H2 §799; H-A-390). + againSetting, _ := stdio.Setting(steprun.AgainDelaysSetting) + againDelay, againErr := steprun.AgainDelays(againSetting) + if againErr != nil { + logf("the setting %s: %v", steprun.AgainDelaysSetting, againErr) + os.Exit(1) + } + puller.Delay = againDelay m.Held = puller if m.Node != "" { // A step a previous process left running is ended (issue 1890): one that names another owner, or none and diff --git a/modules/mesh-build-node/cmd/mesh-build-node/manifest_test.go b/modules/mesh-build-node/cmd/mesh-build-node/manifest_test.go index 03d182e38..8310d9478 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/manifest_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/manifest_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -118,13 +119,33 @@ func TestManifestKeepsItsStatesClaimsItsBuildSeatAndDeclaresItsHealthTool(t *tes if want := []string{"keys", "pauses", "toolchains"}; !slices.Equal(states, want) { t.Errorf("state = %v, want %v", states, want) } - if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output"}) { + if len(m.Claims) != 1 || m.Claims[0].Name != Seat || !slices.Equal(m.Claims[0].Serves, []string{"current", "drop", "pause", "resume", "steps", "kept-artifact", "output", "answer"}) { t.Errorf("claims = %v, want the seat %s alone", m.Claims, Seat) } + // Design 47 H2 H-A-411 (2), (3): a core module; its state detected-steps is pruned at its own writes, with the two prune + // tools and the settings prune-mark (70 %) and prune-target (50 %). + if m.Class != catalogue.ClassCore { + t.Errorf("class = %q, want %s", m.Class, catalogue.ClassCore) + } + for _, tool := range []string{ModuleName + "_state_prune_now", ModuleName + "_state_keep"} { + if !slices.Contains(m.Tools, tool) { + t.Errorf("tools = %v lack %s", m.Tools, tool) + } + } + raw, _ := os.ReadFile(filepath.Join(moduleDir, "module.json")) + var doc struct { + Config map[string]struct { + Default json.RawMessage `json:"default"` + } `json:"config"` + } + _ = json.Unmarshal(raw, &doc) + if mark, target := string(doc.Config[stdio.PruneMarkSetting].Default), string(doc.Config[stdio.PruneTargetSetting].Default); mark != "70" || target != "50" { + t.Errorf("prune-mark %s and prune-target %s, want 70 and 50", mark, target) + } if !slices.Contains(m.Tools, HealthTool) { t.Errorf("tools = %v lack %s", m.Tools, HealthTool) } - raw, _ := os.ReadFile(filepath.Join(moduleDir, "module.json")) + raw, _ = os.ReadFile(filepath.Join(moduleDir, "module.json")) if !strings.Contains(string(raw), `"tool": "`+HealthTool+`"`) { t.Errorf("runtime-health does not name %s", HealthTool) } @@ -277,10 +298,22 @@ func TestTheModuleRequiresNodeToolsItPullsThrough(t *testing.T) { if !slices.Contains(m.Requires, "node-tools") { t.Errorf("requires %v lack node-tools", m.Requires) } + // Design 47 G A-488a: its runtime follows the seat list (seatlist.Start subscribes to the seat mesh-catalog's events), so the + // module consumes both, which makes its durable consumer _mesh-build-node_tools: with none, the seat list is never + // read and the asks of a named asker are given back for ever. + for _, ev := range []string{"mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed"} { + if !slices.Contains(m.Consumes, ev) { + t.Errorf("consumes %v lack %s", m.Consumes, ev) + } + } + if !slices.Contains(m.Invokes, "seat:mesh-catalog.seat-definitions") { + t.Errorf("invokes %v lack seat:mesh-catalog.seat-definitions (A-488b)", m.Invokes) + } } -// Design 47 G A-254, A-313, A-314: the module keeps a run's answer over what step-ended carries inline in the steps state's own -// objects store, sized in `requires` by the state option objects-max-mib, and serves it through the verb output. +// Design 47 G A-254, A-313, A-314: the module keeps a step's end over what step-ended carries inline in the steps state's own +// objects store, sized in `requires` by the state option objects-max-mib, and serves it through the verb answer (H2 H-A-412 +// addendum); and a run's test output in its outputs objects, 1 GiB kept 7 days, read by the verb output (H2 §791, §820). func TestManifestRequiresTheStepsStateWithItsObjectsStore(t *testing.T) { raw, err := os.ReadFile(moduleDir + "/module.json") if err != nil { @@ -292,11 +325,12 @@ func TestManifestRequiresTheStepsStateWithItsObjectsStore(t *testing.T) { if err := json.Unmarshal(raw, &doc); err != nil { t.Fatal(err) } - want := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256)}} - for _, r := range doc.Requires { - if reflect.DeepEqual(r, want) { - return + for _, want := range []map[string]any{ + {"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(16)}}, + {"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}}, + } { + if !slices.ContainsFunc(doc.Requires, func(r any) bool { return reflect.DeepEqual(r, any(want)) }) { + t.Errorf("requires %v lack %v", doc.Requires, want) } } - t.Errorf("requires %v lack %v", doc.Requires, want) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/module.go b/modules/mesh-build-node/cmd/mesh-build-node/module.go index b21fbd131..a70154071 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/module.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/module.go @@ -25,15 +25,19 @@ const CheckRound = 10 * time.Minute // Module is the Node build module's one running state: the node it runs on, its recipe, the toolchain guard, the // toolchain directory and the states it writes (toolchains, steps). type Module struct { - // Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when - // the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163. - Callers func(kind string) ([]string, bool) - // Outputs is the object store of a run's answers over what step-ended carries inline (steprun.OutputsStore); nil keeps none. + // Answers is the steps state's objects (steprun.AnswersStore), where a step's end over what its key or step-ended + // carries is kept and the seat's verb answer reads it (design 47 H2 H-A-412 addendum); nil keeps none. + Answers steprun.OutputObjects + // Outputs are the outputs objects (steprun.OutputsStore) a test step keeps a run's output in, which the verb output + // reads (design 47 H2 §791); nil is the module's own on the bus (outputs), a test sets its own. Outputs steprun.OutputObjects // SayEvent publishes an event of the node build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the // puller's ask-taken, step-progress and step-ended (design 47 G §496, §602). SayEvent func(subject string, body any, id string) error + // SayStep says a pipeline step's end (steprun.AskSteps.SayStep); the seat's publish on this node when nil (a test's own). + SayStep func(sdkstep.StepEnded) error + Node string // Recipe is the recipe in force. Reload, when set, reads it again at every check (the lock file the mesh // writes can change under a running module); a failure to read it is a refusal. @@ -41,6 +45,9 @@ type Module struct { Reload func() (Recipe, error) // Probe reads the installed Node version (ProbeNode). Probe func(ctx context.Context) (string, error) + // Builtins reads the installed Node's own module names, its module.builtinModules (ProbeBuiltins), at each imports + // step; nil reads them with ProbeBuiltins. + Builtins func(ctx context.Context) ([]string, error) // Toolchain installs the toolchain directory; nil in a module that only guards. Toolchain *Toolchain // Work is the work directory, outside the home: a workspace is //tree. Run runs the commands of a @@ -103,6 +110,8 @@ type Module struct { // when set, answers it instead (a test). Settings string Capacity func() int + // inHand answers how many steps the seat has in hand in place of Held's (a test's; design 47 H2 H-A-488). + inHand func() int spacesOnce sync.Once workspaces *steprun.Workspaces diff --git a/modules/mesh-build-node/cmd/mesh-build-node/module_test.go b/modules/mesh-build-node/cmd/mesh-build-node/module_test.go index a04ed8e4f..99b460230 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/module_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/module_test.go @@ -117,7 +117,7 @@ func TestANodeThatCannotBeRunRefusesEveryStepAndHealthIsUnhealthy(t *testing.T) {Name: "short_probe", Run: run}, }, (&Module{}).StepTools()...) for _, tool := range m.Tools(steps) { - if tool.Name == StatusTool || tool.Name == HealthTool || tool.Name == StepReadTool || tool.Name == StepsReadTool || tool.Name == ToolchainsReadTool || tool.Name == ReleaseTool || tool.Name == StepEndTool { + if strings.HasPrefix(tool.Name, ModuleName+"_state_") || tool.Name == StatusTool || tool.Name == HealthTool || tool.Name == StepReadTool || tool.Name == StepsReadTool || tool.Name == ToolchainsReadTool || tool.Name == ReleaseTool || tool.Name == StepEndTool { continue } var reason string diff --git a/modules/mesh-build-node/cmd/mesh-build-node/narrow.go b/modules/mesh-build-node/cmd/mesh-build-node/narrow.go new file mode 100644 index 000000000..dd3f00156 --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/narrow.go @@ -0,0 +1,135 @@ +package main + +// A copy of mesh-build-go's narrowTree and generatedFromDirs (mesh-build-go/cmd/mesh-build-go/narrow.go) without its Go +// part (the directories of the repository's packages a go.mod requires at the zero version). Copied, not moved to +// mesh-delivery-sdk's steprun beside Narrow: the move is a change to two more repositories (mesh-delivery and back +// into mesh-build-go) and a group delivery for some sixty lines, in a fix that unblocks the build modules' steps now; +// the copy is said here so the move is not forgotten. + +import ( + "os" + "path" + "path/filepath" + "slices" + "strings" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// narrowedKeptAtRoot are what steprun.Narrow keeps beside the named paths, read from the request's directory: the +// manifest and its lock files. A request narrowed from the repository's root keeps them at the root too, where the +// asked module names none of them; they are removed again. +var narrowedKeptAtRoot = []string{"module.json", "go.sum", "package-lock.json"} + +// narrowTree narrows the fetched tree for a step of an artifact that names its paths (ADR 0499 clause 4, +// steprun.Narrow). Beside the artifact's paths and the module's manifest, the workspace holds every generated-from +// directory an artifact of the module names, so the unit level's generator check (steprun.OutOfStep) finds the seat +// definitions and every generated package; nothing else (design 47 H, lead answers H-A-136 and H-A-137). +func narrowTree(tree string, req sdkstep.FetchRequest) error { + dir := cleanDir(req.Dir) + if dir == "" { + return steprun.Narrow(tree, req) // refused there: named paths without the module's directory + } + var outside []string + inside := slices.Clone(req.Paths) + for _, e := range generatedFromDirs(tree, dir) { + if rel, ok := under(dir, e); ok { + if !slices.Contains(inside, rel) { + inside = append(inside, rel) + } + } else if !slices.Contains(outside, e) { + outside = append(outside, e) + } + } + if len(outside) == 0 { + r := req + r.Paths = inside + return steprun.Narrow(tree, r) + } + // A directory outside the module's own: the request is narrowed from the root, with every path the module's + // narrowing keeps named by its path from the root (the manifest and lock files only where the module has them). + all := []string{} + for _, p := range inside { + all = append(all, path.Join(dir, p)) + } + for _, f := range narrowedKeptAtRoot { + if _, err := os.Lstat(filepath.Join(tree, filepath.FromSlash(path.Join(dir, f)))); err == nil { + all = append(all, path.Join(dir, f)) + } + } + all = append(all, outside...) + if err := steprun.Narrow(tree, sdkstep.FetchRequest{Repository: req.Repository, Commit: req.Commit, Paths: all}); err != nil { + return err + } + for _, f := range narrowedKeptAtRoot { + if !slices.Contains(all, f) { + if err := os.RemoveAll(filepath.Join(tree, f)); err != nil { + return err + } + } + } + return nil +} + +func cleanDir(dir string) string { + if strings.TrimSpace(dir) == "" { + return "" + } + return strings.Trim(filepath.ToSlash(filepath.Clean(dir)), "/") +} + +// under answers p's path relative to dir when p is dir or lies under it. +func under(dir, p string) (string, bool) { + if dir == "." { + return p, true + } + if p == dir { + return ".", true + } + if rel, ok := strings.CutPrefix(p, dir+"/"); ok { + return rel, true + } + return "", false +} + +// generatedFromDirs are the generated-from directories (from the tree's root) the artifacts of the module in dir name +// (H-A-136). A module at the repository's root keeps not its generated-from directory, which would be the whole +// repository, but the generator's inputs and outputs: the seats/ directory of each generated-from directory and the +// paths of every artifact of the module naming generated-from (H-A-137). A manifest that is absent or unreadable names +// none; the steps that read it say so. +func generatedFromDirs(tree, dir string) []string { + raw, err := os.ReadFile(filepath.Join(tree, filepath.FromSlash(dir), "module.json")) + if err != nil { + return nil + } + man, err := catalogue.Decode(raw) + if err != nil || man.Build == nil { + return nil + } + var out []string + add := func(p string) { + if p == ".." || strings.HasPrefix(p, "../") || slices.Contains(out, p) { + return + } + if _, err := os.Lstat(filepath.Join(tree, filepath.FromSlash(p))); err == nil { // steprun.Narrow refuses a path the tree lacks + out = append(out, p) + } + } + for _, a := range man.Build.Artifacts { + g := strings.TrimSpace(a.GeneratedFrom) + if g == "" { + continue + } + if dir != "." { + add(path.Join(dir, filepath.ToSlash(g))) + continue + } + add(path.Join(filepath.ToSlash(g), "seats")) + for _, p := range a.Paths { + add(path.Clean(filepath.ToSlash(p))) + } + } + return out +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/narrow_test.go b/modules/mesh-build-node/cmd/mesh-build-node/narrow_test.go new file mode 100644 index 000000000..06380b13e --- /dev/null +++ b/modules/mesh-build-node/cmd/mesh-build-node/narrow_test.go @@ -0,0 +1,74 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/seatgen" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" +) + +// A root contracts module (mesh-contracts at 87eab81, pipeline main.3 of 2026-11-20): two seats, each generated as a Go +// and a TypeScript package naming generated-from ".", in step with the seat generator, beside what no step reads. +func rootContracts(t *testing.T) string { + t.Helper() + tree := t.TempDir() + put := func(p, body string) { + write(t, filepath.Join(tree, filepath.FromSlash(p)), body, 0o644) + } + var arts []string + for _, s := range []string{"one-store", "two-store"} { + put("seats/"+s+"/seat.json", `{"format":1,"seat":"`+s+`","scope":"mesh","grain":"whole","domain":"Module","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"},"answer":{"type":"object"}}]}`) + pkg := strings.ReplaceAll(s, "-", "") + arts = append(arts, + `{"name":"go-`+pkg+`","kind":"package","language":"go","paths":["go/seats/`+pkg+`"],"generated-from":"."}`, + `{"name":"ts-`+pkg+`","kind":"package","language":"typescript","paths":["ts/seats/`+pkg+`"],"generated-from":"."}`) + } + put("module.json", `{"module":"c","version":"0.1","build":{"artifacts":[`+strings.Join(arts, ",")+`]}}`) + put("README.md", "the repository\n") + g, err := seatgen.Load(tree, "example.org/c/go", "@example/c") + if err != nil { + t.Fatal(err) + } + files, err := seatgen.Generate(g) + if err != nil { + t.Fatal(err) + } + for p, body := range files { + put(p, string(body)) + } + return tree +} + +// Design 47 H, H-A-136 and H-A-137: a step's workspace of one package of a root module keeps, beside the package's path +// and module.json, the seats/ directory and the paths of every artifact naming generated-from, so the unit level's +// generator check finds nothing out of step; nothing else is kept. Narrowed bare (steprun.Narrow), the check names the +// generated files left out. +func TestANarrowedRootContractsModuleIsInStepWithTheGenerator(t *testing.T) { + req := sdkstep.FetchRequest{Repository: "novox/c", Commit: commitSHA, Dir: ".", Paths: []string{"ts/seats/onestore"}} + bare := rootContracts(t) + if err := steprun.Narrow(bare, req); err != nil { + t.Fatal(err) + } + if out, err := steprun.OutOfStep(bare, steprun.GeneratedRootTS); err != nil || len(out) == 0 { + t.Fatalf("narrowed bare: out of step %v (%v), want the left-out packages named", out, err) + } + tree := rootContracts(t) + if err := narrowTree(tree, req); err != nil { + t.Fatal(err) + } + if out, err := steprun.OutOfStep(tree, steprun.GeneratedRootTS); err != nil || len(out) != 0 { + t.Errorf("narrowed: out of step %v (%v), want none", out, err) + } + for _, kept := range []string{"module.json", "seats/two-store/seat.json", "ts/seats/twostore/package.json", "go/seats/twostore/go.mod"} { + if _, err := os.Stat(filepath.Join(tree, filepath.FromSlash(kept))); err != nil { + t.Errorf("%s is not kept: %v", kept, err) + } + } + if _, err := os.Stat(filepath.Join(tree, "README.md")); err == nil { + t.Error("README.md is still in the workspace") + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/package.go b/modules/mesh-build-node/cmd/mesh-build-node/package.go index f55341aa3..58d691788 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/package.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/package.go @@ -364,9 +364,9 @@ func placeGroup(dir string, served map[string]*packed) error { return nil } -// sdkLocked is what a module's lock names of the SDK: its version, its integrity and where it was resolved from; ok is -// false when the lock names none (the latest release is then placed, placeSDK). -func sdkLocked(dir string) (version, integrity string, ok bool, err error) { +// locked is what a module's lock names of the package name: its version and its integrity; ok is false when the lock +// names none (the latest release is then placed, placeLatest). +func locked(dir, name string) (version, integrity string, ok bool, err error) { raw, err := os.ReadFile(filepath.Join(dir, "package-lock.json")) if os.IsNotExist(err) { return "", "", false, nil @@ -383,7 +383,7 @@ func sdkLocked(dir string) (version, integrity string, ok bool, err error) { if err := json.Unmarshal(raw, &lock); err != nil { return "", "", false, fmt.Errorf("the package-lock.json is not JSON: %w", err) } - p, ok := lock.Packages["node_modules/"+sdkPackage] + p, ok := lock.Packages["node_modules/"+name] if !ok || p.Version == "" { return "", "", false, nil } @@ -398,51 +398,197 @@ func sdkLocked(dir string) (version, integrity string, ok bool, err error) { // none. The lock's integrity is checked when the lock names the registry's version placed; a registry holding no // release is a wait (`waits for:`). func (m *Module) placeSDK(ctx context.Context, dir, rel string, group *packed) error { - version, integrity, _, err := sdkLocked(dir) + if group == nil { + return m.placeLatest(ctx, dir, rel, sdkPackage) + } + version, _, _, err := locked(dir, sdkPackage) if err != nil { return err } - var tgz []byte - if group != nil { - if m.Say != nil && version != "" && version != group.Version { - m.Say("%s: its lock names %s@%s; the group's %s is placed (design 47 G A-284)", rel, sdkPackage, version, group.Version) - } - tgz = group.tgz - } else { - latest, err := m.registryLatest(ctx, sdkPackage) - if err != nil { - return err - } - if latest == "" { - return fmt.Errorf("%s%s", builds.WaitsFor, sdkPackage) - } - if version != latest { - if m.Say != nil && version != "" { - m.Say("%s: its lock names %s@%s; the latest published %s is placed (ADR 0573 §2)", rel, sdkPackage, version, latest) - } - version, integrity = latest, "" - } - want := sdkPackage + "@" + version - got, registered, held, err := m.registryPackageChecked(ctx, sdkPackage, version) - if err != nil { - return err - } - if !held { - return fmt.Errorf("%s%s", builds.WaitsFor, want) - } - if integrity == "" { - integrity = registered - } - if integrity != "" && integrityOf(got) != integrity { - return fmt.Errorf("the registry's %s is %s, and the lock of %s names %s", want, integrityOf(got), rel, integrity) - } - tgz = got + if m.Say != nil && version != "" && version != group.Version { + m.Say("%s: its lock names %s@%s; the group's %s is placed (design 47 G A-284)", rel, sdkPackage, version, group.Version) } into := filepath.Join(dir, "node_modules", filepath.FromSlash(sdkPackage)) if err := os.RemoveAll(into); err != nil { return err } - return unpackPackage(tgz, into) + return unpackPackage(group.tgz, into) +} + +// placeMeshPackages places in the module's node_modules each mesh package beyond the SDK (@novox/mesh-*) its +// package.json names at the latest release the registry holds, as placeSDK does for the SDK (ADR 0573 §2; design 47 H, +// H-A-267): the install leaves them out (ownDependencies). One the group serves or a member's build lays is left to +// placeGroup and layBuilds, which take precedence; the module itself is not placed. +func (m *Module) placeMeshPackages(ctx context.Context, dir, rel string, served map[string]*packed, members []storedBuild) error { + self, _ := readPackageJSON(dir) + var names []string + for name := range namedPackages(dir) { + if name == sdkPackage || !strings.HasPrefix(name, "@novox/mesh-") || name == self.Name || served[name] != nil || namesPackage(members, name) { + continue + } + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + if err := m.placeLatest(ctx, dir, rel, name); err != nil { + return err + } + } + return nil +} + +// placeLatest places in the module's node_modules the latest release of the mesh package name the registry holds, +// whatever the module's lock names (ADR 0573 §2), checked against the lock's integrity when the lock names that +// version; a registry holding no release is a wait (`waits for:`). +func (m *Module) placeLatest(ctx context.Context, dir, rel, name string) error { + version, integrity, _, err := locked(dir, name) + if err != nil { + return err + } + latest, err := m.registryLatest(ctx, name) + if err != nil { + return err + } + if latest == "" { + return fmt.Errorf("%s%s", builds.WaitsFor, name) + } + if version != latest { + if m.Say != nil && version != "" { + m.Say("%s: its lock names %s@%s; the latest published %s is placed (ADR 0573 §2)", rel, name, version, latest) + } + version, integrity = latest, "" + } + if spec := namedRange(dir, name); spec != "" && m.Say != nil { + // Said, never refused: the latest release is placed whatever the range (ADR 0573 §2; design 47 H, H-A-276). + switch in, read := inRange(spec, version); { + case !read: + m.Say("%s: its package.json names %s at %q, a range not read; the latest published %s is placed (ADR 0573 §2)", rel, name, spec, version) + case !in: + m.Say("%s: the latest published %s@%s lies outside the range %q its package.json names; it is placed (ADR 0573 §2)", rel, name, version, spec) + } + } + want := name + "@" + version + got, registered, held, err := m.registryPackageChecked(ctx, name, version) + if err != nil { + return err + } + if !held { + return fmt.Errorf("%s%s", builds.WaitsFor, want) + } + if integrity == "" { + integrity = registered + } + if integrity != "" && integrityOf(got) != integrity { + return fmt.Errorf("the registry's %s is %s, and the lock of %s names %s", want, integrityOf(got), rel, integrity) + } + into := filepath.Join(dir, "node_modules", filepath.FromSlash(name)) + if err := os.RemoveAll(into); err != nil { + return err + } + return unpackPackage(got, into) +} + +// namedRange is the range the module's package.json names of name: its dependencies first, then its peer, optional and +// dev dependencies; "" when it names none. +func namedRange(dir, name string) string { + raw, err := os.ReadFile(filepath.Join(dir, "package.json")) + if err != nil { + return "" + } + var p map[string]any + if json.Unmarshal(raw, &p) != nil { + return "" + } + for _, k := range []string{"dependencies", "peerDependencies", "optionalDependencies", "devDependencies"} { + deps, _ := p[k].(map[string]any) + if spec, ok := deps[name].(string); ok { + return strings.TrimSpace(spec) + } + } + return "" +} + +// inRange says whether the release v (major.minor.patch) lies in the npm range spec; read is false for a range of a +// form it does not read (a union, a hyphen range, a comparator, a tag other than latest), never taken as in or out. It +// reads what a package file of the mesh names: an exact version, an x-range, a caret and a tilde range, as npm does. +func inRange(spec, v string) (in, read bool) { + spec = strings.TrimSpace(spec) + if spec == "" || spec == "*" || spec == "latest" { + return true, true + } + if strings.ContainsAny(spec, " |<>") { + return false, false + } + op := "" + if spec[0] == '^' || spec[0] == '~' { + op, spec = spec[:1], spec[1:] + } + spec = strings.TrimPrefix(strings.TrimPrefix(spec, "="), "v") + if strings.Contains(spec, "-") || strings.Contains(spec, "+") { + return false, false // a pre-release or build range + } + var low [3]int + given := 0 + for i, part := range strings.Split(spec, ".") { + if i > 2 { + return false, false + } + if part == "x" || part == "X" || part == "*" { + break + } + n, err := strconv.Atoi(part) + if err != nil || n < 0 { + return false, false + } + low[i] = n + given = i + 1 + } + if given == 0 { + return true, true // x, x.x + } + var at [3]int + for i, part := range strings.Split(v, ".") { + if i > 2 { + return false, false + } + n, err := strconv.Atoi(part) + if err != nil { + return false, false + } + at[i] = n + } + // bump is the part of low raised by one for the exclusive upper bound, the parts after it zero. + bump := given - 1 + switch op { + case "^": + switch { + case low[0] > 0 || given == 1: + bump = 0 + case low[1] > 0 || given == 2: + bump = 1 + default: + bump = 2 + } + case "~": + bump = 0 + if given > 1 { + bump = 1 + } + } + high := low + high[bump]++ + for i := bump + 1; i < 3; i++ { + high[i] = 0 + } + less := func(a, b [3]int) bool { + for i := range a { + if a[i] != b[i] { + return a[i] < b[i] + } + } + return false + } + return !less(at, low) && less(at, high), true } // placedSDK is the version of the SDK placed in the module's node_modules ("" when none is). @@ -695,3 +841,115 @@ func setPackageVersion(dir, version string) (restore func(), err error) { } return func() { _ = os.WriteFile(path, raw, 0o644) }, nil } + +// installPlacedDependencies installs into the module's node_modules the dependencies every mesh package placed there +// (@novox/mesh-*: placeSDK, placeMeshPackages, placeGroup, layBuilds) declares, as a registry install of that package +// would (design 47 H, H-A-491 addendum): a placed package's tarball is unpacked whole, and its built code imports what +// its package.json's `dependencies` name (the SDK's seal code imports blakejs). Its devDependencies are left out, a mesh +// package and what is build-time are not installed (ownDependencies), nor one the module's node_modules holds already. +// The install is installOwn's: a scratch package.json naming each at the range its package declares (the first placed +// package by name decides a name two declare), `npm install` through the registry's config file and the npm cache, +// the install's copies of the SDK removed, and each package it put that the module's node_modules lacks moved there. +func (m *Module) installPlacedDependencies(ctx context.Context, root, dir, rel string) error { + nm := filepath.Join(dir, "node_modules") + entries, err := os.ReadDir(filepath.Join(nm, "@novox")) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + wanted := map[string]any{} + for _, e := range entries { + if !e.IsDir() || !strings.HasPrefix(e.Name(), "mesh-") { + continue + } + names, pkg, err := ownDependencies(filepath.Join(nm, "@novox", e.Name())) + if err != nil { + return fmt.Errorf("the placed @novox/%s: %w", e.Name(), err) + } + deps, _ := pkg["dependencies"].(map[string]any) + for _, name := range names { + if _, ok := wanted[name]; ok { + continue + } + if _, err := os.Stat(filepath.Join(nm, filepath.FromSlash(name), "package.json")); err == nil { + continue + } + wanted[name] = deps[name] + } + } + if len(wanted) == 0 { + return nil + } + var names []string + for name := range wanted { + names = append(names, name) + } + sort.Strings(names) + scratch := filepath.Join(root, "npm-placed-"+strings.NewReplacer("/", "-", ".", "root").Replace(rel)) + if err := os.MkdirAll(scratch, 0o700); err != nil { + return err + } + defer os.RemoveAll(scratch) + raw, _ := json.Marshal(map[string]any{"name": "placed-dependencies", "private": true, "dependencies": wanted}) + if err := os.WriteFile(filepath.Join(scratch, "package.json"), raw, 0o600); err != nil { + return err + } + npmrc, err := m.npmrcIn(root) + if err != nil { + return fmt.Errorf("installing the dependencies of the mesh packages placed in %s: %w", rel, err) + } + env := append(m.baseEnv(), "npm_config_cache="+m.npmCache()) + r := m.Run(ctx, env, "npm", "install", "--omit=dev", "--omit=peer", "--ignore-scripts", "--no-bin-links", + "--no-audit", "--no-fund", "--prefix", scratch, "--userconfig", npmrc) + os.Remove(npmrc) + if why := ranFailed(r); why != "" { + return steprun.Transport(fmt.Errorf("installing the dependencies of the mesh packages placed in %s (%s): %s", rel, strings.Join(names, ", "), why)) + } + got := filepath.Join(scratch, "node_modules") + if err := removeSDKCopies(got); err != nil { + return err + } + if err := moveAbsent(got, nm); err != nil { + return err + } + if m.Say != nil { + m.Say("%s: installed %s, which the mesh packages placed there declare (design 47 H, H-A-491)", rel, strings.Join(names, ", ")) + } + return nil +} + +// moveAbsent moves each package of the node_modules from (a scope's packages one by one) to the node_modules into +// that holds none of its name; npm's own files (.bin, .package-lock.json) stay. +func moveAbsent(from, into string) error { + entries, err := os.ReadDir(from) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + for _, e := range entries { + if strings.HasPrefix(e.Name(), ".") || !e.IsDir() { + continue + } + if strings.HasPrefix(e.Name(), "@") { + if err := moveAbsent(filepath.Join(from, e.Name()), filepath.Join(into, e.Name())); err != nil { + return err + } + continue + } + target := filepath.Join(into, e.Name()) + if _, err := os.Stat(target); err == nil { + continue + } + if err := os.MkdirAll(into, 0o755); err != nil { + return err + } + if err := os.Rename(filepath.Join(from, e.Name()), target); err != nil { + return err + } + } + return nil +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/package_paths_test.go b/modules/mesh-build-node/cmd/mesh-build-node/package_paths_test.go index 98dd5f781..56ac043df 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/package_paths_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/package_paths_test.go @@ -91,3 +91,54 @@ func TestAFolderModulesPackageIsBuiltAndTestedInItsPath(t *testing.T) { t.Errorf("unit level = %+v, ran tests in %v, want both package paths", r, tests) } } + +// A step of one package of a root module with several (mesh-contracts' ts-meshbroker beside ts-meshrecovery, pipeline +// main.3 of 2026-11-20) fetches a workspace narrowed to that package's path (ADR 0499 clause 4; design 47 H, H-A-136: +// nothing else is fetched). The other packages' paths are not in it: they are no module of this build, never the +// module's directory, which holds no lock ("the package in . has no package-lock.json"). +func TestANarrowedFetchOfOneFolderPackageLeavesTheOthersOut(t *testing.T) { + m, f := fetchMachine(t, folderFiles(""), nil) + args := map[string]any{"repository": "novox/mesh-contracts", "commit": commitSHA, "dir": ".", "paths": []any{"ts/seats/a"}} + out, err := m.fetch(context.Background(), args) + if err != nil { + t.Fatal(err) + } + r := out.(FetchResult) + if strings.Join(r.Modules, ",") != "ts/seats/a" || strings.Join(r.Installed, ",") != "ts/seats/a" { + t.Errorf("modules %v, installed %v; want only the named package ts/seats/a", r.Modules, r.Installed) + } + if n := len(npmCalls(f)); n != 1 { + t.Errorf("%d npm commands, want the one install of the named package", n) + } +} + +// The lint and test levels of that narrowed workspace run in the named package's path alone: a package whose path was +// left out is no target, and the module's directory is not tested whole in its place (H-A-136). +func TestANarrowedWorkspaceTestsOnlyItsPackage(t *testing.T) { + work := t.TempDir() + files := folderFiles("") + for p := range files { + if strings.HasPrefix(p, "ts/seats/b/") { + delete(files, p) + } + } + for p, body := range files { + write(t, filepath.Join(work, filepath.FromSlash(p)), body, 0o644) + } + for _, tc := range []struct { + narrowed bool + want string + }{{true, "ts/seats/a"}, {false, "."}} { + got, err := testTargets(work, ".", tc.narrowed) + if err != nil { + t.Fatal(err) + } + var where []string + for _, g := range got { + where = append(where, g.where) + } + if strings.Join(where, ",") != tc.want { + t.Errorf("narrowed %v: targets %v, want %s", tc.narrowed, where, tc.want) + } + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/package_test.go b/modules/mesh-build-node/cmd/mesh-build-node/package_test.go index 4eefea9fe..8c7459d52 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/package_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/package_test.go @@ -6,6 +6,7 @@ import ( "compress/gzip" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -33,34 +34,40 @@ func tgzOf(t *testing.T, name, version string) []byte { return buf.Bytes() } -// fakeRegistry serves the packument and the packed files of the versions it holds; asked counts its answers. +// fakeRegistry serves the packument and the packed files of the SDK's versions it holds; asked counts its answers. func fakeRegistry(t *testing.T, m *Module, held map[string][]byte) *atomic.Int32 { + t.Helper() + return fakeRegistryOf(t, m, map[string]map[string][]byte{sdkPackage: held}) +} + +// fakeRegistryOf serves the packument and the packed files of each package's versions it holds (by name); asked counts +// its answers. +func fakeRegistryOf(t *testing.T, m *Module, held map[string]map[string][]byte) *atomic.Int32 { t.Helper() var asked atomic.Int32 var srv *httptest.Server srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { asked.Add(1) - switch { - case r.URL.Path == "/npm/@novox%2fmesh-sdk" || r.URL.Path == "/npm/@novox/mesh-sdk": - if len(held) == 0 { - http.NotFound(w, r) - return - } - versions := map[string]any{} - for v, tgz := range held { - versions[v] = map[string]any{"dist": map[string]any{"tarball": srv.URL + "/files/" + v + ".tgz", "integrity": integrityOf(tgz)}} - } - json.NewEncoder(w).Encode(map[string]any{"versions": versions}) - case strings.HasPrefix(r.URL.Path, "/files/"): - v := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/files/"), ".tgz") - if tgz, ok := held[v]; ok { + if f, ok := strings.CutPrefix(r.URL.Path, "/files/"); ok { + name, v, _ := strings.Cut(strings.TrimSuffix(f, ".tgz"), "@@") + if tgz, ok := held[strings.ReplaceAll(name, "~", "/")][v]; ok { w.Write(tgz) return } http.NotFound(w, r) - default: - http.NotFound(w, r) + return } + name, ok := strings.CutPrefix(r.URL.Path, "/npm/") + name = strings.ReplaceAll(name, "%2f", "/") + if !ok || len(held[name]) == 0 { + http.NotFound(w, r) + return + } + versions := map[string]any{} + for v, tgz := range held[name] { + versions[v] = map[string]any{"dist": map[string]any{"tarball": srv.URL + "/files/" + strings.ReplaceAll(name, "/", "~") + "@@" + v + ".tgz", "integrity": integrityOf(tgz)}} + } + json.NewEncoder(w).Encode(map[string]any{"versions": versions}) })) t.Cleanup(srv.Close) m.Toolchain.Registry = func() (Registry, error) { return Registry{URL: srv.URL + "/npm/"}, nil } @@ -183,3 +190,46 @@ func TestTheGroupPackagesArgumentIsRefusedWhenItIsNotOne(t *testing.T) { t.Errorf("a member's root and a member's directory: %+v %v", gs, err) } } + +// design 47 H, H-A-276 (amending H-A-267): the latest release placed outside the range the package file names is said in +// the journal, and placed all the same; one inside it is not said; a range of a form not read is said as such. +func TestALatestReleaseOutsideItsRangeIsSaid(t *testing.T) { + for _, c := range []struct { + spec, v string + in, read bool + }{ + {"^0.1.0", "0.1.9", true, true}, {"^0.1.0", "0.2.0", false, true}, {"^1.2.3", "1.9.0", true, true}, + {"^1.2.3", "2.0.0", false, true}, {"^0.0.3", "0.0.4", false, true}, {"^0.x", "0.9.0", true, true}, + {"~0.1.2", "0.1.9", true, true}, {"~0.1.2", "0.2.0", false, true}, {"~1", "1.5.0", true, true}, + {"0.1.4", "0.1.4", true, true}, {"0.1.4", "0.1.5", false, true}, {"0.1.x", "0.1.7", true, true}, + {"0.1", "0.2.0", false, true}, {"*", "9.9.9", true, true}, {"^0.1.0", "0.0.9", false, true}, + {">=0.1.0", "0.2.0", false, false}, {"^0.1.0 || ^0.2.0", "0.2.0", false, false}, {"file:../x", "0.1.0", false, false}, + } { + if in, read := inRange(c.spec, c.v); in != c.in || read != c.read { + t.Errorf("inRange(%q, %q) = %v, %v; want %v, %v", c.spec, c.v, in, read, c.in, c.read) + } + } + m, _, _ := newMachine(t) + const name = "@novox/mesh-delivery-contracts-git" + fakeRegistryOf(t, m, map[string]map[string][]byte{name: {"0.1.9": tgzOf(t, name, "0.1.9"), "0.2.0": tgzOf(t, name, "0.2.0")}}) + for _, c := range []struct{ spec, said string }{ + {"^0.1.0", `the latest published ` + name + `@0.2.0 lies outside the range "^0.1.0"`}, + {"^0.2.0", ""}, + {">=0.1.0", `at ">=0.1.0", a range not read`}, + } { + var said []string + m.Say = func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) } + dir := t.TempDir() + write(t, filepath.Join(dir, "package.json"), `{"dependencies":{"`+name+`":"`+c.spec+`"}}`, 0o644) + if err := m.placeLatest(context.Background(), dir, "modules/m", name); err != nil { + t.Fatalf("%s: %v", c.spec, err) + } + if p, _ := readPackageJSON(filepath.Join(dir, "node_modules", filepath.FromSlash(name))); p.Version != "0.2.0" { + t.Errorf("%s: placed %q, want the latest release 0.2.0", c.spec, p.Version) + } + joined := strings.Join(said, "\n") + if c.said == "" && joined != "" || c.said != "" && !strings.Contains(joined, c.said) { + t.Errorf("%s: said %q, want %q", c.spec, joined, c.said) + } + } +} diff --git a/modules/mesh-build-node/cmd/mesh-build-node/probe.go b/modules/mesh-build-node/cmd/mesh-build-node/probe.go index 70ddd21be..e27a02b79 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/probe.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/probe.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "fmt" "os/exec" "strings" @@ -22,6 +23,22 @@ func ProbeNode(ctx context.Context) (string, error) { return parseNodeVersion(string(out)) } +// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly +// what the probed toolchain holds (principle 11: read, never a fixed list). +func ProbeBuiltins(ctx context.Context) ([]string, error) { + ctx, cancel := context.WithTimeout(ctx, ProbeTimeout) + defer cancel() + out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output() + if err != nil { + return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err) + } + var names []string + if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 { + return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out))) + } + return names, nil +} + func parseNodeVersion(out string) (string, error) { v := strings.TrimSpace(out) if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") { diff --git a/modules/mesh-build-node/cmd/mesh-build-node/push_test.go b/modules/mesh-build-node/cmd/mesh-build-node/push_test.go index 880a774d7..b3d0dd3a1 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/push_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/push_test.go @@ -1,6 +1,9 @@ package main import ( + "archive/tar" + "bytes" + "compress/gzip" "context" "crypto/sha256" "encoding/base64" @@ -9,6 +12,8 @@ import ( "errors" "os" "path/filepath" + "reflect" + "slices" "strings" "sync" "testing" @@ -18,6 +23,7 @@ import ( builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds" sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-sdk/go/forgekey" ) // pushed are the blobs the fake holder took, by digest, for the tests that read an archive back. @@ -51,7 +57,7 @@ func withStore(t *testing.T, m *Module) *fakeStore { case "publish": var in registry.PublishInput _ = json.Unmarshal(raw, &in) - if (seat == steprun.ArtifactSeat) != (in.Kind == "bundle") || in.Transfer == "" || strings.ContainsAny(in.Transfer, "/. *>") { + if (seat == steprun.ArtifactSeat) != (in.Kind == "bundle" || in.Kind == "archive") || in.Transfer == "" || strings.ContainsAny(in.Transfer, "/. *>") { t.Errorf("publish on %s of kind %q, transfer %q", seat, in.Kind, in.Transfer) } s.open[in.Transfer] = in @@ -94,11 +100,13 @@ func archiveOf(t *testing.T, r BuildResult) []byte { } // 1587-S6 (ADR 0498 §1; CAT-BN3): a done bundle is published through oci-artifact-registry and answers the seat's -// reference of its archive, under the manifest's module. +// reference of its archive, under the manifest's module. Its publish names the version the ask reserved, so the bundle +// is marked against its reservation (design 47 H, H-A-372). func TestADoneBundleAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) { m, _, _ := builtMachine(t, ``) store := withStore(t, m) - out, err := m.build(context.Background(), buildArgs()) + args := buildArgs() + out, err := m.build(context.Background(), args) if err != nil { t.Fatal(err) } @@ -109,6 +117,75 @@ func TestADoneBundleAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) { if store.blobs["m/tools@"+r.Digest] == nil || len(store.seats) != 1 || store.seats[0] != steprun.ArtifactSeat { t.Errorf("the holder holds %d files through %v, not m/tools@%s through %s", len(store.blobs), store.seats, r.Digest, steprun.ArtifactSeat) } + if len(store.published) != 1 || store.published[0].Version != "1.4.3" { + t.Errorf("the bundle was published as %+v, want the ask's version 1.4.3", store.published) + } + // Design 47 H2 §800, H-A-403, H-A-427: an install runs no script and makes no link; its tree alone, under the module's + // directory, is published as the archive :node-modules under the ask's version, and the end names its reference. + t.Run("an install runs no script", func(t *testing.T) { + m := &Module{Work: t.TempDir(), Toolchain: &Toolchain{Paths: Paths{Home: t.TempDir(), Cache: t.TempDir()}, + Registry: func() (Registry, error) { return Registry{}, nil }}} + store := withStore(t, m) + var ran []string + var written map[string]any + m.Run = func(_ context.Context, _ []string, name string, args ...string) forgekey.Ran { + ran = append([]string{name}, args...) + dir := args[slices.Index(args, "--prefix")+1] + raw, _ := os.ReadFile(filepath.Join(dir, "package.json")) + _ = json.Unmarshal(raw, &written) + os.MkdirAll(filepath.Join(dir, "node_modules", "left-pad"), 0o755) + os.WriteFile(filepath.Join(dir, "node_modules", "left-pad", "index.js"), []byte("module.exports = 1\n"), 0o644) + return forgekey.Ran{} + } + lock := `{"lockfileVersion": 3, "packages": {"": {"name": "@novox/module-gitea", "scripts": {"install": "touch ran"}, + "dependencies": {"left-pad": "^1.3.0"}}, "node_modules/left-pad": {"version": "1.3.0", "hasInstallScript": true}}}` + install := func(lock string) (any, error) { + return m.installTreeStep(context.Background(), map[string]any{"module": "gitea", "commit": strings.Repeat("a", 40), "fingerprint": "fp", + "pipeline": "p1", "lock": lock, "artifact": sdkstep.InstallArtifact("gitea"), "version": "0.4.2"}) + } + out, err := install(lock) + if err != nil { + t.Fatal(err) + } + if !slices.Contains(ran, "--ignore-scripts") || !slices.Contains(ran, "--no-bin-links") || ran[0] != "npm" || ran[1] != "ci" { + t.Errorf("the install ran %v, want npm ci --ignore-scripts --no-bin-links", ran) + } + if _, scripts := written["scripts"]; scripts || written["name"] != "@novox/module-gitea" { + t.Errorf("the package.json beside the lock is %v, want the lock's root with no script", written) + } + if len(store.published) != 1 || store.published[0].Name != "gitea/node-modules" || store.published[0].Kind != "archive" || store.published[0].Version != "0.4.2" { + t.Fatalf("published %+v, want gitea/node-modules of kind archive at 0.4.2", store.published) + } + digest := store.published[0].Digest + if want := map[string]any{"archive": "oci-artifact-registry/gitea/node-modules@" + digest}; !reflect.DeepEqual(out, want) { + t.Errorf("the install answered %v, want %v", out, want) + } + if names := archiveNames(t, store.blobs["gitea/node-modules@"+digest]); !slices.Equal(names, []string{"modules/gitea/node_modules/left-pad/index.js"}) { + t.Errorf("the archive holds %v, want the tree alone under the module's directory", names) + } + if _, err := install(`{"lockfileVersion": 1, "dependencies": {}}`); err == nil { + t.Error("a lock with no root package was installed") + } + }) +} + +// archiveNames are the file names a packed archive holds (steprun.Pack: tar in gzip). +func archiveNames(t *testing.T, archive []byte) []string { + t.Helper() + z, err := gzip.NewReader(bytes.NewReader(archive)) + if err != nil { + t.Fatal(err) + } + var names []string + r := tar.NewReader(z) + for { + h, err := r.Next() + if err != nil { + break + } + names = append(names, h.Name) + } + return names } // 1587-S7 and S8 (ADR 0498 §2, the lead's decision L9): a publish the holder refuses fails the step `not stored: @@ -131,17 +208,9 @@ func TestARefusedPushFailsNotStoredAndNoPackedFileStays(t *testing.T) { if c.words != "" && (err == nil || !strings.HasPrefix(err.Error(), builds.NotStored+"tools: ") || !strings.Contains(err.Error(), c.words)) { t.Errorf("a refused publish answered %v", err) } - if c.noSeat { - // ADR 0664 §1: with a holder named by the assigner the same words are a transport fault, the bus gives the ask again. - m.Call = func(key string, _ any) (json.RawMessage, error) { - if key == steprun.AssignerHolders { - return json.RawMessage(`{"seats":[{"seat":"oci-artifact-registry","holders":[{"module":"mesh-registry","node":"novox"}]}],"holds":1}`), nil - } - return nil, errors.New("nats: no responders available for request") - } - if _, err := m.build(context.Background(), buildArgs()); err == nil || !sdkstep.IsPassing(err) || !strings.Contains(err.Error(), "the holder is silent") { - t.Errorf("no responders with a holder named answered %v, want a transport fault", err) - } + if c.noSeat && (err == nil || !sdkstep.IsPassing(err) || !strings.Contains(err.Error(), "publish: ")) { + // A publish met by no responders is a transport fault with no seat call to learn why (design 47 H2 §799). + t.Errorf("no responders answered %v, want a transport fault opening publish:", err) } var archives []string filepath.WalkDir(work, func(p string, d os.DirEntry, err error) error { diff --git a/modules/mesh-build-node/cmd/mesh-build-node/read.go b/modules/mesh-build-node/cmd/mesh-build-node/read.go index ec7b2d2a8..6b6a29dac 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/read.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/read.go @@ -147,15 +147,15 @@ func (m *Module) RecentSteps(limit int) (lines []StepLine, cut bool, err error) if err != nil { return nil, false, err } - own := keys[:0:0] + // Every key of this node's steps, an ask's under its asker (`..`) as well as `.` (design 47 + // H2 §801): the tool is never empty while asks run. Ordered by the id, newest first. + own, ids := keys[:0:0], map[string]string{} for _, k := range keys { - if strings.HasPrefix(k, m.Node+".") { - if _, node, _, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { - own = append(own, k) - } + if _, node, id, err := sdkstep.ParseStepKey(k); err == nil && node == m.Node { + own, ids[k] = append(own, k), id } } - sort.Sort(sort.Reverse(sort.StringSlice(own))) + sort.SliceStable(own, func(i, j int) bool { return ids[own[i]] > ids[own[j]] }) if n := min(max(limit*4, 100), MaxStateReads); len(own) > n { own, cut = own[:n], true } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/read_test.go b/modules/mesh-build-node/cmd/mesh-build-node/read_test.go index 70be8af51..ae61e13c0 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/read_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/read_test.go @@ -157,10 +157,12 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { reads int64 steps int cut bool + asked bool // design 47 H2 §801: the newest step is an ask's, keyed under its asker }{ - {20, 0, 20, 10, false}, - {600, 0, 100, 10, true}, - {1500, 300, MaxStateReads, 300, true}, + {20, 0, 20, 10, false, false}, + {600, 0, 100, 10, true, false}, + {1500, 300, MaxStateReads, 300, true, false}, + {19, 0, 20, 10, false, true}, } { var reads, inFlight, maxFlight atomic.Int64 stored := map[string][]byte{} @@ -170,6 +172,10 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { stored[n+".s"+fmt.Sprintf("%04d", i)] = b } } + if row.asked { + b, _ := sdkstep.EncodeStep(sdkstep.Step{ID: "s9999", Tool: "t", Node: "shanks", State: sdkstep.StepRunning, Started: t0.Add(time.Hour)}) + stored["mesh-pipeline-runner.shanks.s9999"] = b + } m := &Module{Node: "shanks"} m.ReadSteps = StateRead{ Keys: func() ([]string, error) { @@ -186,7 +192,7 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { } time.Sleep(time.Millisecond) inFlight.Add(-1) - if !strings.HasPrefix(key, "shanks.") { + if _, node, _, err := sdkstep.ParseStepKey(key); err != nil || node != "shanks" { t.Errorf("read %s, a key of another node", key) } return stored[key], nil @@ -200,6 +206,9 @@ func TestRecentStepsReadsOnlyTheNodesKeysInParallelAndBounded(t *testing.T) { if row.cut && len(lines) > 0 && lines[0].ID != fmt.Sprintf("s%04d", row.perNode-1) { t.Errorf("%d a node: newest answered %s", row.perNode, lines[0].ID) } + if row.asked && (len(lines) == 0 || lines[0].ID != "s9999") { + t.Errorf("an ask's step under its asker is not the newest line: %+v", lines) + } if maxFlight.Load() < 2 { t.Errorf("%d a node: values read one at a time", row.perNode) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/steps.go b/modules/mesh-build-node/cmd/mesh-build-node/steps.go index ff4e7d2fb..4593073f7 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/steps.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/steps.go @@ -1,7 +1,9 @@ package main // **The verb `steps`** (design 47 G §22, §307, §326, §328): which pipeline steps a TypeScript artifact can run, by the -// convention check.go tests by. The type-check is the lint step (§328) and is always one; the unit step is the packages +// convention check.go tests by. The type-check is the lint step (§328), answered only when one of the artifact's packages +// holds a TypeScript file, by the test the lint step itself uses (lint.go; design 47 H2 H-A-515 second addendum), so the +// pipeline runner ends a lint with nothing to type-check at placement, never asking it (H-A-515 addendum); the unit step is the packages // holding a package.json script `test`, the integration step those holding `test:integration`. A level with none is not // answered. The answer is kept in the state detected-steps by the artifact's fingerprint, replaced by a newer one and by // again, as the Go build module keeps it. @@ -43,14 +45,23 @@ type StepsAnswer struct { Error string `json:"error,omitempty"` } -// detectSteps finds the steps of the package directories under dir. -func detectSteps(dir string) ([]DetectedStep, error) { - targets, err := testTargets(dir, ".") +// detectSteps finds the steps of the package directories under dir; narrowedTree says the tree was narrowed to an +// artifact's paths, as testTargets reads it. +func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) { + targets, err := testTargets(dir, ".", narrowedTree) if err != nil { return nil, err } unit, integration := []string{}, []string{} + lint := false for _, tg := range targets { + if !lint { + sources, err := typeScriptFiles(tg.dir) + if err != nil { + return nil, err + } + lint = len(sources) > 0 + } scripts, err := packageScripts(tg.dir) if err != nil { return nil, err @@ -62,7 +73,10 @@ func detectSteps(dir string) ([]DetectedStep, error) { integration = append(integration, tg.where) } } - steps := []DetectedStep{{Step: StepLint}} + steps := []DetectedStep{} + if lint { + steps = append(steps, DetectedStep{Step: StepLint}) + } for _, l := range []struct { step string pkgs []string @@ -78,7 +92,7 @@ func detectSteps(dir string) ([]DetectedStep, error) { // stepsTool is the seat's verb `steps`. func (m *Module) stepsTool() stdio.Tool { return stdio.Tool{Name: Seat + "." + seat.VerbSteps, - Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, always; unit tests where a package has a test script; " + + Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, where one of its packages holds a TypeScript file; unit tests where a package has a test script; " + "integration tests where one has a test:integration script. A level with no test is not answered.", Input: map[string]any{"type": "object", "required": []string{"module", "artifact"}, "properties": map[string]any{ "module": map[string]any{"type": "string"}, @@ -113,7 +127,7 @@ func (m *Module) steps(ctx context.Context, args map[string]any) (any, error) { key := seat.DetectedStepsByModuleArtifactKey(str("module"), name) if again, _ := args["again"].(bool); !again && fp != "" && m.ReadDetected != nil { if raw, err := m.ReadDetected(key); err == nil && len(raw) > 0 { - if kept, err := seat.DecodeDetectedStepsByModuleArtifactValue(raw); err == nil && kept.Fingerprint == fp { + if kept, _, err := seat.DecodeDetectedStepsByModuleArtifactValue(raw); err == nil && kept.Fingerprint == fp { return StepsAnswer{Artifact: artifact, Fingerprint: fp, Steps: kept.Steps, Kept: true}, nil } } @@ -176,7 +190,8 @@ func (m *Module) stepsOfTree(ctx context.Context, req sdkstep.FetchRequest) ([]D return nil, err } if len(req.Paths) > 0 { - if err := steprun.Narrow(tree, req); err != nil { + // Narrowed as the fetch of the step's workspace narrows (narrowTree), so the steps answered are those the levels run. + if err := narrowTree(tree, req); err != nil { return nil, err } } @@ -184,5 +199,5 @@ func (m *Module) stepsOfTree(ctx context.Context, req sdkstep.FetchRequest) ([]D if req.Dir != "" && req.Dir != "." { dir = filepath.Join(tree, filepath.FromSlash(req.Dir)) } - return detectSteps(dir) + return detectSteps(dir, len(req.Paths) > 0) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/steps_test.go b/modules/mesh-build-node/cmd/mesh-build-node/steps_test.go index 3593c2d65..272e2ad12 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/steps_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/steps_test.go @@ -10,8 +10,9 @@ import ( "testing" ) -// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint always, the packages with a test script as -// unit, those with test:integration as integration, and leaves out a level with none. +// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint where a package holds a TypeScript file (design 47 +// H2 H-A-515 second addendum: none for a tree with none, whose lint would end nothing to run), the packages with a test +// script as unit, those with test:integration as integration, and leaves out a level with none. func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) { put := func(dir, name, body string) { if err := os.MkdirAll(filepath.Join(dir), 0o755); err != nil { @@ -22,17 +23,37 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) { } } for name, c := range map[string]struct { - pkg string - want []DetectedStep + pkg string + noTS bool + narrowed bool + want []DetectedStep }{ - "both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, + "both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}, {Step: "integration", Packages: []string{"."}}}}, - "unit only": {`{"scripts":{"test":"node t.js"}}`, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}}, - "no script": {`{"scripts":{}}`, []DetectedStep{{Step: "lint"}}}, + "unit only": {`{"scripts":{"test":"node t.js"}}`, false, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}}, + "no script": {`{"scripts":{}}`, false, false, []DetectedStep{{Step: "lint"}}}, + // No TypeScript file (only a declaration, as a generated package of JavaScript has): nothing to type-check, no lint. + "no TypeScript file": {`{"scripts":{}}`, true, false, []DetectedStep{}}, + // A folder module's tree narrowed to ts/seats/a (H-A-136): the steps are those the narrowed levels run there. + "narrowed folder": {"", false, true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}}, } { dir := t.TempDir() - put(dir, "package.json", c.pkg) - got, err := detectSteps(dir) + if c.narrowed { + for p, body := range folderFiles("") { + if !strings.HasPrefix(p, "ts/seats/b/") { + put(filepath.Join(dir, filepath.Dir(p)), filepath.Base(p), body) + } + } + } else { + put(dir, "package.json", c.pkg) + if c.noTS { + put(dir, "index.d.ts", "export declare const v: number;\n") + put(dir, "index.js", "export const v = 1;\n") + } else { + put(dir, "index.ts", "export const v = 1;\n") + } + } + got, err := detectSteps(dir, c.narrowed) if err != nil || !reflect.DeepEqual(got, c.want) { t.Errorf("%s: steps = %+v (%v), want %+v", name, got, err, c.want) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/store_integration_test.go b/modules/mesh-build-node/cmd/mesh-build-node/store_integration_test.go index 65634fb0a..558c27337 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/store_integration_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/store_integration_test.go @@ -96,7 +96,7 @@ func TestADoneBundleResolvesInARealArtifactStore(t *testing.T) { needBubblewrap(t) m, _ := realMachine(t) addr := realStore(t, m) - out, err := m.build(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m", "artifact": "tools"}) + out, err := m.build(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m", "artifact": "tools", "version": askedVersion}) if err != nil { t.Fatal(err) } diff --git a/modules/mesh-build-node/cmd/mesh-build-node/toolchain.go b/modules/mesh-build-node/cmd/mesh-build-node/toolchain.go index f984f9a22..a6bee5544 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/toolchain.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/toolchain.go @@ -172,13 +172,8 @@ func (t Toolchain) open(dir string) error { return os.Chmod(mark, 0o644) } -func tail(s string) string { - s = strings.TrimSpace(s) - if len(s) > 400 { - s = s[len(s)-400:] - } - return s -} +// tail is what a failed toolchain install wrote on stderr, its head and its tail within 400 bytes (H-A-475). +func tail(s string) string { return headAndTail(strings.TrimSpace(s), 400) } func (t *Toolchain) homeOrEmpty() string { if t == nil { diff --git a/modules/mesh-build-node/cmd/mesh-build-node/tools.go b/modules/mesh-build-node/cmd/mesh-build-node/tools.go index 604a034e3..0233b633e 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/tools.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/tools.go @@ -25,7 +25,7 @@ type StepTool struct { // StepTools are the module's step tools. Each step's issue adds its own. func (m *Module) StepTools() []StepTool { - return []StepTool{m.fetchTool(), m.testTool(), m.buildTool()} + return []StepTool{m.fetchTool(), m.testTool(), m.buildTool(), m.importsTool()} } // Tools is every tool the module serves: its step tools behind the guard, its status and its health. @@ -43,6 +43,7 @@ func (m *Module) Tools(steps []StepTool) []stdio.Tool { tools = append(tools, m.ReadTools()...) tools = append(tools, steprun.StepEndTool(StepEndTool, m.Node, m.stepScan(), m.Held)) tools = append(tools, m.releaseTool()) + tools = append(tools, pruneTools()...) return append(tools, stdio.Tool{Name: StatusTool, Description: "What the Node build module is on this machine: the Node version its recipe builds with and the one installed, " + diff --git a/modules/mesh-build-node/cmd/mesh-build-node/workspace.go b/modules/mesh-build-node/cmd/mesh-build-node/workspace.go index 11f1936ce..0ad4edaf5 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/workspace.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/workspace.go @@ -15,6 +15,7 @@ import ( "path/filepath" "regexp" "strings" + "unicode/utf8" "git.novox.be/novox/mesh-sdk/go/forgekey" ) @@ -180,18 +181,17 @@ func (m *Module) runIn(ctx context.Context, root string, write bool, dir string, return run(ctx, extra, "env", append([]string{"-C", dir, name}, args...)...) } -// ranFailed says why a command did not pass, or "" when it did (issue 1703): its exit status, the end of what it wrote -// on stderr (npm's error is its last lines) and the start of what it wrote on stdout (tsc writes its errors there, -// first first), each bounded, so a long stdout never pushes stderr's error out of the reason. +// ranFailed says why a command did not pass, or "" when it did (issue 1703): its exit status, the head and the tail of +// what it wrote on stderr (npm's error is its last lines; esbuild's is its first, before its Node launcher's stack +// trace, H-A-475) and the start of what it wrote on stdout (tsc writes its errors there, first first), each bounded, so +// a long stdout never pushes stderr's error out of the reason. func ranFailed(r forgekey.Ran) string { if r.Status == 0 && r.Err == "" { return "" } why := fmt.Sprintf("status %d %s", r.Status, r.Err) if e := strings.TrimSpace(r.Stderr); e != "" { - if len(e) > failedBytes/2 { - e = "... " + e[len(e)-failedBytes/2:] - } + e = headAndTail(e, failedBytes/2) why += ": stderr: " + e } if o := strings.TrimSpace(r.Stdout); o != "" { @@ -205,3 +205,26 @@ func ranFailed(r forgekey.Ran) string { // failedBytes bounds what ranFailed carries of a command's output, stderr and stdout half each. const failedBytes = 1500 + +// headAndTail is s when it fits in max bytes, else its first and its last part within max, with "… bytes left +// out …" between them (H-A-475): a launcher's stack trace at the end never pushes the tool's own error line at the +// start out of what is kept, nor the reverse. Both parts are cut on whole characters. +func headAndTail(s string, max int) string { + if len(s) <= max { + return s + } + mark := func(n int) string { return fmt.Sprintf(" … %d bytes left out … ", n) } + room := max - len(mark(len(s))) + if room < 2 { + room = 2 + } + head := s[:room/2] + for len(head) > 0 && !utf8.RuneStart(s[len(head)]) { + head = head[:len(head)-1] + } + tail := s[len(s)-(room-room/2):] + for len(tail) > 0 && !utf8.RuneStart(tail[0]) { + tail = tail[1:] + } + return head + mark(len(s)-len(head)-len(tail)) + tail +} diff --git a/modules/mesh-build-node/go.mod b/modules/mesh-build-node/go.mod index 48a161b27..73bdb12b6 100644 --- a/modules/mesh-build-node/go.mod +++ b/modules/mesh-build-node/go.mod @@ -5,6 +5,7 @@ go 1.26.0 require ( git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000 @@ -101,7 +102,6 @@ require ( git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect ) diff --git a/modules/mesh-build-node/module.json b/modules/mesh-build-node/module.json index 1f141d375..b0a1f50f4 100644 --- a/modules/mesh-build-node/module.json +++ b/modules/mesh-build-node/module.json @@ -1,6 +1,7 @@ { "module": "mesh-build-node", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds": "0.1", "git.novox.be/novox/mesh-catalog/modules/ssh-client/sshkeys": "0.1" @@ -13,17 +14,21 @@ "user-namespaces" ], "state": [ - "toolchains", - "keys", - "pauses" + {"name": "toolchains", "max-mib": 8}, + {"name": "keys", "max-mib": 8}, + {"name": "pauses", "max-mib": 8} ], "claims": [ { "name": "node-build-node", "scope": "node", - "serves": ["current", "drop", "pause", "resume", "steps", "kept-artifact", "output"] + "serves": ["current", "drop", "pause", "resume", "steps", "kept-artifact", "output", "answer"] } ], + "consumes": [ + "mesh-catalog.seat-definition-changed", + "mesh-catalog.seat-definition-removed" + ], "config": { "capacity": { "type": "number", @@ -42,23 +47,52 @@ "description": "How many processors one Node step of this module needs (tsc, esbuild and a test runner; a median step takes 15 s). The capacity above is an upper bound: on each node the module runs at most floor(the cores of its build slice's CPU quota / this) steps at once, the quota read live from its cgroup (issue 1806), so a lowered build CPU share never starves its steps. Above 0.", "minimum": 0.1, "default": 2 + }, + "again-delays": { + "type": "string", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "trusted": false, + "runtime": true, + "default": "15s,60s" + }, + "prune-mark": { + "type": "number", + "description": "The fill of mesh-build-node's state detected-steps, in percent of its cap, past which the module prunes it at its own write, oldest first (design 47 H2 §812): below the bus module's raise mark of 75 %.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 70 + }, + "prune-target": { + "type": "number", + "description": "The fill, in percent of the cap, a prune of mesh-build-node's state detected-steps takes it down to (design 47 H2 §812); below prune-mark.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 50 } }, "tools": [ "build_node_fetch", "build_node_test", "build_node_build", + "build_node_imports", "build_node_release", "build_node_step", "build_node_steps", "build_node_step_end", "build_node_toolchains", "build_node_status", - "build_node_health" + "build_node_health", + "mesh-build-node_state_keep", + "mesh-build-node_state_prune_now" ], "requires": [ - {"name": "steps", "storage": "key-value", "template": "state", "options": {"ttl-seconds": 172800, "objects-max-mib": 256}}, - {"name": "detected-steps", "storage": "key-value", "template": "state", "options": {"history": 1}}, + {"name": "steps", "storage": "key-value", "template": "state", "options": {"ttl-seconds": 172800, "objects-max-mib": 256, "max-mib": 16}}, + {"name": "detected-steps", "storage": "key-value", "template": "state", "options": {"history": 1, "max-mib": 8}}, + {"name": "outputs", "storage": "object-store", "template": "objects", "options": {"max-mib": 1024, "max-age-days": 7}}, "artifact-store", "forge-account", "npm-package-registry", @@ -75,8 +109,8 @@ "seat:oci-artifact-registry.publish-part", "seat:npm-package-registry.publish", "seat:npm-package-registry.publish-part", - "seat:mesh-module-assigner.assignments", - "seat:mesh-catalog.module" + "seat:mesh-catalog.module", + "seat:mesh-catalog.seat-definitions" ], "own-secrets": { "broker": "${dir:state}/broker" @@ -200,6 +234,9 @@ "binary": "mesh-build-node", "loads": [ "mesh-build-node" + ], + "check-needs": [ + "node-build-node" ] }, { diff --git a/modules/mesh-catalog/module.json b/modules/mesh-catalog/module.json index f3353220c..421804df1 100644 --- a/modules/mesh-catalog/module.json +++ b/modules/mesh-catalog/module.json @@ -2,6 +2,7 @@ "module": "mesh-catalog", "slug": "catalog", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/mesh-cli/README.md b/modules/mesh-cli/README.md index 1835cf7e2..ef4e1eac0 100644 --- a/modules/mesh-cli/README.md +++ b/modules/mesh-cli/README.md @@ -35,21 +35,24 @@ puts the call on the bus, as every agent session on the machine does. The consol - **Who judges.** The seat that owns the job: a change of assignments is a proposal the operator approves (`mesh-module-assigner.propose`), a config value is set with its why (`mesh-config.config`), a silence or a hand act is - recorded as one. Until novox/hq issue 1126 the controller ran these lines and judged the account (ADR 0272); with - the controller unassigned, that judgement went with it. -- **The map.** Every line the controller ran, and the seat verb or tool that does its job now, or none, is - `commands.go`'s table (and hq's `.work/1126/nox-map.md` while issue 1126 runs). A line no seat or module owns says - that it was the controller's, that the controller is unassigned, and what to use instead, and exits 1 having called - nothing. A line nox cannot read says how it is written and exits 2. + recorded as one. +- **The map.** Every line nox takes, and the seat verb or tool that does its job, is `commands.go`'s table. A line + nox does not know, or cannot read, says so and how lines are found or written, and exits 2 having called nothing. - **Any address.** `nox call
[json]` calls any seat verb or tool; `nox search ` and `nox describe
` find one and its arguments. -- **What is printed.** The owner's answer as the console gave it (JSON), on standard output with exit 0; an answer the +- **What is printed.** The owner's answer as the console gave it (JSON), or the line's table (`nox nodes`, + `nox licence`, `nox licence usage`; `--json` prints the answer raw), on standard output with exit 0; an answer the console marks an error (a refusal, nothing serving, no answer within its bound) on standard error with exit 1. A console that does not answer is said as nothing having been called; no answer in time is said as a call that may have run. - **`nox status`** is the delivery view's (`mesh-delivery-view.view_status`). When the view does not answer, nox says so first, shows the open conditions and the deliveries under their own addresses, and exits 1: they are never passed off as the status. +- **`nox licence`** (and `nox licence list`) is the operator's overview of the licences in one line + (one-question-one-tool): the licence manager's `licences` as one table (licence, kind, bound nodes, weekly, session + and sonnet usage with their resets, the token's expiry, failures, conditions, whether it is the target), then its + `bindings` (node, licence, since, why), every time local; with `--json` the two answers as one object + `{licences, bindings}`. `nox licence usage []` is the manager's `usage` readings as a table. - **`nox enrol open --key `** runs here and asks nothing of the mesh (ADR 0587 §8). A process that runs for a verb (it carries `MESH_VERB`) is refused before anything is called: a verb is never the @@ -57,15 +60,16 @@ operator. ## What it does not do yet -- **No formatting beyond `nox nodes`.** Answers are the owners' JSON. -- **Lines with no owner.** Accepting a secret from a person, making or setting the operator key, opening a sealed - secret locally, registering a module from another repository and forgetting a module have no seat verb yet; nox - names what to use meanwhile. +- **No formatting beyond `nox nodes` and the licence lines.** Answers are the owners' JSON. +- **No line without a seat verb.** Accepting a secret from a person, making or setting the operator key, opening a + sealed secret locally, registering a module from another repository and forgetting a module have no seat verb yet, + so nox has no line for them. ## Tests `go test ./...`: every owned line calls its owner's address with the arguments it reads, against a stand-in console -answering MCP `tools/call` as node-tools does; a line with no owner or not read calls nothing and says why; an error +answering MCP `tools/call` as node-tools does; a line not known or not read calls nothing and says why; the licence +lines print their tables from the manager's answers; an error answer, a silent console and a verb's process are said; the status's fallback is labelled and exits 1; the console's address is found; `enrol open` opens a sealed token locally; the module places the program and the console's address and nothing else. diff --git a/modules/mesh-cli/cmd/mesh-cli/commands.go b/modules/mesh-cli/cmd/mesh-cli/commands.go index 71a971df7..84e42eb8d 100644 --- a/modules/mesh-cli/cmd/mesh-cli/commands.go +++ b/modules/mesh-cli/cmd/mesh-cli/commands.go @@ -1,8 +1,7 @@ package main -// Every command line nox takes, and the seat verb or module tool that owns its job now that the controller is -// unassigned (novox/hq issue 1126; the map is hq's .work/1126/nox-map.md). A line no seat or module owns says so and -// names what to use instead: it never fails silently, and it never pretends to have run. +// Every command line nox takes, and the seat verb or module tool that owns its job. A line nox does not know says so +// and calls nothing: it never fails silently, and it never pretends to have run. import ( "encoding/json" @@ -93,18 +92,25 @@ type command struct { words []string usage string does string - // build reads the line and answers the call; nil for a line no seat owns. + // build reads the line and answers the call. build func(l line) (call, error) // allowed are the flags the line reads; any other is refused before anything is called. allowed []string - // instead says, for a line with no owner, what to use; empty for one that is owned. - instead string - // render shapes a successful answer for reading; nil prints it as the console gave it. + // render shapes a successful answer for reading; nil prints it as the console gave it. With --json the answer is + // printed raw. render func(text string) string + // also is a second call the line makes after the first, its answer read beside the first's; nil for a line of one + // call. + also *second } -// gone is the reason every unowned line gives. -const gone = "this was the controller's, and the controller is unassigned (novox/hq issue 1126). Nothing was called" +// second is a line's second call: its address, asked with no arguments, the keys the two raw answers are printed +// under with --json, and the render that reads both answers. +type second struct { + address string + keys [2]string + render func(first, second string) string +} // commands is every line, longest words first within a word. var commands = []command{ @@ -120,8 +126,6 @@ var commands = []command{ {words: []string{"node", "public-domain"}, usage: " [ | --clear] [--why ]", does: "the domain a node composes its routed names under; with a domain or --clear, proposed to assignments", allowed: []string{"clear", "why"}, build: publicDomain}, - {words: []string{"node", "add"}, instead: "a new machine joins through the seat mesh-node-enroller: nox enrol issue --why "}, - {words: []string{"node", "networks"}, instead: "no seat keeps a node's routed networks yet; mesh-module-assigner.assignments shows what a node decides"}, {words: []string{"plan"}, usage: "", does: "what the assigner wants the node to run", build: optNode("mesh-delivery-view.assigner_wants")}, {words: []string{"haves"}, usage: "[]", does: "what each node runs, as its node-engine said", build: optNode("mesh-delivery-view.node_haves")}, {words: []string{"switch"}, does: "what each node runs, as its node-engine said", build: fixed("mesh-delivery-view.node_haves")}, @@ -135,7 +139,6 @@ var commands = []command{ {words: []string{"seats"}, does: "who holds each seat, and where", build: func(line) (call, error) { return call{"mesh-module-assigner.assignments", map[string]any{"seats": "true"}}, nil }}, - {words: []string{"seat"}, instead: "a seat is held by placing its module: nox assign --why (mesh-module-assigner.propose)"}, {words: []string{"assign"}, usage: " ... --why ", does: "propose placing modules on a node", allowed: []string{"why"}, build: placeModules("place")}, {words: []string{"unassign"}, usage: " ... --why ", does: "propose taking modules off a node", @@ -157,7 +160,6 @@ var commands = []command{ }}, {words: []string{"proposals"}, usage: "[]", does: "the open proposals of assignments", build: optArg("mesh-module-assigner.proposals", "id")}, {words: []string{"overlay", "show"}, does: "every node's assignments, with its tunnel", build: fixed("mesh-module-assigner.assignments")}, - {words: []string{"overlay"}, instead: "a node's tunnel is a decided field of its assignments: mesh-module-assigner.propose with op decide"}, // Deliveries and builds. {words: []string{"deliveries"}, usage: "[--state s] [--repository owner/repo] [--group g] [--all]", @@ -166,28 +168,7 @@ var commands = []command{ return call{"mesh-delivery.deliveries", pick(l, "state", "repository", "group", "all")}, nil }}, {words: []string{"delivery"}, usage: "", does: "one delivery or group whole", build: needArg("mesh-delivery.show", "id")}, - {words: []string{"groups"}, usage: "[--all]", does: "every delivery group", allowed: []string{"all"}, - build: func(l line) (call, error) { return call{"mesh-delivery.groups", pick(l, "all")}, nil }}, {words: []string{"stalled"}, does: "every delivery held past its state's bound", build: fixed("mesh-delivery.stalled")}, - {words: []string{"checks"}, usage: " [--number n | --commit c]", does: "what the mesh's checks said of a head", - allowed: []string{"number", "commit"}, build: func(l line) (call, error) { - if len(l.pos) != 1 { - return call{}, usageErr("give the repository, owner/repo") - } - a := pick(l, "number", "commit") - a["repository"] = l.pos[0] - return call{"mesh-delivery.checks", a}, nil - }}, - {words: []string{"try"}, usage: " [--level l] [--trunk t] [--tests t]", - does: "try a pushed head before its pull request is opened", allowed: []string{"level", "trunk", "tests"}, - build: func(l line) (call, error) { - if len(l.pos) != 2 { - return call{}, usageErr("give the repository and the head") - } - a := pick(l, "level", "trunk", "tests") - a["repository"], a["head"] = l.pos[0], l.pos[1] - return call{"mesh-delivery-checker.try", a}, nil - }}, {words: []string{"builds"}, usage: "[--since ]", does: "every build that ended since (the last day by default)", allowed: []string{"since"}, build: func(l line) (call, error) { since := l.flags["since"] @@ -289,12 +270,12 @@ var commands = []command{ does: "clear one of a module's config values on one node", allowed: []string{"node", "why"}, build: func(l line) (call, error) { return configChange(l, "clear") }}, {words: []string{"config"}, usage: "[list|set|clear|history|propose|proposals] [--module m] [--node n] [--key k] [--value v] [--why w]", - does: "the mesh's config values, at any level", allowed: []string{"module", "node", "key", "value", "why", "limit", "proposal", "pull", "clear"}, + does: "the mesh's config values, at any level", allowed: []string{"module", "node", "key", "value", "why", "limit", "proposal", "clear"}, build: func(l line) (call, error) { if len(l.pos) > 1 { return call{}, usageErr("give at most one action") } - a := pick(l, "module", "node", "key", "why", "proposal", "pull", "clear", "limit") + a := pick(l, "module", "node", "key", "why", "proposal", "clear", "limit") if len(l.pos) == 1 { a["action"] = l.pos[0] } @@ -312,11 +293,7 @@ var commands = []command{ c, err := fixed("mesh-vault.secret_vault_export")(l) return warranted(c, "the vault's sealed copies"), err }}, - {words: []string{"secret", "accept"}, instead: "mesh-vault.accept takes a value from the controller alone, and no seat takes one from a person yet; a module's own secret is asked at a desk (mesh-vault.secret-ask)"}, - {words: []string{"secret", "recover"}, instead: "opening a sealed copy locally is not built yet (beside nox enrol open); nox secret export gives the sealed copies"}, - {words: []string{"secret"}, instead: "nox secret export; mesh-vault.rotate makes one anew"}, {words: []string{"operator", "key", "show"}, does: "what needs a person's eye in the vault, the operator key among it", build: fixed("mesh-vault.vault_status")}, - {words: []string{"operator"}, instead: "no seat sets or makes the operator key yet; nox operator key show reads it (mesh-vault.vault_status)"}, {words: []string{"rotate"}, usage: "[--node n --module m --name s | --provider n --provision p] --why ", does: "make a secret anew", allowed: []string{"node", "module", "name", "provider", "provision", "consumer", "consumer_module", "why"}, build: func(l line) (call, error) { @@ -374,7 +351,13 @@ var commands = []command{ }}, {words: []string{"images"}, usage: "", does: "every container image a machine's wants and haves name", build: needArg("mesh-artifact-sweep.images", "node")}, {words: []string{"mirrors"}, does: "the bases the mesh copied into its store", build: fixed("mesh-artifact-sweep.mirrors")}, - {words: []string{"licence", "list"}, does: "every licence the manager holds", build: fixed("anthropic-licence-manager.licences")}, + // The operator's overview of the licences, in one line (one-question-one-tool). + {words: []string{"licence"}, does: "every licence: kind, bound nodes, usage and its resets, token expiry, failures, conditions, target; then the bindings", + build: fixed("anthropic-licence-manager.licences"), also: licenceBindings}, + {words: []string{"licence", "list"}, does: "every licence: kind, bound nodes, usage and its resets, token expiry, failures, conditions, target; then the bindings", + build: fixed("anthropic-licence-manager.licences"), also: licenceBindings}, + {words: []string{"licence", "usage"}, usage: "[]", does: "the usage readings, the latest first, of every licence or one", + build: optArg("anthropic-licence-manager.usage", "licence"), render: renderUsage}, {words: []string{"licence", "use"}, usage: " ", does: "move a node's agent to another licence", build: func(l line) (call, error) { if len(l.pos) != 2 { @@ -384,18 +367,16 @@ var commands = []command{ }}, {words: []string{"licence", "refresh"}, usage: "[]", does: "refresh a licence now, or every due one", build: optArg("anthropic-licence-manager.refresh", "licence")}, {words: []string{"licence", "key"}, does: "the manager's public key", build: fixed("anthropic-licence-manager.public-key")}, - {words: []string{"licence"}, instead: "anthropic-licence-manager.adopt takes an API key from a file on the manager's node; nox licence list|use|refresh|key"}, {words: []string{"module", "list"}, does: "every module the indexer holds", build: fixed("mesh-delivery-view.indexer_modules")}, {words: []string{"module", "show"}, usage: "", does: "what the indexer holds of one module", build: needArg("mesh-delivery-view.indexer_module", "module")}, - {words: []string{"module", "moved"}, usage: " --why ", does: "take a registered module in now", allowed: []string{"why"}, + {words: []string{"head", "take"}, usage: " --why ", does: "take a held head in by hand (design 47 H §742, H-A-105)", allowed: []string{"why"}, build: func(l line) (call, error) { - if len(l.pos) < 1 { - return call{}, usageErr("give the module") + if len(l.pos) != 2 { + return call{}, usageErr("give the repository and the branch") } - return call{"mesh-delivery-indexer.indexer_take_in", map[string]any{"module": l.pos[0], "why": l.flags["why"]}}, nil + return call{"mesh-delivery-gate.gate_head_take", map[string]any{"repository": l.pos[0], "branch": l.pos[1], "why": l.flags["why"]}}, nil }}, - {words: []string{"module"}, instead: "the indexer takes modules in from their repositories; nox module list|show|moved, and nothing forgets one by hand yet"}, - {words: []string{"register"}, instead: "no seat registers a module from another repository yet (novox/hq ADR 0501 §4); nox module moved takes a registered one in"}, + {words: []string{"head", "list"}, does: "every untaken head the gate holds", build: fixed("mesh-delivery-gate.gate_heads")}, {words: []string{"account", "issue"}, usage: "", does: "mint one bus account the grants part wants, now", build: needArg("mesh-vault.issue-account", "user")}, // Issues and records. @@ -499,21 +480,6 @@ var commands = []command{ }}, } -// unowned are the controller's own lines that no seat or module took over, and what to use where there is anything. -var unowned = map[string]string{ - "migrate": "", "prepare": "", "serve": "", "declare": "", "broker": "", "board": "", "api": "", "facts": "", - "rehearse": "", "take": "", "converge": "", "adopt": "", "move-placement": "", "move-config": "", "durations": "", - "data": "each machine's backups: nox call /node-backup.backed-up", - "forget-checks": "nox checks ", "queue": "nox builds; nox stuck", "cancel": "nox deliveries", - "clear": "nox deliveries", "kill": "nox deliveries", "replay": "nox dead-letters", - "pause": "nox call /node-build-go.pause (or node-build-node, node-build-image)", - "resume": "nox call /node-build-go.resume (or node-build-node, node-build-image)", - "push": "a merge is delivered by mesh-delivery: nox deliveries; one version on one machine is mesh-delivery-assigner.assigner_put", - "deliver": "nox deliveries", "plans": "nox deliveries", "delivery-stop": "nox stalled", - "delivery-backups-again": "nox deliveries", "delivery-walks": "nox deliveries", "delivery-order": "nox deliveries", - "rollout": "nox upgrade ; delivery is mesh-delivery's: nox deliveries", -} - // find answers the command whose words begin the line, the longest first, and what follows them. func find(args []string) (*command, []string) { var best *command diff --git a/modules/mesh-cli/cmd/mesh-cli/console.go b/modules/mesh-cli/cmd/mesh-cli/console.go index a952784b8..f24819337 100644 --- a/modules/mesh-cli/cmd/mesh-cli/console.go +++ b/modules/mesh-cli/cmd/mesh-cli/console.go @@ -1,8 +1,7 @@ package main -// How mesh-cli reaches the mesh now that the controller is unassigned (novox/hq issue 1126): through this machine's -// console, the mesh MCP server the module node-tools serves on loopback (provision mcp-endpoint, ADR 0152: the -// machine's login is the authority). mesh-cli calls `mesh_call` with a seat verb's or a module tool's address, and the +// How mesh-cli reaches the mesh: through this machine's console, the mesh MCP server the module node-tools serves on +// loopback (provision mcp-endpoint, ADR 0152: the machine's login is the authority). mesh-cli calls `mesh_call` with a seat verb's or a module tool's address, and the // console puts the call on the bus, the way every agent session on the machine does. mesh-cli holds no credential and // keeps no bus account of its own. diff --git a/modules/mesh-cli/cmd/mesh-cli/enrol.go b/modules/mesh-cli/cmd/mesh-cli/enrol.go index b04e59a25..13d52cf4f 100644 --- a/modules/mesh-cli/cmd/mesh-cli/enrol.go +++ b/modules/mesh-cli/cmd/mesh-cli/enrol.go @@ -4,7 +4,7 @@ package main // // The seat mesh-node-enroller's `tokens` answers the token sealed to the operator key, which only the operator's private key // opens; the mesh never holds it. This subcommand is local: it asks nothing of the node-engine's socket and nothing of -// the controller or the bus. It reads the sealed token (the base64 of the sealed box) on standard input and the private +// the bus. It reads the sealed token (the base64 of the sealed box) on standard input and the private // key from a file (`--key`, the raw X25519 key in base64 that `operator key make` wrote), opens the box, and prints the // token text a joining machine's `enrol` takes. The key is read from the file named and nowhere else, and never printed. diff --git a/modules/mesh-cli/cmd/mesh-cli/licence.go b/modules/mesh-cli/cmd/mesh-cli/licence.go new file mode 100644 index 000000000..2ca125bd6 --- /dev/null +++ b/modules/mesh-cli/cmd/mesh-cli/licence.go @@ -0,0 +1,176 @@ +package main + +// The operator's overview of the licences in one line (one-question-one-tool): the licence manager's licences and +// bindings as two tables, and its usage readings as one; every time is local. + +import ( + "encoding/json" + "fmt" + "strings" + "text/tabwriter" + "time" +) + +// licenceBindings is the second call of `nox licence`: which licence each node is bound to, since when and why. +var licenceBindings = &second{address: "anthropic-licence-manager.bindings", keys: [2]string{"licences", "bindings"}, + render: renderLicences} + +// splitAnswer is the console's answer as its first JSON value and what the console said after it ("answered by ace"). +func splitAnswer(text string) (json.RawMessage, string) { + dec := json.NewDecoder(strings.NewReader(text)) + var v json.RawMessage + if err := dec.Decode(&v); err != nil { + return nil, text + } + return v, strings.TrimSpace(text[dec.InputOffset():]) +} + +// localTime is an RFC 3339 time in this machine's zone, to the minute; "-" for none, and the text itself when it is +// not one. +func localTime(s string) string { + if s == "" { + return "-" + } + t, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + return s + } + return t.Local().Format("2006-01-02 15:04") +} + +// percent is a reading with its reset when it has one; "-" for a reading the vendor did not give. +func percent(pct *float64, resets string) string { + if pct == nil { + return "-" + } + if resets == "" { + return fmt.Sprintf("%g %%", *pct) + } + return fmt.Sprintf("%g %% (resets %s)", *pct, localTime(resets)) +} + +func dashed(s string) string { + if s == "" { + return "-" + } + return s +} + +// conditionNames are a licence's open conditions as their keys; a condition that is not a key is said as given. +func conditionNames(cs []json.RawMessage) string { + names := make([]string, 0, len(cs)) + for _, c := range cs { + var s string + if json.Unmarshal(c, &s) == nil { + names = append(names, s) + continue + } + var o struct { + Key string `json:"key"` + } + if json.Unmarshal(c, &o) == nil && o.Key != "" { + names = append(names, o.Key) + continue + } + names = append(names, string(c)) + } + return dashed(strings.Join(names, " ")) +} + +// renderLicences is the licences as one table, then the bindings as another; an answer it cannot read is printed as +// given. +func renderLicences(licences, bindings string) string { + var ls []struct { + Name string `json:"name"` + Kind string `json:"kind"` + Bound []string `json:"bound"` + Usage struct { + WeeklyPct *float64 `json:"weeklyPct"` + WeeklyResetsAt string `json:"weeklyResetsAt"` + SessionPct *float64 `json:"sessionPct"` + SessionResetsAt string `json:"sessionResetsAt"` + SonnetPct *float64 `json:"sonnetPct"` + } `json:"usage"` + AccessExpiresAt string `json:"accessExpiresAt"` + Failures int `json:"failures"` + Conditions []json.RawMessage `json:"conditions"` + Target bool `json:"target"` + } + var bs []struct { + Consumer string `json:"consumer"` + Licence string `json:"licence"` + Since string `json:"since"` + Why string `json:"why"` + } + lv, lafter := splitAnswer(licences) + bv, bafter := splitAnswer(bindings) + if lv == nil || json.Unmarshal(lv, &ls) != nil || bv == nil || json.Unmarshal(bv, &bs) != nil { + return licences + "\n" + bindings + } + var b strings.Builder + w := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "LICENCE\tKIND\tBOUND\tWEEKLY\tSESSION\tSONNET\tTOKEN EXPIRES\tFAILURES\tCONDITIONS\tTARGET") + for _, l := range ls { + target := "no" + if l.Target { + target = "yes" + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n", l.Name, dashed(l.Kind), dashed(strings.Join(l.Bound, " ")), + percent(l.Usage.WeeklyPct, l.Usage.WeeklyResetsAt), percent(l.Usage.SessionPct, l.Usage.SessionResetsAt), + percent(l.Usage.SonnetPct, ""), localTime(l.AccessExpiresAt), l.Failures, conditionNames(l.Conditions), target) + } + w.Flush() + b.WriteString("\n") + w = tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "NODE\tLICENCE\tSINCE\tWHY") + for _, x := range bs { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", x.Consumer, x.Licence, localTime(x.Since), dashed(x.Why)) + } + w.Flush() + // Which machine answered each call, said once when both say the same. + for i, a := range []string{lafter, bafter} { + if a != "" && (i == 0 || a != lafter) { + b.WriteString(a + "\n") + } + } + return b.String() +} + +// renderUsage is the usage readings as one table, the latest first as the manager answers them; an answer it cannot +// read is printed as given. +func renderUsage(text string) string { + var rs []struct { + At int64 `json:"at"` + Licence string `json:"licence"` + Reading struct { + WeeklyPct *float64 `json:"weeklyPct"` + WeeklyResetsAt string `json:"weeklyResetsAt"` + SessionPct *float64 `json:"sessionPct"` + SessionResetsAt string `json:"sessionResetsAt"` + SonnetResetsAt string `json:"sonnetResetsAt"` + } `json:"reading"` + } + v, after := splitAnswer(text) + if v == nil || json.Unmarshal(v, &rs) != nil { + return text + } + var b strings.Builder + w := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "LICENCE\tREAD AT\tWEEKLY\tSESSION\tRESETS") + for _, r := range rs { + var resets []string + for _, x := range [][2]string{{"weekly", r.Reading.WeeklyResetsAt}, {"session", r.Reading.SessionResetsAt}, + {"sonnet", r.Reading.SonnetResetsAt}} { + if x[1] != "" { + resets = append(resets, x[0]+" "+localTime(x[1])) + } + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", r.Licence, time.UnixMilli(r.At).Local().Format("2006-01-02 15:04"), + percent(r.Reading.WeeklyPct, ""), percent(r.Reading.SessionPct, ""), dashed(strings.Join(resets, ", "))) + } + w.Flush() + if after != "" { + b.WriteString(after + "\n") + } + return b.String() +} diff --git a/modules/mesh-cli/cmd/mesh-cli/main.go b/modules/mesh-cli/cmd/mesh-cli/main.go index e48c3db5f..34e78cc31 100644 --- a/modules/mesh-cli/cmd/mesh-cli/main.go +++ b/modules/mesh-cli/cmd/mesh-cli/main.go @@ -1,8 +1,8 @@ // Command mesh-cli is the operator's command on every node: `mesh-cli `, in interactive zsh also `nox`. // -// Each line calls the seat verb or the module tool that owns its job (novox/hq issue 1126: the controller that ran -// these lines before is unassigned), through this machine's console, the mesh MCP server on loopback (console.go). -// A line no seat or module owns says so and names what to use instead. `enrol open` runs here and asks nothing. +// Each line calls the seat verb or the module tool that owns its job, through this machine's console, the mesh MCP +// server on loopback (console.go). A line nox does not know says so and calls nothing. `enrol open` runs here and asks +// nothing. package main import ( @@ -75,16 +75,10 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int { } c, rest := find(args) if c == nil { - if instead, ok := unowned[args[0]]; ok { - return noOwner(args[0], instead, stderr) - } fmt.Fprintf(stderr, "mesh-cli: %q is not a command. nox help lists them; nox search finds a seat verb "+ "or a tool, and nox call
calls it\n", args[0]) return 2 } - if c.build == nil { - return noOwner(strings.Join(c.words, " "), c.instead, stderr) - } k, err := c.read(rest) if err != nil { fmt.Fprintf(stderr, "mesh-cli: %v. Nothing was called\n nox %s %s\n", err, strings.Join(c.words, " "), c.usage) @@ -100,7 +94,59 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int { if k.Address == "mesh-delivery-view.view_status" { return status(ctx, stdout, stderr) } - return show(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args}, c.render, stdout, stderr) + render := c.render + l, _ := parseLine(rest) + if l.has("json") { + render = nil + } + if c.also != nil { + return showTwo(ctx, k, c.also, !l.has("json"), stdout, stderr) + } + return show(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args}, render, stdout, stderr) +} + +// showTwo calls a line's two addresses in turn and prints both answers: through the line's render, or raw as one +// object under the line's two keys. The second is not called when the first fails, and either failing is said with +// exit 1. +func showTwo(ctx context.Context, first call, also *second, rendered bool, stdout, stderr io.Writer) int { + var texts [2]string + for i, k := range []call{first, {also.address, map[string]any{}}} { + a, err := consoleTool(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args}) + if err != nil { + return failed(err, stderr) + } + if a.IsError { + fmt.Fprintln(stderr, "mesh-cli: "+k.Address+": "+strings.TrimRight(a.Text, "\n")) + return 1 + } + texts[i] = a.Text + } + if rendered { + fmt.Fprintln(stdout, strings.TrimRight(also.render(texts[0], texts[1]), "\n")) + return 0 + } + whole := map[string]json.RawMessage{} + var after []string + for i, text := range texts { + v, rest := splitAnswer(text) + if v == nil { + fmt.Fprintf(stderr, "mesh-cli: %s answered no JSON: %q\n", []string{first.Address, also.address}[i], text) + return 1 + } + whole[also.keys[i]] = v + if rest != "" && (len(after) == 0 || after[0] != rest) { + after = append(after, rest) + } + } + b, err := json.MarshalIndent(whole, "", " ") + if err != nil { + return failed(err, stderr) + } + fmt.Fprintln(stdout, string(b)) + for _, a := range after { + fmt.Fprintln(stdout, a) + } + return 0 } // recordAct records the hand act a sensitive vault verb is warranted by, through mesh-hand-acts, and answers its id; @@ -127,17 +173,6 @@ func recordAct(ctx context.Context, h handAct, stderr io.Writer) (string, int) { return rec.Act.ID, 0 } -// noOwner says a line has no owner since the controller went, and what to use. -func noOwner(what, instead string, stderr io.Writer) int { - fmt.Fprintf(stderr, "mesh-cli: nox %s: %s.\n", what, gone) - if instead != "" { - fmt.Fprintf(stderr, " instead: %s\n", instead) - } else { - fmt.Fprintln(stderr, " no seat or module does this now; nox search finds what does nearby") - } - return 1 -} - // show calls one of the console's tools and prints what it answered: an answer marked an error on standard error, with // exit 1. func show(ctx context.Context, tool string, args map[string]any, render func(string) string, stdout, stderr io.Writer) int { @@ -218,14 +253,11 @@ func usage() string { b.WriteString(`mesh-cli: the operator's command (nox in interactive zsh) Each line calls the seat verb or module tool that owns the job, through this machine's console (the mesh MCP -server on loopback). The controller that ran these lines before is unassigned (novox/hq issue 1126). +server on loopback). `) lines := make([]string, 0, len(commands)) for _, c := range commands { - if c.build == nil { - continue - } lines = append(lines, fmt.Sprintf(" nox %s %s\n %s", strings.Join(c.words, " "), c.usage, c.does)) } sort.Strings(lines) @@ -239,7 +271,7 @@ server on loopback). The controller that ran these lines before is unassigned (n open an enrolment token sealed to the operator key, here; asks nothing of the mesh nox version -Every answer is the owner's own, as JSON. A line the controller ran that no seat owns says so and what to use. +Every answer is the owner's own, as JSON, or a table where the line says so; --json prints it raw. `) return b.String() } diff --git a/modules/mesh-cli/cmd/mesh-cli/main_test.go b/modules/mesh-cli/cmd/mesh-cli/main_test.go index 2fca7dfd5..7984172ea 100644 --- a/modules/mesh-cli/cmd/mesh-cli/main_test.go +++ b/modules/mesh-cli/cmd/mesh-cli/main_test.go @@ -77,8 +77,8 @@ func runLine(args ...string) (int, string, string) { return code, out.String(), errOut.String() } -// Every owned line calls the seat verb or module tool that owns its job, with the arguments the owner reads -// (novox/hq issue 1126; hq .work/1126/nox-map.md), and prints its answer. +// Every line calls the seat verb or module tool that owns its job, with the arguments the owner reads, and prints its +// answer. func TestEachLineCallsItsOwner(t *testing.T) { now = func() time.Time { return time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC) } t.Cleanup(func() { now = time.Now }) @@ -88,6 +88,8 @@ func TestEachLineCallsItsOwner(t *testing.T) { args string }{ {"node show ace", "mesh-module-assigner.assignments", `{"node":"ace"}`}, + {"head take novox/x main --why moved", "mesh-delivery-gate.gate_head_take", `{"branch":"main","repository":"novox/x","why":"moved"}`}, + {"head list", "mesh-delivery-gate.gate_heads", `{}`}, {"node public-domain ace", "mesh-module-assigner.assignments", `{"node":"ace"}`}, {"node public-domain ace example.org --why moved", "mesh-module-assigner.propose", `{"changes":[{"field":"public-domain","node":"ace","op":"decide","value":"example.org"}],"why":"moved"}`}, {"plan ace", "mesh-delivery-view.assigner_wants", `{"node":"ace"}`}, @@ -100,8 +102,6 @@ func TestEachLineCallsItsOwner(t *testing.T) { {"unpin ace postgres-database --why back", "mesh-module-assigner.propose", `{"changes":[{"node":"ace","op":"unpin","provision":"postgres-database"}],"why":"back"}`}, {"deliveries --state merged --json", "mesh-delivery.deliveries", `{"state":"merged"}`}, {"delivery novox/mesh-sdk@dff0ce2abb21", "mesh-delivery.show", `{"id":"novox/mesh-sdk@dff0ce2abb21"}`}, - {"checks novox/mesh-catalog --number 591", "mesh-delivery.checks", `{"number":"591","repository":"novox/mesh-catalog"}`}, - {"try novox/mesh-catalog abc123 --level unit", "mesh-delivery-checker.try", `{"head":"abc123","level":"unit","repository":"novox/mesh-catalog"}`}, {"builds", "mesh-delivery-builder.builder_builds_since", `{"since":"2026-11-01T10:00:00Z"}`}, {"upgrade nats --policy record --why bus", "mesh-wants.upgrade", `{"module":"nats","policy":"record","why":"bus"}`}, {"bus", "mesh-wants.bus", `{}`}, @@ -121,14 +121,14 @@ func TestEachLineCallsItsOwner(t *testing.T) { {"settings clear zsh execute --node g14 --why test", "mesh-config.config", `{"action":"clear","key":"execute","module":"zsh","node":"g14","why":"test"}`}, {"config history --key k --limit 5", "mesh-config.config", `{"action":"history","key":"k","limit":5}`}, {"operator key show", "mesh-vault.vault_status", `{}`}, - // A cleanup without --confirm deletes nothing, so no hand act is recorded for it (issue 1126 review 2). + // A cleanup without --confirm deletes nothing, so no hand act is recorded for it. {"cleanup delete ace.plex --why dry", "mesh-vault.provisioner_delete", `{"consumer":"ace.plex","why":"dry"}`}, {"collect --confirm --why space", "mesh-artifact-sweep.collect", `{"confirm":"true","why":"space"}`}, {"images ace", "mesh-artifact-sweep.images", `{"node":"ace"}`}, {"licence use g14 work", "anthropic-licence-manager.switch", `{"consumer":"g14","licence":"work"}`}, {"module show plex", "mesh-delivery-view.indexer_module", `{"module":"plex"}`}, {"issues apostrophe bug --status open --limit 5", "issue-tracker.list", `{"limit":5,"search":"apostrophe bug","status":"open"}`}, - {"issue 1126 --brief", "issue-tracker.get", `{"brief":true,"number":1126}`}, + {"issue 294 --brief", "issue-tracker.get", `{"brief":true,"number":294}`}, {"kb ask what holds about the merge window", "knowledge-base.ask", `{"question":"what holds about the merge window"}`}, {"kb get 587 --reasoning", "knowledge-base.get", `{"number":587,"reasoning":true}`}, {"progress 47", "knowledge-base.progress", `{"of":"design 47"}`}, @@ -154,37 +154,43 @@ func TestEachLineCallsItsOwner(t *testing.T) { } } -// A line the controller ran that no seat owns says so and what to use, exits 1 and calls nothing; a line nox cannot -// read says how it is written, exits 2 and calls nothing. -func TestALineWithNoOwnerOrNotReadCallsNothingAndSaysWhy(t *testing.T) { +// 1126/AC4: a line nox cannot read says how it is written, exits 2 and calls nothing; the controller's retired lines are gone with +// it, not mapped to a refusal (the operator, 2026-11-22: "why are there still references to the controller?"), and +// nothing nox says names the controller. +func TestALineNotReadCallsNothingAndSaysWhy(t *testing.T) { for _, c := range []struct { line string - code int err string }{ - {"push ace", 1, "mesh-delivery-assigner.assigner_put"}, - {"migrate", 1, "no seat or module does this now"}, - {"secret accept ace plex token", 1, "mesh-vault.secret-ask"}, - {"node add new1", 1, "nox enrol issue"}, - {"pause", 1, "node-build-go.pause"}, - {"operator key make", 1, "operator key show"}, - {"assign ace plex", 2, "needs --why"}, - {"issue twelve", 2, "not an issue's number"}, - {"conditions --bogus x", 2, "--bogus is not a flag"}, - {"settings set zsh {\"execute\":\"withhold\"} --node g14 --why x", 2, "set each key"}, - {"healers --days soon", 2, "takes a number"}, - {"frobnicate", 2, "is not a command"}, + {"push ace", "is not a command"}, + {"migrate", "is not a command"}, + {"secret accept ace plex token", "is not a command"}, + {"node add new1", "is not a command"}, + {"pause", "is not a command"}, + {"operator key make", "is not a command"}, + {"module forget plex", "is not a command"}, + {"assign ace plex", "needs --why"}, + {"issue twelve", "not an issue's number"}, + {"conditions --bogus x", "--bogus is not a flag"}, + {"settings set zsh {\"execute\":\"withhold\"} --node g14 --why x", "set each key"}, + {"healers --days soon", "takes a number"}, + {"config propose --pull novox/x#1", "--pull is not a flag"}, + {"frobnicate", "is not a command"}, + // The checker and the groups go whole (design 47 H §764): nox calls neither. + {"try novox/mesh-catalog abc123 --level unit", "is not a command"}, + {"groups", "is not a command"}, + {"checks novox/mesh-catalog --number 591", "is not a command"}, } { got := console(t, nil) args := strings.Fields(c.line) code, _, errOut := runLine(args...) - if code != c.code || len(*got) != 0 || !strings.Contains(errOut, c.err) { - t.Errorf("nox %s: exit %d, asked %+v, stderr %q; want exit %d saying %q", c.line, code, *got, errOut, c.code, c.err) - } - if c.code == 1 && !strings.Contains(errOut, "issue 1126") { - t.Errorf("nox %s does not say the controller is unassigned: %q", c.line, errOut) + if code != 2 || len(*got) != 0 || !strings.Contains(errOut, c.err) || strings.Contains(errOut, "controller") { + t.Errorf("nox %s: exit %d, asked %+v, stderr %q; want exit 2 saying %q", c.line, code, *got, errOut, c.err) } } + if strings.Contains(usage(), "controller") { + t.Errorf("the help still names the controller:\n%s", usage()) + } } // What the console says is printed as said: an answer it marks an error on standard error with exit 1, a console that @@ -274,16 +280,13 @@ func TestEveryLineIsInTheHelpOnce(t *testing.T) { if c.build != nil && !strings.Contains(help, "nox "+w+" ") { t.Errorf("nox %s is not in the help", w) } - if c.build == nil && c.instead == "" { - t.Errorf("nox %s has neither an owner nor an instead", w) - } - if _, dup := unowned[c.words[0]]; dup && len(c.words) == 1 { - t.Errorf("nox %s is both owned and unowned", w) + if c.build == nil { + t.Errorf("nox %s has no owner", w) } } } -// ADR 0590 §8 (issue 1126 review 1): each sensitive vault verb judges its own caller, and nox reaches the vault as its +// ADR 0590 §8: each sensitive vault verb judges its own caller, and nox reaches the vault as its // machine's runtime, so nox first records the hand act that warrants the line through mesh-hand-acts (the vault verb as // its verb, what it acts on as its what) and names it as `act`; a recording refused calls the vault not at all. func TestASensitiveLineRecordsItsHandActAndNamesIt(t *testing.T) { @@ -317,3 +320,82 @@ func TestASensitiveLineRecordsItsHandActAndNamesIt(t *testing.T) { t.Errorf("a refused recording: exit %d, asked %+v, %q", code, *got, errOut) } } + +// 1126/AC1, 1126/AC2, 1126/AC3: the operator's overview of the licences is one line (one-question-one-tool): `nox licence` and +// `nox licence list` call the licence manager's licences and bindings and print one table of each, every time local; +// `nox licence usage` prints the readings; --json prints the raw answers, the two as one object. +func TestTheLicencesAreOneTable(t *testing.T) { + local := time.Local + time.Local = time.FixedZone("CET", 3600) + t.Cleanup(func() { time.Local = local }) + licences := `[{"name":"work","account":"a@example.org","kind":"subscription","bound":["ace","novox"], + "usage":{"readAt":"2026-11-22T19:32:27Z","weeklyPct":2,"weeklyResetsAt":"2026-11-25T01:59:59.5+00:00", + "sessionPct":7,"sessionResetsAt":"2026-11-23T00:29:59+00:00","sonnetPct":null}, + "accessExpiresAt":"2026-11-23T01:56:57Z","refreshExpiresAt":"2026-12-14T01:48:16Z","room":98, + "failures":0,"conditions":[],"target":true}, + {"name":"home","account":"b@example.org","kind":"subscription","bound":[], + "usage":{"weeklyPct":99,"weeklyResetsAt":"2026-11-25T10:59:59+00:00","sessionPct":null,"sonnetPct":40}, + "accessExpiresAt":"2026-11-23T02:02:57Z","failures":2,"conditions":["licence.home.full"],"target":false}]` + bindings := `[{"consumer":"g14","licence":"home","kind":"subscription","generation":3,"since":"2026-11-22T19:32:28Z", + "why":"work reached 99 % of its weekly window","by":"usage"}]` + usage := `[{"at":1795376250078,"licence":"work","reading":{"weeklyPct":4,"weeklyResetsAt":"2026-11-29T17:59:59+00:00", + "sessionPct":null,"sonnetPct":null}}]` + answers := map[string]string{"anthropic-licence-manager.licences": licences, + "anthropic-licence-manager.bindings": bindings, "anthropic-licence-manager.usage": usage} + for _, words := range []string{"licence", "licence list"} { + got := console(t, answers) + code, out, errOut := runLine(strings.Fields(words)...) + if code != 0 || errOut != "" || len(*got) != 2 || (*got)[0].Address != "anthropic-licence-manager.licences" || + (*got)[1].Address != "anthropic-licence-manager.bindings" || (*got)[1].Args != `{}` { + t.Fatalf("nox %s: exit %d, stderr %q, asked %+v", words, code, errOut, *got) + } + for _, want := range []string{ + "LICENCE", "KIND", "BOUND", "WEEKLY", "SESSION", "SONNET", "TOKEN EXPIRES", "FAILURES", "CONDITIONS", "TARGET", + "work", "ace novox", "2 % (resets 2026-11-25 02:59)", "7 % (resets 2026-11-23 01:29)", "2026-11-23 02:56", "yes", + "home", "99 % (resets 2026-11-25 11:59)", "40 %", "licence.home.full", + "NODE", "SINCE", "WHY", "g14", "2026-11-22 20:32", "work reached 99 % of its weekly window", + } { + if !strings.Contains(out, want) { + t.Errorf("nox %s does not print %q:\n%s", words, want, out) + } + } + if strings.Contains(out, "2026-12-14") || strings.Contains(out, "98") { + t.Errorf("nox %s prints the refresh-token expiry or the room:\n%s", words, out) + } + } + + // 1126/AC3: --json prints the raw answers, the two calls' as one object. + console(t, answers) + code, out, _ := runLine("licence", "--json") + var raw struct { + Licences []map[string]any `json:"licences"` + Bindings []map[string]any `json:"bindings"` + } + if err := json.Unmarshal([]byte(strings.SplitN(out, "\nanswered by", 2)[0]), &raw); code != 0 || err != nil || + len(raw.Licences) != 2 || len(raw.Bindings) != 1 { + t.Errorf("nox licence --json: exit %d, %v:\n%s", code, err, out) + } + + // 1126/AC3: on every rendered line, as on the nodes. + nodes := `{"keys":{"ace":{"assignments":{"decided":{"address":"10.0.0.1"},"modules":[]}}}}` + console(t, map[string]string{"mesh-module-assigner.assignments": nodes}) + if code, out, _ := runLine("nodes", "--json"); code != 0 || !strings.HasPrefix(out, nodes) { + t.Errorf("nox nodes --json: exit %d, does not print the raw answer:\n%s", code, out) + } + + // 1126/AC2: the usage readings as one table. + got := console(t, answers) + code, out, errOut := runLine("licence", "usage", "work") + if code != 0 || len(*got) != 1 || (*got)[0].Address != "anthropic-licence-manager.usage" || (*got)[0].Args != `{"licence":"work"}` { + t.Fatalf("nox licence usage work: exit %d, stderr %q, asked %+v", code, errOut, *got) + } + for _, want := range []string{"LICENCE", "READ AT", "WEEKLY", "SESSION", "RESETS", "work", + time.UnixMilli(1795376250078).Local().Format("2006-01-02 15:04"), "4 %", "weekly 2026-11-29 18:59"} { + if !strings.Contains(out, want) { + t.Errorf("nox licence usage does not print %q:\n%s", want, out) + } + } + if code, _, _ := runLine("licence", "usage", "--limit", "5"); code != 2 { + t.Errorf("nox licence usage --limit is read (exit %d); it takes no limit", code) + } +} diff --git a/modules/mesh-cli/cmd/mesh-cli/manifest_test.go b/modules/mesh-cli/cmd/mesh-cli/manifest_test.go index c411eab7d..9e42e6d51 100644 --- a/modules/mesh-cli/cmd/mesh-cli/manifest_test.go +++ b/modules/mesh-cli/cmd/mesh-cli/manifest_test.go @@ -24,8 +24,8 @@ func TestTheArchivePlacesExactlyOneFileAndTheConsolesAddressOne(t *testing.T) { if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } - // Beside the program, one directory and one file: the console's address, from the mcp-endpoint it requires - // (novox/hq issue 1126). Nothing else. + // Beside the program, one directory and one file: the console's address, from the mcp-endpoint it requires. + // Nothing else. var r map[string]any for _, res := range m.Resources { switch { @@ -43,7 +43,7 @@ func TestTheArchivePlacesExactlyOneFileAndTheConsolesAddressOne(t *testing.T) { if len(m.Resources) != 3 || r == nil || r["path"] != "/usr/local/bin" { t.Fatalf("its resources are %v", m.Resources) } - // The build has a second artifact, the files archive the controller reads the templates back from; it + // The build has a second artifact, the files archive the templates are read back from; it // places no file. The artifact the resource unpacks is the one that does. var a map[string]any for _, candidate := range m.Build.Artifacts { diff --git a/modules/mesh-cli/module.json b/modules/mesh-cli/module.json index d07f47d85..86325ec23 100644 --- a/modules/mesh-cli/module.json +++ b/modules/mesh-cli/module.json @@ -1,6 +1,7 @@ { "module": "mesh-cli", "version": "0.1", + "class": "leaf", "moved": true, "requires": [ "mcp-endpoint" diff --git a/modules/mesh-conditions/cmd/mesh-conditions/hold.go b/modules/mesh-conditions/cmd/mesh-conditions/hold.go index cbf90c8e5..9b99add42 100644 --- a/modules/mesh-conditions/cmd/mesh-conditions/hold.go +++ b/modules/mesh-conditions/cmd/mesh-conditions/hold.go @@ -321,5 +321,5 @@ func decodeWant(value []byte) (motion.Want, error) { if err := json.Unmarshal(value, &w); err != nil { return motion.Want{}, err } - return motion.Want{FP: w.Fp, Composed: w.Composed, Removed: w.Removed}, nil + return motion.Want{FP: w.Fp, Removed: w.Removed}, nil } diff --git a/modules/mesh-conditions/cmd/mesh-conditions/hold_test.go b/modules/mesh-conditions/cmd/mesh-conditions/hold_test.go index 6850411c6..34c17cc39 100644 --- a/modules/mesh-conditions/cmd/mesh-conditions/hold_test.go +++ b/modules/mesh-conditions/cmd/mesh-conditions/hold_test.go @@ -34,8 +34,9 @@ const ( // failed delivery raises what stands at once; another module's and the machine's own are raised at once; compare lists a // held key as held. func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) { - want := func(fp, composed string) []byte { - raw, _ := json.Marshal(meshwants.WantsByWantNodeModuleValue{V: 1, Fp: fp, Composed: composed}) + // A want names the fingerprint alone (design 47 H, H-A-78): a have at it is the want applied. + want := func(fp string) []byte { + raw, _ := json.Marshal(meshwants.WantsByWantNodeModuleValue{V: 1, Fp: fp}) return raw } have := func(fp, composed string, phase, h string) haveSpec { return haveSpec{fp, composed, phase, h} } @@ -55,10 +56,10 @@ func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) { said: "raised module.mesh-controller.novox.unhealthy", line: "as the delivery of version 0d1e2f3a4b5c"}, } { r := newRig() - _ = r.k.Want("want.novox.mesh-controller", want(ctrlRunning, ctrlComposed), false) + _ = r.k.Want("want.novox.mesh-controller", want(ctrlRunning), false) r.engineHave("novox.mesh-controller", have(ctrlRunning, ctrlComposed, motion.PhaseRunning, engineclient.HealthOK)) // The delivery starts: the assigner wants the next fingerprint; the node applies it. - _ = r.k.Want("want.novox.mesh-controller", want(ctrlNext, ctrlNextComp), false) + _ = r.k.Want("want.novox.mesh-controller", want(ctrlNext), false) r.engineHave("novox.mesh-controller", have(ctrlNext, ctrlNextComp, motion.PhaseApplying, engineclient.HealthUnknown)) own, ownRaw := finding(t, watchman, cc.ScopeModule, "mesh-controller.novox", "unhealthy", "health", cc.Warning, r.now) other, otherRaw := finding(t, watchman, cc.ScopeModule, "postgres.novox", "unhealthy", "health", cc.Warning, r.now) @@ -109,7 +110,7 @@ func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) { } r.k.Assignments("ace.mesh-delivery-assigner", placed["ace.mesh-delivery-assigner"], false) r.k.Assignments("ace.node", placed["ace.node"], false) - _ = r.k.Want("want.ace.mesh-delivery-assigner", want(ctrlNext, ctrlNextComp), false) + _ = r.k.Want("want.ace.mesh-delivery-assigner", want(ctrlNext), false) r.engineHave("ace.mesh-delivery-assigner", have(ctrlRunning, ctrlComposed, motion.PhaseRunning, engineclient.HealthOK)) seatKey, seatRaw := finding(t, selfCheck, cc.ScopeSeat, "mesh-module-assigner.ace", "holder-silent", "D3", cc.Warning, r.now) _ = r.k.Finding(selfCheck, seatKey, seatRaw, false) diff --git a/modules/mesh-conditions/cmd/mesh-conditions/homes.go b/modules/mesh-conditions/cmd/mesh-conditions/homes.go index dad8d9eb5..6b6e11030 100644 --- a/modules/mesh-conditions/cmd/mesh-conditions/homes.go +++ b/modules/mesh-conditions/cmd/mesh-conditions/homes.go @@ -108,10 +108,9 @@ var Homes = map[string]Home{ // An owner's change not said on its views family past its bound (mesh-sdk views.UnsaidFinding, id .): // written by each owner of a views family in its own findings (the indexer, the assigner), so no one observer. "view-unsaid": {Source: "views", Why: "every owner of a views family writes its own"}, - // The builder's own (design 51): a build that ended failed, a floor whose holder said nothing past its bound, an old - // form held seven days by a counted node-engine, a tag's removal asked and not done. + // The builder's own (design 51): a build that ended failed, an old form held seven days by a counted node-engine, a tag's + // removal asked and not done. Its floor-silent went with its version floor (design 47 H2 H-A-553 (2)). "build-failed": {Source: "builder", Observer: builder}, - "floor-silent": {Source: "builder", Observer: builder}, "old-form-held": {Source: "builder", Observer: builder}, "tag-removal-not-done": {Source: "builder", Observer: builder}, // The builder's publishing (design 51): a holder refused the publish, or said nothing past its bound (about the name); diff --git a/modules/mesh-conditions/cmd/mesh-conditions/keeper_test.go b/modules/mesh-conditions/cmd/mesh-conditions/keeper_test.go index d6331c34e..71817fed3 100644 --- a/modules/mesh-conditions/cmd/mesh-conditions/keeper_test.go +++ b/modules/mesh-conditions/cmd/mesh-conditions/keeper_test.go @@ -156,7 +156,7 @@ func (r *rig) open(key string) (Condition, bool) { var c Condition if ok { // The seat's layout, read strictly: a field the seat does not name is a fault of the keeper's write. - v, err := seat.DecodeConditionsByKeyValue(raw) + v, _, err := seat.DecodeConditionsByKeyValue(raw) if err != nil { panic(fmt.Sprintf("the condition %s is not the seat's layout: %v: %s", key, err, raw)) } @@ -366,7 +366,7 @@ func TestEveryControllerKindHasItsHome(t *testing.T) { } for kind, observer := range map[string]string{"needs-operator": watchman, "machine-network": watchman, "lease-split": selfCheck, "data-shrank": selfCheck, "retire-waiting": provisioner, "asks-undelivered": messenger, - "image-missing": artifactStore, "build-failed": builder, "floor-silent": builder, "old-form-held": builder, + "image-missing": artifactStore, "build-failed": builder, "old-form-held": builder, "tag-removal-not-done": builder, "seat-definition-unparsed": indexer, "generated-types-out-of-step": indexer, "seat-defined-twice": indexer, "accepted-unsaid": indexer, "manifest-held": indexer, "packages-token-refused": gitea, "publish-refused": builder, "publish-unanswered": builder, "seat-outcome-unread": builder} { @@ -374,6 +374,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) { t.Errorf("%s's home is %+v", kind, h) } } + // Design 47 H2 H-A-553 (2): the builder's floor-silent went with its version floor, so no home names it. + if h, ok := Homes["floor-silent"]; ok { + t.Errorf("floor-silent still has a home: %+v", h) + } for _, kind := range []string{"resolver-wrong", "holder-silent", "archives-missing", "archives-unheld", "binding-kept", "binding-moved", "binding-moving", "grant-composes-nothing", "root-not-free", "cleanup-waiting", "data-held-twice"} { if h := Homes[kind]; !h.Carried || h.Observer != "" || h.Why != Dropped { @@ -397,9 +401,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) { // first view, the owners' view too large, the builder's four, the indexer's four and the package seats' token refused. // And the builder's three publishing kinds and the delivery parts' family not heard: 103. // And the owners' changes not said, view-unsaid: 104. And the indexer's mesh-wide hold past its bound, manifest-held - // (ADR 0632 §2): 105. (The bus module's own conditions, nats.status-unwritten among them, are said to the keeper - // directly, never through findings, so they have no home here.) - if len(Homes) != 105 || carried != 37 { + // (ADR 0632 §2): 105. Less the builder's floor-silent, gone with its floor (design 47 H2 H-A-553 (2)): 104. (The bus + // module's own conditions, nats.status-unwritten among them, are said to the keeper directly, never through findings, so + // they have no home here.) + if len(Homes) != 104 || carried != 37 { t.Errorf("the table holds %d kinds, %d carried", len(Homes), carried) } } diff --git a/modules/mesh-conditions/module.json b/modules/mesh-conditions/module.json index f8b9ca440..4bfcc3fe1 100644 --- a/modules/mesh-conditions/module.json +++ b/modules/mesh-conditions/module.json @@ -1,6 +1,7 @@ { "module": "mesh-conditions", "version": "0.1", + "class": "core", "runs-as": "mesh-conditions", "claims": [ { diff --git a/modules/mesh-config/README.md b/modules/mesh-config/README.md index 99f368a43..5e5e3dd22 100644 --- a/modules/mesh-config/README.md +++ b/modules/mesh-config/README.md @@ -30,7 +30,7 @@ module none of whose manifests can be read is listed under `unresolved` with why values last resolved for it. Then: the manifest's default; mesh config for the predefined key the value falls back to; node config for that key on the node; the module's own value on that node, the most specific winning. A value naming no predefined key resolves from its default and the module's own value only (ADR 0348 §2). It resolves at -start, whenever an assignment, a want or a trunk module moves, and every five minutes, writing only the values that moved. +start, whenever an assignment, a want or a trunk module moves, writing only the values that moved. ## The verb @@ -87,8 +87,9 @@ Each directory or archive this module declares says how it treats a file it did - `mesh-config_declared`: each placed module's declarations at the trunk, with the manifest and commit they come from, written only when they differ. - Its own sources hold always (novox/hq ADR 0590): declarations from the modules' own manifests, the list from the - indexer's `predefined`, pull requests' config from the indexer's `config-candidates`. The controller's - `pull-declares`, the take-over, compare and hand-back went with the controller. `config_declared` and + indexer's `predefined`. The controller's `pull-declares`, the take-over, compare and hand-back went with the + controller, and so did every pull request path (`pulls`, `kept`, `held`, a proposal's `pull`): the mesh knows no pull + request (design 47 G, ADR 0502 ended by the operator's word, record pending). `config_declared` and `config_resync` read and write again what it keeps. - A trusted value is set only through propose and the operator's Approve: no controller relay is trusted (issue 1126). - Its sets, clears and warrants are recorded in the hand-act log of the seat `mesh-hand-acts` alone. diff --git a/modules/mesh-config/cmd/mesh-config/config.go b/modules/mesh-config/cmd/mesh-config/config.go index e50109780..84542fd7a 100644 --- a/modules/mesh-config/cmd/mesh-config/config.go +++ b/modules/mesh-config/cmd/mesh-config/config.go @@ -73,10 +73,6 @@ type Change struct { Approved string `json:"approved,omitempty"` At time.Time `json:"at"` Moved []Moved `json:"moved"` - // Pull and Head name the pull request a value is held for, dropped from, or applied from at its merge (novox/hq - // ADR 0502): the actions hold and drop are always about one, and a set with a pull is its merge. - Pull string `json:"pull,omitempty"` - Head string `json:"head,omitempty"` } // Config is the module: its store, its clock, and one lock, so a set and a resolution never interleave. @@ -94,8 +90,6 @@ type Config struct { // Asks is the operator channel as this module asks on it (proposals.go); nil, nothing can be proposed. Asks AskBus - // Forge is the forge as pulls are asked of it (pulls.go); nil, a merge or a close is heard from its events alone. - Forge PullForge // Delivery is what the delivery parts answer (renames.go, retiring.go); nil, no window closes and nothing retires. Delivery Delivery // Catalog is the catalog half: which modules exist and the manifest each entry carries, and the entry of a build's @@ -130,13 +124,6 @@ type Call struct { // Clear asks a proposal to clear the value instead of setting it; Proposal names one proposal to read. Clear bool Proposal string - // Pull names the open pull request that introduces the key, for propose (a held value) and pull-declares; Head is - // the commit its declarations are read at; Declares the config declarations the head adds or changes, by module; - // Pulls the pull requests held asks about, each at a head. - Pull string - Head string - Declares map[string]any - Pulls []PullAt // approval is the operator's warrant a set or a clear is made on: given by a decided proposal alone, never by // a call's arguments. @@ -177,13 +164,8 @@ func (c *Config) Do(call Call) (any, error) { return c.Propose(call) case "proposals": return c.Proposals(call) - case "pull-declares": - return c.PullDeclares(call) - case "held": - return c.Held(call) } - return nil, fmt.Errorf("config does set, clear, list, history, propose, proposals, pull-declares or held; %q is "+ - "none of them", call.Action) + return nil, fmt.Errorf("config does set, clear, list, history, propose or proposals; %q is none of them", call.Action) } // level is the level a call names, refused as ADR 0348 §3 says: a module's own value is for one node. @@ -211,10 +193,6 @@ func (c *Config) Change(call Call) (*SetAnswer, error) { if call.Clear || call.Proposal != "" { return nil, fmt.Errorf("clear and proposal are a proposal's: %s takes neither", call.Action) } - if call.Pull != "" { - return nil, fmt.Errorf("pull names the pull request a value is held for, which only a proposal does: %s takes "+ - "none", call.Action) - } call.approval = nil // only a decided proposal gives one c.mu.Lock() defer c.mu.Unlock() diff --git a/modules/mesh-config/cmd/mesh-config/delivery.go b/modules/mesh-config/cmd/mesh-config/delivery.go index 2ab1babe1..8490cad49 100644 --- a/modules/mesh-config/cmd/mesh-config/delivery.go +++ b/modules/mesh-config/cmd/mesh-config/delivery.go @@ -131,3 +131,37 @@ func (v toolVault) Retire(r RetireRequest) error { _, err = v.ask(VaultRetireAsk, map[string]any{"node": r.Node, "module": r.Module, "name": r.Name, "warrant": rec.Act.ID, "ask": r.Ask}) return err } + +// unwrapAnswer reads a tool's answer whatever wraps it: the protocol's content list, or {output, ok, answer}. +func unwrapAnswer(raw json.RawMessage) (json.RawMessage, string, bool) { + var s string + if json.Unmarshal(raw, &s) == nil { + return unwrapAnswer(json.RawMessage(s)) + } + var m map[string]json.RawMessage + if json.Unmarshal(raw, &m) != nil { + return raw, string(raw), true + } + if content, has := m["content"]; has { + var items []struct { + Text string `json:"text"` + } + var e struct { + IsError bool `json:"isError"` + } + _ = json.Unmarshal(raw, &e) + if json.Unmarshal(content, &items) == nil && len(items) > 0 { + inner, out, ok := unwrapAnswer(json.RawMessage(items[0].Text)) + return inner, out, ok && !e.IsError + } + } + var v struct { + Output string `json:"output"` + OK *bool `json:"ok"` + Answer json.RawMessage `json:"answer"` + } + if json.Unmarshal(raw, &v) == nil && v.OK != nil { + return v.Answer, v.Output, *v.OK + } + return raw, string(raw), true +} diff --git a/modules/mesh-config/cmd/mesh-config/list.go b/modules/mesh-config/cmd/mesh-config/list.go index 099bafaf9..4aa8912c4 100644 --- a/modules/mesh-config/cmd/mesh-config/list.go +++ b/modules/mesh-config/cmd/mesh-config/list.go @@ -19,8 +19,6 @@ type Listed struct { Withheld string `json:"withheld,omitempty"` // Unresolved is each placed module the call narrows to whose declarations cannot be read, with why (issue 1953). Unresolved []Unresolved `json:"unresolved,omitempty"` - // Held is the approved values held for open pull requests, not yet set (novox/hq ADR 0502). - Held []HeldValue `json:"held,omitempty"` } // SetValue is one value set, at its level. @@ -95,10 +93,6 @@ func (c *Config) List(call Call) (*Listed, error) { if call.Module == "" { out.Predefined = s.Predefined } - out.Held = heldListed(s, call) - if len(out.Held) == 0 { - out.Held = nil - } return out, nil } diff --git a/modules/mesh-config/cmd/mesh-config/main.go b/modules/mesh-config/cmd/mesh-config/main.go index 09f0b32dd..383708344 100644 --- a/modules/mesh-config/cmd/mesh-config/main.go +++ b/modules/mesh-config/cmd/mesh-config/main.go @@ -38,15 +38,19 @@ func logf(format string, a ...any) { fmt.Fprintf(os.Stderr, format+"\n", a...) } var theViews *ownerViews // runtimeStore is the bus, through the runtime that launched this bundle. A state of the delivery owners that the -// owners' tools answer is read from the picture those keep (ownerviews.go), the rest from the bus. -type runtimeStore struct{} +// owners' tools answer is read from the picture those keep (ownerviews.go), this module's own states from the copy their +// watches keep (ownstates.go), the rest from the bus. +type runtimeStore struct{ own *ownCopy } -func (runtimeStore) Get(state, key string) (*Entry, error) { +func (r runtimeStore) Get(state, key string) (*Entry, error) { if theViews != nil { if e, followed, err := theViews.get(state, key); followed { return e, err } } + if r.own != nil && ownStates[state] { + return r.own.get(state, key) + } e, err := stdio.State(state).Get(key) if err != nil || e == nil { return nil, err @@ -54,19 +58,30 @@ func (runtimeStore) Get(state, key string) (*Entry, error) { return &Entry{Key: e.Key, Value: e.Value, Revision: e.Revision}, nil } -func (runtimeStore) Put(state, key string, value any) error { +func (r runtimeStore) Put(state, key string, value any) error { + if r.own != nil && ownStates[state] { + return r.own.write(state, key, value) + } _, err := stdio.State(state).Put(key, value) return err } -func (runtimeStore) Delete(state, key string) error { return stdio.State(state).Delete(key) } +func (r runtimeStore) Delete(state, key string) error { + if r.own != nil && ownStates[state] { + return r.own.remove(state, key) + } + return stdio.State(state).Delete(key) +} -func (runtimeStore) Keys(state string) ([]string, error) { +func (r runtimeStore) Keys(state string) ([]string, error) { if theViews != nil { if keys, followed, err := theViews.keys(state); followed { return keys, err } } + if r.own != nil && ownStates[state] { + return r.own.keys(state) + } return stdio.State(state).Keys() } @@ -119,8 +134,22 @@ func (runtimeAsks) Warranted(ask string) error { return err } +// armsDeadline says a write to this state can move the deadline timer: a proposal, a retirement or a rename window (A-490l). +func armsDeadline(state string) bool { + return state == ProposalsState || state == RetiringState || state == RenamesState +} + func main() { - c := &Config{Store: runtimeStore{}, Logf: logf, Asks: runtimeAsks{}, Forge: toolForge{ask: stdio.Ask}, + own, rearm := newOwnCopy(), make(chan struct{}, 1) + own.changed = func(state string) { + if armsDeadline(state) { + select { + case rearm <- struct{}{}: + default: + } + } + } + c := &Config{Store: runtimeStore{own: own}, Logf: logf, Asks: runtimeAsks{}, Delivery: toolDelivery{ask: stdio.Ask}, Vault: toolVault{ask: stdio.Ask, recorder: recorder}} // The module's one held writer (design 47 G §689, A-16, A-29, A-32): the renames' and retirements' findings and the views reader's go through it. w, err := views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ @@ -181,6 +210,7 @@ func main() { theViews.Start(context.Background()) go resolving(c, moved) go hearing(c) + go deciding(c, rearm) go hearingDelivery(c) if err := stdio.Serve("", append(Tools(c), branches.EntryAgainTool("config", c.Store.HandAct))); err != nil { logf("%v", err) @@ -188,23 +218,12 @@ func main() { } } -// resolving resolves at start and again whenever a source moves, and every five minutes besides, so a change -// heard nowhere is still resolved. The runtime answers only once Serve runs, so the watches are asked again -// until they are taken. +// resolving resolves at start and again whenever a source moves: an assignment, a want, a catalog revision, an entry +// answered or the predefined list (each reaches `moved` through its view, ownerviews.go and main), and never on a timer +// (novox/hq principle 1, issue 1982). The runtime answers only once Serve runs. func resolving(c *Config, moved chan struct{}) { - // The owners' states reach `moved` through their views (ownerviews.go); the builder's builds, which has no tool yet, - // is read when a want moves, and nothing else is watched. - tick := time.NewTicker(5 * time.Minute) - defer tick.Stop() - time.Sleep(time.Second) - for sweep := true; ; { - if sweep { - // A merge or a close of a pull request a value is held for, heard nowhere, is found here (ADR 0502). - for _, s := range c.SweepPulls() { - logf("[mesh-config] %s", s) - } - } - sweep = false + <-stdio.Served() + for { r, err := c.Reconcile() switch { case err != nil: @@ -215,21 +234,22 @@ func resolving(c *Config, moved chan struct{}) { if r.Published != "" { logf("[mesh-config] published %s", r.Published) } + // A window or a retirement judged while the entry of the build it waits on was still asked stays open until the + // entry answers: the answer moves this pass, and the open ones are judged again here (design 32 *A config value + // renamed*). It reads nothing from the bus when none is open. + for _, s := range c.Windows("") { + logf("[mesh-config] %s", s) + } + <-moved + time.Sleep(500 * time.Millisecond) // a burst of writes is one resolution select { case <-moved: - time.Sleep(500 * time.Millisecond) // a burst of writes is one resolution - select { - case <-moved: - default: - } - case <-tick.C: - sweep = true + default: } } } -// hearing takes the router's word on this module's asks, asked again until the runtime takes the subscription, and -// reads the router's record of every waiting ask once a minute besides, so an answer heard nowhere is still taken. +// hearing takes the router's word on this module's asks, asked again until the runtime takes the subscription. func hearing(c *Config) { go func() { <-stdio.Served() // subscribed as soon as the runtime serves, never after a guessed wait: an event sent meanwhile is heard @@ -251,32 +271,32 @@ func hearing(c *Config) { time.Sleep(wait) } }() - for _, pattern := range []string{"git.pull-merged", "git.pull-closed"} { - go func(pattern string) { - <-stdio.Served() // subscribed as soon as the runtime serves, never after a guessed wait: an event sent meanwhile is heard - for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { - err := stdio.Subscribe(pattern, func(e stdio.Envelope) error { - p, ok := pullEventOf(e.Body) - if !ok { - logf("[mesh-config] %s is not readable", pattern) - return nil - } - for _, s := range c.HeardPull(p, pattern == "git.pull-merged") { - logf("[mesh-config] %s", s) - } - return nil - }) - if err == nil { - return - } - logf("[mesh-config] does not hear %s yet (%v); asking again in %s", pattern, err, wait) - time.Sleep(wait) - } - }(pattern) +} + +// DeadlineFloorKey is this module's setting for the least wait of its one deadline timer, in seconds (module.json `config`). +const DeadlineFloorKey = "deadline-floor-seconds" + +// DefaultDeadlineFloor is the floor when the setting cannot be read. +const DefaultDeadlineFloor = time.Minute + +// floorOf is the floor a setting's value names: its seconds, or the default for a value that is not a positive number. +func floorOf(raw json.RawMessage, err error) time.Duration { + var seconds float64 + if err != nil || json.Unmarshal(raw, &seconds) != nil || seconds < 1 { + return DefaultDeadlineFloor } - tick := time.NewTicker(time.Minute) - defer tick.Stop() - for range tick.C { + return time.Duration(seconds * float64(time.Second)) +} + +func deadlineFloor() time.Duration { return floorOf(stdio.Config(DeadlineFloorKey)) } + +// deciding reads the router's record of every waiting ask once at start, which finds an answer said while this module was +// down, and then when the router says an ask ended (hearing's `decided` subscription calls Decide itself) or the next +// deadline of a waiting proposal or retirement passes: one timer for the earliest, set again whenever a proposal or a +// retirement is written (issue 1982; novox/hq ADR 0426 §3: a timer is a deadline, never a poll). +func deciding(c *Config, rearm chan struct{}) { + <-stdio.Served() + decide := func() { said, err := c.Decide() if err != nil { logf("[mesh-config] reading the operator's answers: %v", err) @@ -284,12 +304,31 @@ func hearing(c *Config) { for _, s := range said { logf("[mesh-config] %s", s) } + if err := c.JudgeHeldWindows(); err != nil { + logf("[mesh-config] the held windows cannot be judged: %v", err) + } + } + decide() + for { + at, ok := c.NextDeadline() + if !ok { + <-rearm + continue + } + // Not sooner than the floor: a deadline that passed and was not settled (an ask the router refused) is tried again, not spun on. + timer := time.NewTimer(max(time.Until(at), deadlineFloor())) + select { + case <-timer.C: + decide() + case <-rearm: + timer.Stop() + } } } // hearingDelivery takes the delivery parts' words that close a rename window or retire a value, each asked again until // the runtime takes the subscription: the status view's `delivered`, the node-engine seat's `manifest-reads-changed` -// (a returning node-engine; design 32) and the seat mesh-catalog's `manifest-accepted`. At its start it judges the windows once, +// (a returning node-engine; design 32) and the seat mesh-catalog's `catalog-revision` (design 47 H §764, H-A-49). At its start it judges the windows once, // since an event said while this module was down is not said again. func hearingDelivery(c *Config) { <-stdio.Served() @@ -309,15 +348,7 @@ func hearingDelivery(c *Config) { } return c.Windows(b.Node) }}, - {"mesh-catalog.manifest-accepted", func(e stdio.Envelope) []string { - var b struct { - Module string `json:"module"` - } - if json.Unmarshal(e.Body, &b) != nil { - return nil - } - return c.Retirements(b.Module) - }}, + {"mesh-catalog.catalog-revision.>", func(e stdio.Envelope) []string { return catalogRevisionRetirements(c, e.Body) }}, } { go func(pattern string, handle func(stdio.Envelope) []string) { for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { @@ -340,6 +371,22 @@ func hearingDelivery(c *Config) { } } +// catalogRevisionRetirements judges the retirements of every module a catalog revision names changed: the seat +// mesh-catalog's `catalog-revision` replaces `manifest-accepted`, which goes in H1 (design 47 H §764, H-A-49). +func catalogRevisionRetirements(c *Config, body []byte) []string { + var b struct { + Changed []string `json:"changed"` + } + if json.Unmarshal(body, &b) != nil { + return nil + } + var said []string + for _, m := range b.Changed { + said = append(said, c.Retirements(m)...) + } + return said +} + // seatRename is one open rename as the seat's definition answers it: module, from, to, at and the nodes holding it open. type seatRename struct { Module string `json:"module"` @@ -379,13 +426,10 @@ func Tools(c *Config) []stdio.Tool { "who and why. A trusted value is set only on the operator's Approve: " + "propose asks the operator, under mesh-config's own name on a channel that proves who answered, and sets " + "the value on Approve if what it was shown against still stands; proposals lists them, or one with " + - "proposal. A proposal naming the open pull request that introduces its key (pull) is judged against what " + - "that pull request declares and asked of the operator, and on Approve is held until the pull request " + - "merges, then set; list shows the held values. pull-declares and held are the controller's. list and " + - "history are narrowed by module, node and key.", + "proposal. list and history are narrowed by module, node and key.", Input: map[string]any{"type": "object", "properties": map[string]any{ "action": map[string]any{"type": "string", - "enum": []string{"list", "set", "clear", "history", "propose", "proposals", "pull-declares", "held"}, + "enum": []string{"list", "set", "clear", "history", "propose", "proposals"}, "description": "list when not given"}, "key": map[string]any{"type": "string", "description": "the config key"}, "value": map[string]any{"description": "for set: the value, of the key's declared type"}, @@ -398,14 +442,6 @@ func Tools(c *Config) []stdio.Tool { "clear": map[string]any{"type": "boolean", "description": "for propose: propose clearing the value at its level instead of setting one"}, "proposal": map[string]any{"type": "string", "description": "for proposals: one proposal's id, read whole"}, - "pull": map[string]any{"type": "string", "description": "owner/repository#number: for propose, the open " + - "pull request that introduces the key, so the value is judged against what it declares and held until " + - "it merges (a module's own value on one node); for pull-declares, the pull request declared for"}, - "head": map[string]any{"type": "string", "description": "for pull-declares: the commit the declarations are read at"}, - "declares": map[string]any{"type": "object", "description": "for pull-declares (the controller's): the " + - "config declarations the head adds or changes against its base, by module and key"}, - "pulls": map[string]any{"type": "array", "description": "for held (the controller's): the pull requests " + - "asked about, each {pull, head}", "items": map[string]any{"type": "object"}}, }}, Run: func(args map[string]any) (any, error) { call, err := callOf(args) @@ -421,8 +457,7 @@ func Tools(c *Config) []stdio.Tool { // callOf reads a call's arguments strictly: an argument it does not know is refused, not ignored. func callOf(args map[string]any) (Call, error) { known := map[string]bool{"action": true, "key": true, "value": true, "module": true, "node": true, "why": true, - "by": true, "limit": true, "clear": true, "proposal": true, "pull": true, "head": true, "declares": true, - "pulls": true} + "by": true, "limit": true, "clear": true, "proposal": true} var unknown []string for k := range args { if !known[k] { @@ -431,7 +466,7 @@ func callOf(args map[string]any) (Call, error) { } if len(unknown) > 0 { return Call{}, fmt.Errorf("config takes no %s; it takes action, key, value, module, node, why, by, limit, "+ - "clear, proposal, pull, head, declares and pulls", + "clear and proposal", strings.Join(unknown, ", ")) } str := func(k string) (string, error) { @@ -448,8 +483,7 @@ func callOf(args map[string]any) (Call, error) { var call Call var problems []error for k, into := range map[string]*string{"action": &call.Action, "key": &call.Key, "module": &call.Module, - "node": &call.Node, "why": &call.Why, "by": &call.By, "proposal": &call.Proposal, "pull": &call.Pull, - "head": &call.Head} { + "node": &call.Node, "why": &call.Why, "by": &call.By, "proposal": &call.Proposal} { s, err := str(k) problems = append(problems, err) *into = s @@ -468,19 +502,6 @@ func callOf(args map[string]any) (Call, error) { } call.Clear = b } - if v, ok := args["declares"]; ok && v != nil { - m, ok := v.(map[string]any) - if !ok { - problems = append(problems, errors.New("declares is an object: a module to its keys' declarations")) - } - call.Declares = m - } - if v, ok := args["pulls"]; ok && v != nil { - raw, _ := json.Marshal(v) - if err := json.Unmarshal(raw, &call.Pulls); err != nil { - problems = append(problems, errors.New("pulls is a list of {pull, head}")) - } - } if v, ok := args["value"]; ok { // The value as given, a JSON value: a number for a number, never its text; the validation judges it. call.Value = v diff --git a/modules/mesh-config/cmd/mesh-config/manifest_test.go b/modules/mesh-config/cmd/mesh-config/manifest_test.go index e561cba26..f2dc32240 100644 --- a/modules/mesh-config/cmd/mesh-config/manifest_test.go +++ b/modules/mesh-config/cmd/mesh-config/manifest_test.go @@ -50,10 +50,10 @@ func TestEveryStateAndActHasItsTool(t *testing.T) { } via := map[string]string{ ValuesState: "config list", ResolvedState: "config list", PredefinedState: "config list", - ProposalsState: "config proposals", PullsState: "config list", KeptState: "config list", HistoryLog: "config history", + ProposalsState: "config proposals", HistoryLog: "config history", DeclaredState: DeclaredTool, - AssignmentsRead: "config list", WantsRead: "config list", IndexerPredefinedRead: "config list", CandidatesRead: ResyncTool, - "a resolution": ResyncTool, "the indexer's candidates taken": ResyncTool, + AssignmentsRead: "config list", WantsRead: "config list", IndexerPredefinedRead: "config list", + "a resolution": ResyncTool, // design 32: each new state with the tool that reads it, each act with the tool that starts it. RenamesState: RenamesTool, RetiringState: RetiringTool, FindingsState: "config_renames and config_retiring", "a move refused": RenameAgainTool, "a window dropped": RenameCloseTool, "an ask again": RetiringTool, diff --git a/modules/mesh-config/cmd/mesh-config/ownerviews.go b/modules/mesh-config/cmd/mesh-config/ownerviews.go index a677a0e8c..8ff66ee26 100644 --- a/modules/mesh-config/cmd/mesh-config/ownerviews.go +++ b/modules/mesh-config/cmd/mesh-config/ownerviews.go @@ -1,8 +1,8 @@ package main // What mesh-config reads of the delivery owners' state, through their tools and views families (novox/hq ADR 0615 §1, -// §4 to §6, ADR 0596): never a bucket of theirs. For each of the four states it follows (the indexer's predefined and -// config-candidates, the assigner's assignments and wants) it asks the owner's read tool for the whole +// §4 to §6, ADR 0596): never a bucket of theirs. For each of the three states it follows (the indexer's predefined, the +// assigner's assignments and wants) it asks the owner's read tool for the whole // state at its start, keeps the picture from the owner's `views.` events, and asks again only on a gap. Started // while an owner is down it keeps asking, and past two minutes writes a finding naming the owner and the tool. // @@ -28,7 +28,6 @@ import ( // The tools of the owners that mesh-config asks, by the state they read. const ( IndexerPredefTool = "indexer_read_predefined" - IndexerCandidatesTool = "indexer_read_config_candidates" AssignerAssignmentsTool = "assigner_read_assignments" AssignerWantsTool = "assigner_read_wants" @@ -40,7 +39,6 @@ const ( // state and its tool. var followed = []struct{ Read, Owner, State, Tool string }{ {IndexerPredefinedRead, indexerModule, catalog.StatePredefined, IndexerPredefTool}, - {CandidatesRead, indexerModule, catalog.StateConfigCandidates, IndexerCandidatesTool}, {AssignmentsRead, assignerModule, "assignments", AssignerAssignmentsTool}, {WantsRead, assignerModule, "wants", AssignerWantsTool}, } @@ -189,7 +187,7 @@ func viewTools(c *Config, o func() *ownerViews) []stdio.Tool { return []stdio.Tool{ {Name: FirstViewsTool, Description: "mesh-config's first views of the delivery owners' state: for each of the indexer's " + - "predefined and config-candidates, the assigner's assignments and wants and the catalog half's registrations and " + + "predefined, the assigner's assignments and wants and the catalog half's registrations and " + "each watched branch's revision, the tool it asks, the revision its " + "picture holds, when it asked and was answered, how many asks (and by hand), and whether its condition is raised.", Run: func(map[string]any) (any, error) { diff --git a/modules/mesh-config/cmd/mesh-config/ownstates.go b/modules/mesh-config/cmd/mesh-config/ownstates.go new file mode 100644 index 000000000..b27778d50 --- /dev/null +++ b/modules/mesh-config/cmd/mesh-config/ownstates.go @@ -0,0 +1,77 @@ +package main + +import ( + "encoding/json" + + stdio "git.novox.be/novox/mesh-sdk/go" +) + +// The module's own states are read from a copy each one's watch keeps, never key by key (novox/hq ADR 0580 §1, issue 1982): +// a resolution reads every key of values, resolved, declared and the rest, and a get per key for each of them, once per +// pass and once per delivery event, was about 4,000 requests to the bus every time. A state is watched on its first read, the +// watch hands every current value over before the read is answered, and this process's own writes are taken into the copy +// as they are made, so a read right after a write sees it. + +// ownStates are the states this module keeps and reads through its store (its manifest's `state`, but the findings, which its +// held writer alone reads and writes): the ones read from the copy. +var ownStates = map[string]bool{ + ValuesState: true, ResolvedState: true, PredefinedState: true, ProposalsState: true, DeclaredState: true, RenamesState: true, RetiringState: true, +} + +// ownCopy is the copy of the module's own states over a bus: watch hands every current value of a state and then each change, +// get reads one key, put and del write one. +type ownCopy struct { + copy *stdio.WatchedStates + put func(state, key string, value any) (uint64, error) + del func(state, key string) error + // changed, when not nil, is told of each write or removal after it is in the copy: what waits on a deadline is judged again. + changed func(state string) +} + +// newOwnCopy is the copy over this bundle's runtime. +func newOwnCopy() *ownCopy { + return &ownCopy{copy: stdio.NewWatchedStates(), + put: func(state, key string, value any) (uint64, error) { return stdio.State(state).Put(key, value) }, + del: func(state, key string) error { return stdio.State(state).Delete(key) }} +} + +func (o *ownCopy) get(state, key string) (*Entry, error) { + raw, ok, err := o.copy.Get(state, key) + if err != nil || !ok { + return nil, err + } + return &Entry{Key: key, Value: raw}, nil +} + +func (o *ownCopy) keys(state string) ([]string, error) { return o.copy.Keys(state) } + +// write puts a key and takes it into the copy at the revision the bus answered. +func (o *ownCopy) write(state, key string, value any) error { + rev, err := o.put(state, key, value) + if err != nil { + return err + } + raw, err := json.Marshal(value) + if err != nil { + return err + } + err = o.copy.Wrote(state, key, raw, rev) + o.told(state) + return err +} + +func (o *ownCopy) told(state string) { + if o.changed != nil { + o.changed(state) + } +} + +// remove deletes a key and takes that into the copy. +func (o *ownCopy) remove(state, key string) error { + if err := o.del(state, key); err != nil { + return err + } + err := o.copy.Removed(state, key) + o.told(state) + return err +} diff --git a/modules/mesh-config/cmd/mesh-config/proposals.go b/modules/mesh-config/cmd/mesh-config/proposals.go index e38bee873..59d31ac8f 100644 --- a/modules/mesh-config/cmd/mesh-config/proposals.go +++ b/modules/mesh-config/cmd/mesh-config/proposals.go @@ -98,11 +98,9 @@ type Proposal struct { HadValue bool `json:"had-value"` WasDigest string `json:"was-digest"` Trusted bool `json:"trusted,omitempty"` - // Pull is the open pull request the value is held for, when it is (novox/hq ADR 0502): the value is then not set - // on Approve but kept apart until the pull request merges, and DeclDigest is the digest of the pull request's - // declaration of the key it was judged and shown against. - Pull string `json:"pull,omitempty"` - DeclDigest string `json:"declaration,omitempty"` + // Pull is read only: a proposal an earlier mesh-config kept for a pull request (ADR 0502, superseded by ADR 0681 §5). + // It is never set on an Approve now, and judged not to be one this module makes (problem). + Pull string `json:"pull,omitempty"` // Reaches is each module on each node whose value it moves, as it was judged when proposed. Reaches []string `json:"reaches"` // From is who proposed it, as the bus proved the caller; Why is theirs; At is when. @@ -175,9 +173,6 @@ func (p Proposal) Fingerprint() string { // about is what its ask is about: the value's place, so a newer proposal for it replaces an older one still open // (ADR 0277 §10, at a level, a key). func (p Proposal) about() string { - if p.Pull != "" { - return "config.held." + pullKey(p.Pull) + "." + p.Level.ValueKey(p.Key) - } return "config." + p.Level.ValueKey(p.Key) } @@ -188,9 +183,6 @@ func (p Proposal) Act(option string) occ.Act { "level": p.Level.Kind, "node": p.Level.Node, "module": p.Level.Module, "key": p.Key, "value": p.Digest, "was": p.WasDigest, "had-value": strconv.FormatBool(p.HadValue), "from": p.From, "at": p.At.UTC().Format(time.RFC3339Nano)} - if p.Pull != "" { - act["pull"], act["declaration"] = p.Pull, p.DeclDigest - } return act } @@ -270,16 +262,6 @@ func (p Proposal) summary() string { if p.Trusted { trusted = ", a trusted value," } - if p.Pull != "" { - s := fmt.Sprintf("Holds %s for %s on %s for %s; approved, it takes effect when that pull request merges, "+ - "and is dropped if it closes unmerged. Nothing reaches a machine before the merge.", p.Key, p.Level.Module, - p.Level.Node, p.Pull) - if len([]rune(s)) > occ.SummaryLength { - s = fmt.Sprintf("Holds %s for %s on %s for %s until it merges; dropped if it closes unmerged.", p.Key, - p.Level.Module, p.Level.Node, p.Pull) - } - return s - } reach := p.reaches() s := fmt.Sprintf("%s%s at %s; approved, it takes effect at once on every node it reaches: %s.", verb, trusted, p.Level, reach) @@ -305,9 +287,6 @@ func (p Proposal) headline() string { if p.Action == "clear" { verb = "Clear" } - if p.Pull != "" { - verb = "Hold" - } where := "for the whole mesh" switch p.Level.Kind { case LevelNode: @@ -359,9 +338,6 @@ func (p Proposal) Ask() oc.Ask { a.WholeDetails = w } does := "the value is set at once, and every node it reaches takes it" - if p.Pull != "" { - does = "the value is held for " + p.Pull + ": it is set when that pull request merges, and dropped if it closes unmerged" - } if p.Action == "clear" { does = "the value is cleared at once, and every node it reaches takes what is below it" } @@ -392,8 +368,8 @@ func (p Proposal) problem() string { return "its value is not the value its digest names: it changed after it was asked" case p.Action == "clear" && (len(p.Value) != 0 || p.Digest != valueDigest(nil, false)): return "a clear carries no value" - case p.Pull != "" && (p.Action != "set" || p.Level.Kind != LevelModule || p.DeclDigest == ""): - return "a value held for a pull request is a set of a module's own value, judged against its declaration" + case p.Pull != "": + return "it was held for a pull request, which the mesh knows no more: nothing is set on it" case valueDigest(p.Was, p.HadValue) != p.WasDigest: return "the value it was shown against is not the one its digest names: it changed after it was asked" } @@ -559,39 +535,16 @@ func (c *Config) propose(call Call, action string) (Proposal, oc.Ask, []string, // **Judged as a set judges it, before anyone is asked** (ADR 0277 §4): no ask for a value the verb would refuse. var r rule var trusted bool - var declDigest string vk := level.ValueKey(call.Key) was, had := s.Values[vk] - if call.Pull != "" { - // **A value held for the open pull request that introduces its key** (novox/hq ADR 0502): judged against what - // the pull request declares at its head, as the controller told it, and asked of the operator whatever the - // key's trust. - if action != "set" { - return fail("a clear is not held for a pull request: only a value to set is") - } - if _, _, _, err := parsePull(call.Pull); err != nil { - return fail("%v", err) - } - call.Pull = strings.TrimSpace(call.Pull) - var herr error - r, _, declDigest, herr = heldRule(s, call, level) - if herr != nil { - return fail("%v", herr) - } - trusted = false - k, kept := s.Kept[keptKey(call.Pull, level.Node, level.Module, call.Key)] - was, had = Value{Value: heldValue(k)}, kept - } else { - var derr error - r, trusted, derr = c.declared(s, level, call.Key) - if derr != nil { - return fail("%v", derr) - } + r, trusted, derr := c.declared(s, level, call.Key) + if derr != nil { + return fail("%v", derr) } now := c.now() prop := Proposal{ID: newProposalID(), Action: action, Level: level, Key: call.Key, HadValue: had, WasDigest: valueDigest(was.Value, had), Trusted: trusted, From: call.Caller, Why: why, At: now, - State: ProposalWaiting, Digest: valueDigest(nil, false), Pull: call.Pull, DeclDigest: declDigest} + State: ProposalWaiting, Digest: valueDigest(nil, false)} if had { prop.Was = compact(was.Value) } @@ -618,19 +571,15 @@ func (c *Config) propose(call Call, action string) (Proposal, oc.Ask, []string, if had && string(compact(was.Value)) == string(prop.Value) { return fail("%s at %s already holds exactly %s", call.Key, level, prop.Value) } - if call.Pull == "" { - after.Values[vk] = Value{Value: prop.Value} - } + after.Values[vk] = Value{Value: prop.Value} case "clear": if !had { return fail("nothing is set for %s at %s, so there is nothing to clear", call.Key, level) } delete(after.Values, vk) } - if call.Pull == "" { - for _, m := range diff(Resolve(s), Resolve(after)) { - prop.Reaches = append(prop.Reaches, m.Module+" on "+m.Node) - } + for _, m := range diff(Resolve(s), Resolve(after)) { + prop.Reaches = append(prop.Reaches, m.Module+" on "+m.Node) } if prop.Reaches == nil { prop.Reaches = []string{} @@ -830,14 +779,6 @@ func (c *Config) decide(p Proposal, w oc.Warrant) string { return fmt.Sprintf("proposal %s: approved by the operator, and not set: the decision could not be kept (%v); "+ "it is read again on the next look", p.ID, err) } - if p.Pull != "" { - // **A held value is kept apart, never set on Approve** (ADR 0502 clause 3). - said, err := c.keep(p) - if err != nil { - return keep(ProposalRefused, "approved by the operator, and refused on Approve, so nothing is held: "+err.Error()) - } - return keep(ProposalApproved, "approved by the operator and held: "+said) - } call := Call{Action: p.Action, Key: p.Key, Module: p.Level.Module, Node: p.Level.Node, Why: p.Why, Caller: p.From, approval: &approval{Proposal: p.ID, By: "the operator", Says: p.Approved, Was: p.Was, HadValue: p.HadValue, WasDigest: p.WasDigest}} @@ -910,19 +851,63 @@ func (c *Config) HeardEnd(w oc.Warrant) []string { c.mu.Lock() defer c.mu.Unlock() defer c.tellEnded(w.Ask, endedWord{Outcome: w.Outcome, Words: w.Words}) + // A retirement's ask ended with no choice is taken from the router's record the same way (retiring.go): the router's word + // is the only thing that moves it, and no timer looks. + said := c.decideRetirements() e, err := c.Store.Get(ProposalsState, w.Ask) if err != nil || e == nil { - return nil + return said } var p Proposal if json.Unmarshal(e.Value, &p) != nil || p.ID != w.Ask || p.State != ProposalWaiting { - return nil + return said } why := "the ask " + string(w.Outcome) if w.Words != "" { why += " (" + w.Words + ")" } - return []string{c.end(p, why+"; nothing was set")} + return append(said, c.end(p, why+"; nothing was set")) +} + +// NextDeadline is when a waiting proposal or retirement is next judged for want of an answer: a proposal with no record +// at the router ends an hour after its ask lapses (Decide), and a retirement left unanswered is asked once more after +// HeldFinding, and an open rename window's held finding comes after HeldFinding too (lead answer A-490l). The earliest of +// them; false when nothing waits on a time. +func (c *Config) NextDeadline() (time.Time, bool) { + c.mu.Lock() + defer c.mu.Unlock() + var at time.Time + earlier := func(t time.Time) { + if at.IsZero() || t.Before(at) { + at = t + } + } + if all, err := c.proposals(); err == nil { + for _, p := range all { + if p.State == ProposalWaiting { + earlier(p.At.Add(ProposalLasts + time.Hour)) + } + } + } + if held, err := c.readRetiring(); err == nil { + for _, e := range held { + if e.State == RetireUnanswered && !e.AskedAgain { + earlier(e.Asked.Add(HeldFinding)) + } + } + } + // An open rename window reaches its held finding after HeldFinding (renames.go): its deadline, while it lies ahead. + if renames, err := c.readRenames(); err == nil { + now := c.now() + for _, r := range renames { + for _, node := range r.Open() { + if d := r.Nodes[node].Since.Add(HeldFinding); d.After(now) { + earlier(d) + } + } + } + } + return at, !at.IsZero() } // ---- the list ---------------------------------------------------------------------------------------------- @@ -940,8 +925,6 @@ type ProposalRow struct { Expires time.Time `json:"expires"` Fingerprint string `json:"fingerprint"` Approved string `json:"approved,omitempty"` - // Pull is the pull request a value is held for, when it is. - Pull string `json:"pull,omitempty"` // What one proposal read whole says besides. Value json.RawMessage `json:"value,omitempty"` Was json.RawMessage `json:"was,omitempty"` @@ -970,8 +953,7 @@ func (c *Config) Proposals(call Call) ([]ProposalRow, error) { continue } row := ProposalRow{ID: p.ID, Action: p.Action, Level: p.Level, Key: p.Key, State: p.State, Outcome: p.Outcome, - From: p.From, At: p.At, Expires: p.At.Add(ProposalLasts), Fingerprint: p.Fingerprint(), Approved: p.Approved, - Pull: p.Pull} + From: p.From, At: p.At, Expires: p.At.Add(ProposalLasts), Fingerprint: p.Fingerprint(), Approved: p.Approved} if p.State == ProposalWaiting && c.now().After(row.Expires) { row.State = "expired, not yet heard" } diff --git a/modules/mesh-config/cmd/mesh-config/proposals_test.go b/modules/mesh-config/cmd/mesh-config/proposals_test.go index da09744a5..af8c99587 100644 --- a/modules/mesh-config/cmd/mesh-config/proposals_test.go +++ b/modules/mesh-config/cmd/mesh-config/proposals_test.go @@ -590,3 +590,42 @@ func TestAnOwnersListOfNamesWithDigitsIsProposed(t *testing.T) { t.Fatalf("the owners were not put to the operator: %+v, asked on %v", a, r.subjects) } } + +// **An approved proposal records a hand act that names no pull request** (ADR 0681 clause 1: nothing it records as a hand act is a +// held value). +func TestAnApprovedProposalsHandActNamesNoPullRequest(t *testing.T) { + c, m, r := aProposingMesh(t) + a := propose(t, c, Call{Key: "font-size", Value: 12.0, Node: "g14"}) + r.choose(t, a.Proposal, OptionApprove, nil) + m.handActs = nil + if said, err := c.Decide(); err != nil || len(said) == 0 { + t.Fatalf("decide: %v, %v", said, err) + } + if len(m.handActs) == 0 { + t.Fatal("the approval recorded no hand act") + } + for _, act := range m.handActs { + if strings.Contains(strings.ToLower(act), "pull") || strings.Contains(act, "#") { + t.Errorf("a hand act names a pull request: %q", act) + } + } +} + +// A stored proposal that names a pull request is refused on its approval, saying why, and nothing is set (lead answer A-490l). +func TestAStoredProposalNamingAPullRequestIsRefusedOnApproval(t *testing.T) { + c, m, r := aProposingMesh(t) + a := propose(t, c, Call{Key: "font-size", Value: 12.0, Node: "g14"}) + p := storedProposal(t, m, a.Proposal) + p.Pull = "novox/mesh-catalog#7" + if err := m.Put(ProposalsState, p.ID, p); err != nil { + t.Fatal(err) + } + r.choose(t, a.Proposal, OptionApprove, nil) + said, _ := c.Decide() + if got := storedProposal(t, m, a.Proposal); got.State == ProposalApproved || len(said) == 0 || !strings.Contains(strings.Join(said, " "), "pull request") { + t.Errorf("said %v, proposal %+v", said, got) + } + if _, ok := storedValue(t, m, "node.g14.font-size"); ok { + t.Error("a value was set on a proposal that names a pull request") + } +} diff --git a/modules/mesh-config/cmd/mesh-config/pullforge_test.go b/modules/mesh-config/cmd/mesh-config/pullforge_test.go deleted file mode 100644 index e2418e65c..000000000 --- a/modules/mesh-config/cmd/mesh-config/pullforge_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "encoding/json" - "testing" -) - -// toolForge.Pull reads the seat git's answer of the verb pull (design 47 G §654), bare or in the wrappings the runtime puts -// around an answer; pullEventOf reads the seat's pull-merged and pull-closed bodies. -func TestToolForgePullReadsTheSeatGitAnswersAndEventsAreRead(t *testing.T) { - var asked struct { - key string - body map[string]any - } - for _, tc := range []struct { - answer string - open, merged bool - head string - }{ - {`{"pull":{"repository":"novox/mesh-catalog","number":435,"state":"merged","head":"7b5f7f84acb73aaf8189200548ff69fd9aac04b2"}}`, false, true, "7b5f7f84acb73aaf8189200548ff69fd9aac04b2"}, - {`{"pull":{"repository":"novox/mesh-catalog","number":434,"state":"open","head":"c948f3a61c74257e6e3147effb396d9d6434f491"}}`, true, false, "c948f3a61c74257e6e3147effb396d9d6434f491"}, - {`{"pull":{"state":"closed","head":"c948f3a61c74257e6e3147effb396d9d6434f491"}}`, false, false, "c948f3a61c74257e6e3147effb396d9d6434f491"}, - } { - raw := json.RawMessage(tc.answer) - content, _ := json.Marshal(map[string]any{"content": []map[string]any{{"type": "text", "text": tc.answer}}}) - ok, _ := json.Marshal(map[string]any{"ok": true, "output": "", "answer": raw}) - for name, answer := range map[string]json.RawMessage{"bare": raw, "content list": content, "ok answer": ok} { - f := toolForge{ask: func(key string, body any) (json.RawMessage, error) { - asked.key, asked.body = key, body.(map[string]any) - return answer, nil - }} - open, merged, head, err := f.Pull("novox", "mesh-catalog", 434) - if err != nil || open != tc.open || merged != tc.merged || head != tc.head { - t.Errorf("%s (%s): open %v merged %v head %q, err %v", tc.answer, name, open, merged, head, err) - } - if asked.key != "seat:git.pull" || asked.body["repository"] != "novox/mesh-catalog" || asked.body["number"] != 434 { - t.Errorf("asked %+v", asked) - } - } - } - failed := toolForge{ask: func(string, any) (json.RawMessage, error) { - return json.RawMessage(`{"error":"no such pull request","error-kind":"not-found"}`), nil - }} - if _, _, _, err := failed.Pull("novox", "mesh-catalog", 9); err == nil { - t.Error("an error answer was read as a pull request") - } - p, ok := pullEventOf([]byte(`{"repository":"novox/mesh-catalog","number":435,"branch":"fix/a","head":"7b5f7f84acb73aaf8189200548ff69fd9aac04b2","base":"main"}`)) - if !ok || p.Owner != "novox" || p.Repo != "mesh-catalog" || p.Number != 435 || p.HeadSHA != "7b5f7f84acb73aaf8189200548ff69fd9aac04b2" { - t.Errorf("%+v %v", p, ok) - } - if _, ok := pullEventOf([]byte(`{"repository":"norepo","number":1}`)); ok { - t.Error("a repository with no owner was read") - } -} diff --git a/modules/mesh-config/cmd/mesh-config/pulls.go b/modules/mesh-config/cmd/mesh-config/pulls.go deleted file mode 100644 index 50f01da94..000000000 --- a/modules/mesh-config/cmd/mesh-config/pulls.go +++ /dev/null @@ -1,644 +0,0 @@ -package main - -import ( - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "regexp" - "strconv" - "strings" - "time" - - "git.novox.be/novox/mesh-contracts/go/clients/meshconfigclient" -) - -// A config value held for the open pull request that introduces its key (novox/hq ADR 0502, issue 1826). -// -// A key a pull request adds is declared by no registered manifest until it merges, so a value for it, which the -// pull request's composed check needs, was refused. The controller reads each pull request's manifests from the -// forge at its head and tells this module the config declarations the head adds or changes (PullDeclares); mesh-config -// reads no manifest itself (ADR 0495 §1). A proposal that names the pull request is judged against those, asked of the -// operator whatever the key's trust, and on Approve kept apart (KeptState) from the values it resolves. The -// controller asks for the approved held values of a check's pull requests (Held) and hands them to the composed -// check. At the merge the value is written as the module's own value on its node (PullMerged), where it resolves -// once the trunk declares the key; a pull request closed unmerged drops it (PullClosed). Nothing reaches a machine -// before the merge. - -// The states of held values, and the actions their changes carry in the history and in `config-changed`. -const ( - PullsState = "pulls" - KeptState = "kept" - - ActionHold = "hold" - ActionDrop = "drop" -) - -// pullName is a pull request as it is named: owner/repository#number. -var pullName = regexp.MustCompile(`^([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)#([0-9]+)$`) - -func parsePull(s string) (owner, repo string, number int, err error) { - m := pullName.FindStringSubmatch(strings.TrimSpace(s)) - if m == nil { - return "", "", 0, fmt.Errorf("%q is not a pull request: name it owner/repository#number", s) - } - n, _ := strconv.Atoi(m[3]) - if n <= 0 { - return "", "", 0, fmt.Errorf("%q is not a pull request: its number is above zero", s) - } - return m[1], m[2], n, nil -} - -// pullKey is a pull request's key in the states. -func pullKey(pull string) string { - return strings.NewReplacer("/", ".", "#", ".").Replace(strings.TrimSpace(pull)) -} - -// PullDecl is what the controller told: the config declarations a pull request's head adds or changes, by module. -type PullDecl struct { - Pull string `json:"pull"` - Head string `json:"head"` - Declares map[string]map[string]Declaration `json:"declares"` - At time.Time `json:"at"` -} - -// KeptValue is an approved held value, kept apart from the values mesh-config resolves, in the layout of the seat's state -// `kept`, which the checker and the assigner's composition check read (novox/hq ADR 0565 §5, ADR 0634 §4). -type KeptValue = meshconfigclient.Kept - -// keptKey is a held value's key in `kept`: the pull request's key form (pullKey), the node, the module and the config -// key, joined by dots. -func keptKey(pull, node, module, key string) string { - k, _ := meshconfigclient.HeldValueKey(pull, node, module, key) // a held value of no pull request has no key, and is found by none - return k -} - -// heldValue is the value held, as the operator approved it, in its JSON form. -func heldValue(k KeptValue) json.RawMessage { - raw, _ := meshconfigclient.ValueOf(k) // a value that was read from JSON writes as JSON - return raw -} - -func heldAt(t time.Time) *time.Time { return &t } - -func keptStateKey(k KeptValue) string { return keptKey(k.Pull, k.Node, k.Module, k.Key) } - -func keptLevel(k KeptValue) Level { return Level{Kind: LevelModule, Node: k.Node, Module: k.Module} } - -// declDigest is the digest of what a declaration holds a value to: a held value stays only while it is the same. -func declDigest(d Declaration) string { - d.Description, d.Why, d.Kind, d.Runtime = "", "", "", false - if !d.HasDefault() { - d.Default = nil - } else { - d.Default = compact(d.Default) - } - raw, _ := json.Marshal(d) - sum := sha256.Sum256(raw) - return "sha256:" + hex.EncodeToString(sum[:]) -} - -// PullForge is the forge as this module asks it of a pull request: its state, and whether it merged. -type PullForge interface { - Pull(owner, repo string, number int) (open, merged bool, head string, err error) -} - -// pulls reads what is kept for pull requests, and the held values. -func (c *Config) readPulls(s *Sources) error { - s.Pulls, s.Kept = map[string]PullDecl{}, map[string]KeptValue{} - if err := c.each(PullsState, func(key string, raw []byte) error { - var p PullDecl - if err := json.Unmarshal(raw, &p); err != nil || p.Pull == "" { - return nil // not one this module wrote - } - s.Pulls[pullKey(p.Pull)] = p - return nil - }); err != nil { - return fmt.Errorf("the pull requests' declarations cannot be read: %w", err) - } - if err := c.each(KeptState, func(key string, raw []byte) error { - k, err := meshconfigclient.DecodeKept(key, raw) - if err != nil { - return nil // not a held value of the seat's layout under its own key - } - s.Kept[key] = k - return nil - }); err != nil { - return fmt.Errorf("the held values cannot be read: %w", err) - } - return nil -} - -// ---- pull-declares --------------------------------------------------------------------------------------- - -// PullDeclaresAnswer is what pull-declares answers. -type PullDeclaresAnswer struct { - Said string `json:"said"` - Pull string `json:"pull"` - Head string `json:"head"` - Modules []string `json:"modules"` - Dropped []string `json:"dropped,omitempty"` - Unsaid []string `json:"unsaid,omitempty"` -} - -// PullDeclares is gone: a pull request's config declarations are read from the indexer's config-candidates -// (takeCandidates), and the controller that told them is not placed (novox/hq ADR 0565 §4, ADR 0590). -func (c *Config) PullDeclares(Call) (*PullDeclaresAnswer, error) { - return nil, errors.New("pull-declares is gone: mesh-config reads a pull request's config declarations from the " + - "indexer's config-candidates (novox/hq ADR 0565 §4, ADR 0590)") -} - -// declarePull keeps what a pull request's head declares and judges again the values held for it, from the indexer's -// config candidates. The caller holds the lock. -func (c *Config) declarePull(pull, head string, declares map[string]map[string]Declaration) (*PullDeclaresAnswer, error) { - if err := c.Store.Put(PullsState, pullKey(pull), PullDecl{Pull: pull, Head: head, Declares: declares, - At: c.now()}); err != nil { - return nil, fmt.Errorf("the declarations were not kept: %v", err) - } - a := &PullDeclaresAnswer{Pull: pull, Head: head, Modules: sortedKeys(declares)} - var s Sources - if err := c.readPulls(&s); err != nil { - return nil, err - } - for _, k := range sortedKeys(s.Kept) { - kv := s.Kept[k] - if pullKey(kv.Pull) != pullKey(pull) { - continue - } - why := "" - d, declared := declares[kv.Module][kv.Key] - switch { - case !declared: - why = "the head no longer adds or changes its declaration" - case declDigest(d) != kv.Declaration: - why = "the head declares the key otherwise than the value was approved against" - default: - var v any - _ = json.Unmarshal(heldValue(kv), &v) - if p := d.rule().check(v); len(p) > 0 { - why = "the value no longer passes: " + strings.Join(p, "; ") - } - } - if why != "" { - a.Unsaid = append(a.Unsaid, c.dropKept(kv, "the new head "+short(head)+": "+why)...) - a.Dropped = append(a.Dropped, fmt.Sprintf("%s for %s on %s: %s", kv.Key, kv.Module, kv.Node, why)) - continue - } - if kv.Head != head { - kv.Head = head - if err := c.Store.Put(KeptState, k, kv); err != nil { - a.Unsaid = append(a.Unsaid, "the held value "+k+" was not moved to the new head: "+err.Error()) - } - } - } - a.Said = fmt.Sprintf("keeps what %s declares at %s for %d module(s)", pull, short(head), len(declares)) - if len(a.Dropped) > 0 { - a.Said += fmt.Sprintf("; %d held value(s) dropped", len(a.Dropped)) - } - return a, nil -} - -// heldChange records a hold, a drop or a merge's set of a held value in the history, the hand-act log and -// config-changed; what could not be done is answered, not dropped. -func (c *Config) heldChange(kv KeptValue, action, why, approved string) []string { - level := keptLevel(kv) - ch := Change{Action: action, Level: &level, Key: kv.Key, Value: heldValue(kv), By: kv.By, Via: kv.Via, Why: why, - Approved: approved, Pull: kv.Pull, Head: kv.Head, At: c.now(), Moved: []Moved{}} - unsaid := c.record(level.ValueKey(kv.Key), ch) - cause := "a value held for " + kv.Pull - what := fmt.Sprintf("config %s %s of %s for %s, held for %s", action, kv.Key, kv.Module, kv.Node, kv.Pull) - if action != ActionDrop { - what += " (" + string(heldValue(kv)) + ")" - } - if err := c.Store.HandAct(what, why, cause); err != nil { - unsaid = append(unsaid, "the hand-act log does not hold it: "+err.Error()) - } - return unsaid -} - -// dropKept removes a held value, saying why. -func (c *Config) dropKept(kv KeptValue, why string) []string { - if err := c.Store.Delete(KeptState, keptStateKey(kv)); err != nil { - return []string{"the held value " + keptStateKey(kv) + " was not dropped: " + err.Error()} - } - c.logf("[mesh-config] dropped %s of %s on %s held for %s: %s", kv.Key, kv.Module, kv.Node, kv.Pull, why) - return c.heldChange(kv, ActionDrop, "dropped, nothing was set: "+why, "") -} - -// ---- held ------------------------------------------------------------------------------------------------ - -// HeldAnswer is what held answers: the approved held values of the pull requests asked, at the heads asked. -type HeldAnswer struct { - Held []HeldValue `json:"held"` - Skipped []HeldSkipped `json:"skipped"` -} - -// HeldValue is one approved held value as it is handed to a composed check and listed. -type HeldValue struct { - Pull string `json:"pull"` - Head string `json:"head"` - Node string `json:"node"` - Module string `json:"module"` - Key string `json:"key"` - Value json.RawMessage `json:"value"` - Approved string `json:"approved"` - By string `json:"by,omitempty"` - Why string `json:"why,omitempty"` - At time.Time `json:"at"` -} - -// HeldSkipped is a pull request asked for whose held values are not answered, and why. -type HeldSkipped struct { - Pull string `json:"pull"` - Why string `json:"why"` -} - -func heldValueOf(k KeptValue) HeldValue { - return HeldValue{Pull: k.Pull, Head: k.Head, Node: k.Node, Module: k.Module, Key: k.Key, Value: compact(heldValue(k)), - Approved: k.Approved, By: k.By, Why: k.Why, At: timeOf(k.At)} -} - -// Held answers the approved held values for the pull requests asked, at the heads asked, to the controller alone: a -// pull request at another head than the one kept is skipped and said (ADR 0502 clause 4). -func (c *Config) Held(call Call) (*HeldAnswer, error) { - if call.Caller != ControllerCaller { - return nil, fmt.Errorf("held is the controller's: it hands the held values to a composed check; %s is not "+ - "the controller", call.Caller) - } - asked := map[string]string{} - var order []string - for _, p := range call.Pulls { - if _, _, _, err := parsePull(p.Pull); err != nil { - return nil, err - } - if strings.TrimSpace(p.Head) == "" { - return nil, fmt.Errorf("name the head of %s", p.Pull) - } - if _, dup := asked[pullKey(p.Pull)]; !dup { - order = append(order, strings.TrimSpace(p.Pull)) - } - asked[pullKey(p.Pull)] = strings.TrimSpace(p.Head) - } - c.mu.Lock() - defer c.mu.Unlock() - var s Sources - if err := c.readPulls(&s); err != nil { - return nil, err - } - out := &HeldAnswer{Held: []HeldValue{}, Skipped: []HeldSkipped{}} - for _, p := range order { - head := asked[pullKey(p)] - var mine []KeptValue - for _, k := range sortedKeys(s.Kept) { - if pullKey(s.Kept[k].Pull) == pullKey(p) { - mine = append(mine, s.Kept[k]) - } - } - for _, k := range mine { - if k.Head != head { - out.Skipped = append(out.Skipped, HeldSkipped{Pull: p, Why: fmt.Sprintf("%s for %s on %s is held "+ - "at head %s, not %s", k.Key, k.Module, k.Node, short(k.Head), short(head))}) - continue - } - out.Held = append(out.Held, heldValueOf(k)) - } - } - return out, nil -} - -// HeldListed is the held values a listing shows, narrowed by module, node and key. -func heldListed(s Sources, call Call) []HeldValue { - out := []HeldValue{} - for _, k := range sortedKeys(s.Kept) { - kv := s.Kept[k] - if (call.Module == "" || kv.Module == call.Module) && (call.Node == "" || kv.Node == call.Node) && - (call.Key == "" || kv.Key == call.Key) { - out = append(out, heldValueOf(kv)) - } - } - return out -} - -// ---- the proposal's rule ------------------------------------------------------------------------------- - -// heldRule is the rule a value held for a pull request is judged by: the pull request's declaration of the key for -// the module at its head, and the module's assignment to the node. Refused, saying what the pull request does -// declare, when it declares none. -func heldRule(s Sources, call Call, level Level) (rule, PullDecl, string, error) { - if level.Kind != LevelModule { - return rule{}, PullDecl{}, "", fmt.Errorf("a value held for a pull request is a module's own value on one "+ - "node, and %s is not one: a predefined key a pull request adds is set after its merge (novox/hq ADR 0502)", - level) - } - pd, ok := s.Pulls[pullKey(call.Pull)] - if !ok { - return rule{}, PullDecl{}, "", fmt.Errorf("mesh-config holds no declaration for %s: the controller tells it "+ - "what a pull request declares when its head is announced, and none has been", strings.TrimSpace(call.Pull)) - } - d, ok := pd.Declares[level.Module][call.Key] - if !ok { - return rule{}, PullDecl{}, "", fmt.Errorf("%s does not add or change a value %q for %s at %s; it declares "+ - "for %s: %s", pd.Pull, call.Key, level.Module, short(pd.Head), level.Module, joinKeys(pd.Declares[level.Module])) - } - if _, reg := s.Declared[level.Module]; !reg { - return rule{}, PullDecl{}, "", fmt.Errorf("%s is not a registered module, so a value cannot be held for it", level.Module) - } - if !assigned(s, level.Node, level.Module) { - return rule{}, PullDecl{}, "", fmt.Errorf("%s is not placed on %s, and a module's own value is set for a node "+ - "it is placed on (novox/hq ADR 0348 §3); it is placed on: %s", level.Module, level.Node, - strings.Join(nodesOf(s, level.Module), ", ")) - } - return d.rule(), pd, declDigest(d), nil -} - -// keep holds an approved proposal's value apart. The caller holds the lock. -func (c *Config) keep(p Proposal) (string, error) { - var s Sources - if err := c.readPulls(&s); err != nil { - return "", err - } - pd, ok := s.Pulls[pullKey(p.Pull)] - if !ok { - return "", fmt.Errorf("mesh-config holds no declaration for %s any more", p.Pull) - } - d, ok := pd.Declares[p.Level.Module][p.Key] - if !ok || declDigest(d) != p.DeclDigest { - return "", fmt.Errorf("%s declares %s otherwise than the operator was shown, or no longer declares it: "+ - "propose it again", p.Pull, p.Key) - } - was, had := s.Kept[keptKey(p.Pull, p.Level.Node, p.Level.Module, p.Key)] - if had != p.HadValue || valueDigest(heldValue(was), had) != p.WasDigest { - return "", fmt.Errorf("the value held for %s changed since the operator was shown the change: propose it "+ - "again", p.Pull) - } - kv := KeptValue{Pull: p.Pull, Head: pd.Head, Declaration: p.DeclDigest, Node: p.Level.Node, Module: p.Level.Module, - Key: p.Key, Value: p.Value, By: "the operator", Via: p.From, Why: p.Why, Approved: p.Approved, Proposal: p.ID, - At: heldAt(c.now())} - if err := c.Store.Put(KeptState, keptStateKey(kv), kv); err != nil { - return "", fmt.Errorf("the value was not kept: %v", err) - } - unsaid := c.heldChange(kv, ActionHold, "held for "+p.Pull+" until it merges: "+p.Why, p.Approved) - said := fmt.Sprintf("%s of %s on %s is held at %s for %s until it merges", p.Key, p.Level.Module, p.Level.Node, - short(pd.Head), p.Pull) - if len(unsaid) > 0 { - said += " (" + strings.Join(unsaid, "; ") + ")" - } - return said, nil -} - -// ---- the merge and the close --------------------------------------------------------------------------- - -// PullMerged writes each value held for a pull request as the module's own value on its node, with the approval kept -// beside it; it resolves once the trunk declares the key. It answers a line for each. -func (c *Config) PullMerged(pull, head string) []string { - return c.settlePull(pull, true, head) -} - -// PullClosed drops the values held for a pull request closed unmerged, and says that nothing was set. -func (c *Config) PullClosed(pull string) []string { - return c.settlePull(pull, false, "") -} - -func (c *Config) settlePull(pull string, merged bool, head string) []string { - c.mu.Lock() - defer c.mu.Unlock() - var s Sources - if err := c.readPulls(&s); err != nil { - return []string{err.Error()} - } - var said []string - wrote := false - for _, k := range sortedKeys(s.Kept) { - kv := s.Kept[k] - if pullKey(kv.Pull) != pullKey(pull) { - continue - } - if !merged { - said = append(said, fmt.Sprintf("%s of %s on %s was held for %s, which closed unmerged: dropped, "+ - "nothing was set", kv.Key, kv.Module, kv.Node, kv.Pull)) - said = append(said, c.dropKept(kv, kv.Pull+" closed unmerged")...) - continue - } - // **Only a value held at the merged head, whose key that head declares as it was approved** (ADR 0502 clause 7). - why := "" - pd, known := s.Pulls[pullKey(pull)] - d, declared := pd.Declares[kv.Module][kv.Key] - switch { - case head == "": - why = "the merged head is not known, so the value cannot be held to it" - case !strings.EqualFold(head, kv.Head): - why = fmt.Sprintf("it is held at head %s and the pull request merged at %s", short(kv.Head), short(head)) - case !known || !declared || declDigest(d) != kv.Declaration: - why = "the merged head does not declare the key as the operator was shown" - } - if why != "" { - said = append(said, fmt.Sprintf("%s of %s on %s was held for %s, which merged: dropped, nothing was set (%s)", - kv.Key, kv.Module, kv.Node, kv.Pull, why)) - said = append(said, c.dropKept(kv, kv.Pull+" merged, but "+why)...) - continue - } - vk := keptLevel(kv).ValueKey(kv.Key) - v := Value{Value: compact(heldValue(kv)), By: kv.By, Via: kv.Via, Why: kv.Why + " (held for " + kv.Pull + - ", merged)", Approved: kv.Approved, At: c.now()} - if err := c.Store.Put(ValuesState, vk, v); err != nil { - said = append(said, fmt.Sprintf("%s of %s on %s held for %s is not written yet: %v; it is tried "+ - "again", kv.Key, kv.Module, kv.Node, kv.Pull, err)) - continue - } - if err := c.Store.Delete(KeptState, k); err != nil { - said = append(said, "the held value "+k+" is written but not removed: "+err.Error()) - } - wrote = true - said = append(said, c.heldChange(kv, "set", kv.Pull+" merged: the held value is the module's own value now", - kv.Approved)...) - said = append(said, fmt.Sprintf("%s of %s on %s held for %s is set: %s", kv.Key, kv.Module, kv.Node, - kv.Pull, kv.Value)) - } - if wrote { - if s2, err := c.sources(); err == nil { - if _, err := c.writeResolved(s2); err != nil { - said = append(said, "the resolved values are not all written yet ("+err.Error()+"); the next "+ - "resolution writes them") - } - } - } - left := 0 - for _, k := range sortedKeys(s.Kept) { - if pullKey(s.Kept[k].Pull) != pullKey(pull) { - continue - } - if e, err := c.Store.Get(KeptState, k); err != nil || e != nil { - left++ - } - } - if left == 0 { - if err := c.Store.Delete(PullsState, pullKey(pull)); err != nil { - said = append(said, "the declarations of "+pull+" were not removed: "+err.Error()) - } - } - return said -} - -// PullEvent is a pull request merged or closed, as far as this module reads it: the seat `git`'s `pull-merged` or `pull-closed` -// (design 47 G §654), read by pullEventOf. -type PullEvent struct { - Owner string - Repo string - Number int - Merged bool - // HeadSHA is the head the pull request merged at. - HeadSHA string -} - -// pullEventOf reads the seat `git`'s `pull-merged` or `pull-closed` body: the repository `/`, the number and the head. -func pullEventOf(body []byte) (PullEvent, bool) { - var e struct { - Repository string `json:"repository"` - Number int `json:"number"` - Head string `json:"head"` - } - if json.Unmarshal(body, &e) != nil { - return PullEvent{}, false - } - owner, repo, ok := strings.Cut(e.Repository, "/") - return PullEvent{Owner: owner, Repo: repo, Number: e.Number, HeadSHA: e.Head}, ok -} - -func (p PullEvent) name() string { return fmt.Sprintf("%s/%s#%d", p.Owner, p.Repo, p.Number) } - -// HeardPull takes the forge's word that a pull request merged or closed. A close is asked of the forge when it can -// be, because a merged pull request may be announced as closed too. -func (c *Config) HeardPull(p PullEvent, merged bool) []string { - if p.Owner == "" || p.Repo == "" || p.Number <= 0 { - return nil - } - head := p.HeadSHA - if !merged && !p.Merged && c.Forge != nil { - // A close is told from a merge by the forge; when it cannot be asked nothing is dropped, and the five-minute - // look finds it. - open, m, h, err := c.Forge.Pull(p.Owner, p.Repo, p.Number) - if err != nil { - c.logf("[mesh-config] %s closed, and the forge does not say whether it merged (%v); the next look decides", p.name(), err) - return nil - } - if open { - return nil - } - merged = m - if head == "" { - head = h - } - } - return c.settlePull(p.name(), merged || p.Merged, head) -} - -// SweepPulls looks at the forge for every pull request it keeps something for, so a merge or a close it did not hear -// is found: run with each five-minute resolution. -func (c *Config) SweepPulls() []string { - if c.Forge == nil { - return nil - } - c.mu.Lock() - var s Sources - err := c.readPulls(&s) - c.mu.Unlock() - if err != nil { - return []string{err.Error()} - } - seen := map[string]string{} - for _, p := range s.Pulls { - seen[pullKey(p.Pull)] = p.Pull - } - for _, k := range s.Kept { - seen[pullKey(k.Pull)] = k.Pull - } - var said []string - for _, key := range sortedKeys(seen) { - pull := seen[key] - owner, repo, n, err := parsePull(pull) - if err != nil { - continue - } - open, merged, head, err := c.Forge.Pull(owner, repo, n) - if err != nil { - said = append(said, fmt.Sprintf("the forge does not say whether %s is open: %v", pull, err)) - continue - } - if !open { - said = append(said, c.settlePull(pull, merged, head)...) - } - } - return said -} - -// PullAt is a pull request at a head, as held asks about it. -type PullAt struct { - Pull string `json:"pull"` - Head string `json:"head"` -} - -// toolForge asks the forge's holder through its tools. -type toolForge struct { - ask func(key string, body any) (json.RawMessage, error) -} - -// Pull asks the seat `git`'s verb `pull` whether a pull request is open, and whether it merged. -func (f toolForge) Pull(owner, repo string, number int) (bool, bool, string, error) { - raw, err := f.ask(GitPullAsk, map[string]any{"repository": owner + "/" + repo, "number": number}) - if err != nil { - return false, false, "", err - } - answer, output, ok := unwrapAnswer(raw) - if !ok { - return false, false, "", fmt.Errorf("the seat git refused pull: %s", output) - } - var a struct { - Pull struct { - State string `json:"state"` - Head string `json:"head"` - } `json:"pull"` - Error string `json:"error"` - } - if err := json.Unmarshal(answer, &a); err != nil || a.Error != "" || a.Pull.State == "" { - return false, false, "", fmt.Errorf("the seat git's pull is not readable: %s", output) - } - return a.Pull.State == "open", a.Pull.State == "merged", a.Pull.Head, nil -} - -// GitPullAsk is the seat `git`'s verb that answers one pull request. -const GitPullAsk = "seat:git.pull" - -// unwrapAnswer reads a tool's answer whatever wraps it: the protocol's content list, or {output, ok, answer}. -func unwrapAnswer(raw json.RawMessage) (json.RawMessage, string, bool) { - var s string - if json.Unmarshal(raw, &s) == nil { - return unwrapAnswer(json.RawMessage(s)) - } - var m map[string]json.RawMessage - if json.Unmarshal(raw, &m) != nil { - return raw, string(raw), true - } - if content, has := m["content"]; has { - var items []struct { - Text string `json:"text"` - } - var e struct { - IsError bool `json:"isError"` - } - _ = json.Unmarshal(raw, &e) - if json.Unmarshal(content, &items) == nil && len(items) > 0 { - inner, out, ok := unwrapAnswer(json.RawMessage(items[0].Text)) - return inner, out, ok && !e.IsError - } - } - var v struct { - Output string `json:"output"` - OK *bool `json:"ok"` - Answer json.RawMessage `json:"answer"` - } - if json.Unmarshal(raw, &v) == nil && v.OK != nil { - return v.Answer, v.Output, *v.OK - } - return raw, string(raw), true -} diff --git a/modules/mesh-config/cmd/mesh-config/pulls_test.go b/modules/mesh-config/cmd/mesh-config/pulls_test.go deleted file mode 100644 index 23f0ea9b8..000000000 --- a/modules/mesh-config/cmd/mesh-config/pulls_test.go +++ /dev/null @@ -1,504 +0,0 @@ -package main - -import ( - "encoding/json" - "errors" - "strings" - "testing" - "time" - - "git.novox.be/novox/mesh-contracts/go/clients/meshconfigclient" - - occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" -) - -// Issue 1826 (novox/hq ADR 0502): a value held for the open pull request that introduces its key. - -const thePull = "novox/mesh-catalog#434" - -// n8nPullDeclares is what the controller tells of the pull request: n8n gets a required number media-gid. -func n8nPullDeclares() map[string]any { - return map[string]any{"n8n": map[string]any{"media-gid": map[string]any{"type": "number", - "description": "the media group", "required": true, "minimum": 1, "maximum": 65535}}} -} - -// aHoldingMesh is a proposing mesh with n8n assigned to ace and declaring nothing on the trunk (the case of the -// issue), and a stand-in forge. -func aHoldingMesh(t *testing.T) (*Config, *memStore, *standIn, *standForge) { - t.Helper() - c, m, r := aProposingMesh(t) - m.declare(t, "n8n", `{"module":"n8n","settings":{}}`) - m.assign(t, "ace", "n8n") - f := &standForge{state: map[string][2]bool{}} - c.Forge = f - if _, err := c.Reconcile(); err != nil { - t.Fatal(err) - } - m.events, m.handActs = nil, nil - return c, m, r, f -} - -type standForge struct { - state map[string][2]bool // pull -> open, merged - head string - err error -} - -func (f *standForge) Pull(owner, repo string, n int) (bool, bool, string, error) { - if f.err != nil { - return false, false, "", f.err - } - st, ok := f.state[(PullEvent{Owner: owner, Repo: repo, Number: n}).name()] - if !ok { - return true, false, f.head, nil - } - return st[0], st[1], f.head, nil -} - -// tell keeps what a pull request's head declares as the indexer's candidate is taken (takeCandidates). -func tell(t *testing.T, c *Config, pull, head string, declares map[string]any) *PullDeclaresAnswer { - t.Helper() - raw, _ := json.Marshal(declares) - d := map[string]map[string]Declaration{} - if err := json.Unmarshal(raw, &d); err != nil { - t.Fatal(err) - } - c.mu.Lock() - defer c.mu.Unlock() - a, err := c.declarePull(pull, head, d) - if err != nil { - t.Fatalf("declare: %v", err) - } - return a -} - -// holdIt proposes media-gid=2000 for n8n on ace held for the pull request and has the operator approve it. -func holdIt(t *testing.T, c *Config, m *memStore, r *standIn) string { - t.Helper() - a := propose(t, c, Call{Module: "n8n", Node: "ace", Key: "media-gid", Value: 2000.0, Pull: thePull, - Why: "n8n's container joins the media group, held for #434"}) - r.choose(t, a.Proposal, OptionApprove, nil) - said, err := c.Decide() - if err != nil || len(said) != 1 || !strings.Contains(said[0], "approved by the operator and held") { - t.Fatalf("the Approve decided %v (%v)", said, err) - } - return a.Proposal -} - -func keptCount(m *memStore) int { k, _ := m.Keys(KeptState); return len(k) } - -// 1826/K1: mesh-config keeps what a pull request declares per pull request; pull-declares is gone (ADR 0590). -func TestAPullRequestsDeclarationsAreKeptPerPullRequest(t *testing.T) { - c, m, _, _ := aHoldingMesh(t) - for _, caller := range []string{"g14.node-tools", Unproven, "", ControllerCaller} { - if _, err := c.Do(Call{Action: "pull-declares", Pull: thePull, Head: "abc1234", Declares: n8nPullDeclares(), - Caller: caller}); err == nil || !strings.Contains(err.Error(), "config-candidates") { - t.Errorf("pull-declares from %q: %v", caller, err) - } - } - a := tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - if len(a.Modules) != 1 || a.Modules[0] != "n8n" { - t.Errorf("answered %+v", a) - } - e, _ := m.Get(PullsState, "novox.mesh-catalog.434") - var pd PullDecl - if e == nil || json.Unmarshal(e.Value, &pd) != nil || pd.Head != "abc1234def" || - pd.Declares["n8n"]["media-gid"].Type != "number" || !pd.Declares["n8n"]["media-gid"].Required { - t.Errorf("kept %s", func() string { - if e == nil { - return "nothing" - } - return string(e.Value) - }()) - } - // Nothing is resolved from a pull request's declaration. - if r, _ := m.Get(ResolvedState, ResolvedKey("ace", "n8n", "media-gid")); r != nil { - t.Errorf("a pull request's declaration was resolved: %s", r.Value) - } -} - -// 1826/K2: a proposal for a key only the pull request declares is refused without its declaration, for a mesh or -// node level, for a clear, for an undeclared key, and for a module not placed on the node; and trunk-only -// proposals are judged as before. -func TestAProposalNamingAPullRequestIsJudgedAgainstItsDeclaration(t *testing.T) { - c, m, _, _ := aHoldingMesh(t) - try := func(call Call) error { - call.Action, call.Caller, call.Why = "propose", "g14.node-tools", "held for 434" - _, err := c.Propose(call) - return err - } - base := Call{Module: "n8n", Node: "ace", Key: "media-gid", Value: 2000.0, Pull: thePull} - if err := try(base); err == nil || !strings.Contains(err.Error(), "holds no declaration for "+thePull) { - t.Errorf("without the pull request's declaration: %v", err) - } - // And without the pull argument it is the trunk's refusal, as before. - plain := base - plain.Pull = "" - if err := try(plain); err == nil || !strings.Contains(err.Error(), `n8n declares no value "media-gid"`) { - t.Errorf("the trunk's refusal changed: %v", err) - } - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - for name, tc := range map[string]struct { - mutate func(*Call) - want string - }{ - "a mesh level": {func(c *Call) { c.Module, c.Node = "", "" }, "a module's own value on one node"}, - "a node level": {func(c *Call) { c.Module = "" }, "a module's own value on one node"}, - "a clear": {func(c *Call) { c.Clear, c.Value = true, nil }, "a clear is not held"}, - "a key not added": {func(c *Call) { c.Key = "other" }, "does not add or change a value"}, - "a bad value": {func(c *Call) { c.Value = 0.0 }, "below the minimum"}, - "a wrong type": {func(c *Call) { c.Value = "2000" }, "is not a number"}, - "another node": {func(c *Call) { c.Node = "g14" }, "is not placed on g14"}, - "another pull": {func(c *Call) { c.Pull = "novox/mesh-catalog#435" }, "holds no declaration for"}, - "a malformed pull": {func(c *Call) { c.Pull = "434" }, "owner/repository#number"}, - } { - call := base - tc.mutate(&call) - if err := try(call); err == nil || !strings.Contains(err.Error(), tc.want) { - t.Errorf("%s: %v, want %q", name, err, tc.want) - } - } - // A set or a clear through the verb takes no pull request. - if _, err := c.Change(Call{Action: "set", Module: "n8n", Node: "ace", Key: "media-gid", Value: 2000.0, Pull: thePull, - Caller: "g14.node-tools", Why: "w"}); err == nil || !strings.Contains(err.Error(), "only a proposal") { - t.Errorf("a set naming a pull request: %v", err) - } - if keptCount(m) != 0 { - t.Error("something was held") - } -} - -// 1826/K2: every held value is asked whatever the key's trust; the ask says it is held and dropped on a close; on -// Approve the value is kept apart, never set or resolved; history, event and hand-act say it; held answers it. -func TestAHeldValueIsAskedAndKeptApartOnApprove(t *testing.T) { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - a := propose(t, c, Call{Module: "n8n", Node: "ace", Key: "media-gid", Value: 2000.0, Pull: thePull, Why: "held for #434"}) - if len(a.Reaches) != 0 { - t.Errorf("a held value reaches %v", a.Reaches) - } - ask := r.asks[a.Proposal] - if err := occ.Check(ask, c.now()); err != nil { - t.Fatalf("the ask: %v", err) - } - for _, want := range []string{thePull, "merges", "dropped if it closes unmerged", "media-gid", "n8n", "ace"} { - if !strings.Contains(ask.Explanation, want) { - t.Errorf("the ask does not say %q:\n%s", want, ask.Explanation) - } - } - if strings.Contains(ask.Explanation, "takes effect at once") || !strings.Contains(ask.Headline, "Hold") { - t.Errorf("the ask: %q\n%s", ask.Headline, ask.Explanation) - } - if ap := ask.Options[0]; !strings.Contains(ap.Does, thePull) || ap.Level == "" { - t.Errorf("the approve option does %q", ap.Does) - } - if keptCount(m) != 0 { - t.Fatal("a proposal held something") - } - r.choose(t, a.Proposal, OptionApprove, nil) - said, _ := c.Decide() - if len(said) != 1 || !strings.Contains(said[0], "held at abc1234d for "+thePull) { - t.Fatalf("decided %v", said) - } - // Kept apart: not a value, not resolved. - if _, set := storedValue(t, m, "module.ace.n8n.media-gid"); set { - t.Error("an Approve set the value") - } - if e, _ := m.Get(ResolvedState, ResolvedKey("ace", "n8n", "media-gid")); e != nil { - t.Errorf("an Approve resolved the value: %s", e.Value) - } - if keptCount(m) != 1 { - t.Fatalf("%d values held", keptCount(m)) - } - if len(m.events) != 1 || m.events[0].Action != ActionHold || m.events[0].Pull != thePull || - m.events[0].Key != "media-gid" || m.events[0].Head != "abc1234def" || len(m.events[0].Moved) != 0 || - !strings.Contains(m.events[0].Approved, "approved by the operator") { - t.Errorf("raised %+v", m.events) - } - if len(m.handActs) != 1 || !strings.Contains(m.handActs[0], thePull) { - t.Errorf("hand-acts %q", m.handActs) - } - h, _ := c.History(Call{Module: "n8n", Node: "ace"}) - if len(h) != 1 || h[0].Action != ActionHold || h[0].Pull != thePull { - t.Errorf("history %+v", h) - } - // held answers it, at the head it is kept at, to the controller alone. - if _, err := c.Do(Call{Action: "held", Caller: "g14.node-tools", Pulls: []PullAt{{thePull, "abc1234def"}}}); err == nil { - t.Error("held answered a caller that is not the controller") - } - got, err := c.Do(Call{Action: "held", Caller: ControllerCaller, Pulls: []PullAt{{thePull, "abc1234def"}}}) - if err != nil { - t.Fatal(err) - } - ha := got.(*HeldAnswer) - if len(ha.Held) != 1 || ha.Held[0].Module != "n8n" || ha.Held[0].Node != "ace" || ha.Held[0].Key != "media-gid" || - string(ha.Held[0].Value) != "2000" || !strings.Contains(ha.Held[0].Approved, "approved by the operator") || - ha.Held[0].Pull != thePull || len(ha.Skipped) != 0 { - t.Errorf("held answered %+v", ha) - } - // Another head, and another pull request, are not answered. - got, _ = c.Do(Call{Action: "held", Caller: ControllerCaller, - Pulls: []PullAt{{thePull, "ffff0000"}, {"novox/mesh-catalog#435", "abc"}}}) - if ha = got.(*HeldAnswer); len(ha.Held) != 0 || len(ha.Skipped) != 1 || !strings.Contains(ha.Skipped[0].Why, "held at") { - t.Errorf("held at another head answered %+v", ha) - } - // The listing shows it as held, and the proposal as held for the pull request. - l, _ := c.List(Call{Module: "n8n"}) - if len(l.Held) != 1 || len(l.Set) != 0 { - t.Errorf("the listing: held %+v set %+v", l.Held, l.Set) - } - rows, _ := c.Proposals(Call{}) - if len(rows) != 1 || rows[0].Pull != thePull || rows[0].State != ProposalApproved { - t.Errorf("proposals %+v", rows) - } -} - -// 1826/K2: an Approve is refused when the pull request's declaration changed after the operator was shown it. -func TestAnApproveOfAHeldValueIsRefusedWhenTheDeclarationChanged(t *testing.T) { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - a := propose(t, c, Call{Module: "n8n", Node: "ace", Key: "media-gid", Value: 2000.0, Pull: thePull, Why: "w"}) - changed := n8nPullDeclares() - changed["n8n"].(map[string]any)["media-gid"].(map[string]any)["maximum"] = 1000.0 - tell(t, c, thePull, "def5678abc", changed) - r.choose(t, a.Proposal, OptionApprove, nil) - said, _ := c.Decide() - if len(said) != 1 || !strings.Contains(said[0], "nothing is held") || keptCount(m) != 0 { - t.Errorf("decided %v; %d held", said, keptCount(m)) - } -} - -// 1826/K1: at a new head a held value is kept if its key is declared the same and it still passes; otherwise it is -// dropped, recorded, raised and said. -func TestANewHeadKeepsAHeldValueOnlyWhileItsDeclarationIsUnchanged(t *testing.T) { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - m.events = nil - - // The same declaration at a new head (the description may differ): kept, moved to the new head. - same := n8nPullDeclares() - same["n8n"].(map[string]any)["media-gid"].(map[string]any)["description"] = "reworded" - if a := tell(t, c, thePull, "1111111111", same); len(a.Dropped) != 0 { - t.Errorf("an unchanged declaration dropped %v", a.Dropped) - } - got, _ := c.Do(Call{Action: "held", Caller: ControllerCaller, Pulls: []PullAt{{thePull, "1111111111"}}}) - if len(got.(*HeldAnswer).Held) != 1 || len(m.events) != 0 { - t.Errorf("after an unchanged head: %+v, events %+v", got, m.events) - } - - // A changed declaration: dropped. - changed := n8nPullDeclares() - changed["n8n"].(map[string]any)["media-gid"].(map[string]any)["maximum"] = 1000.0 - a := tell(t, c, thePull, "2222222222", changed) - if len(a.Dropped) != 1 || !strings.Contains(a.Dropped[0], "declares the key otherwise") || keptCount(m) != 0 { - t.Fatalf("a changed declaration: %+v, %d held", a, keptCount(m)) - } - if len(m.events) != 1 || m.events[0].Action != ActionDrop || m.events[0].Pull != thePull { - t.Errorf("raised %+v", m.events) - } - got, _ = c.Do(Call{Action: "held", Caller: ControllerCaller, Pulls: []PullAt{{thePull, "2222222222"}}}) - if len(got.(*HeldAnswer).Held) != 0 { - t.Error("a dropped value was answered") - } - - // A head that no longer adds the key drops it too. - tell(t, c, thePull, "3333333333", n8nPullDeclares()) - holdIt(t, c, m, r) - if a = tell(t, c, thePull, "4444444444", map[string]any{}); len(a.Dropped) != 1 || - !strings.Contains(a.Dropped[0], "no longer adds or changes") { - t.Errorf("a head without the key: %+v", a) - } -} - -// 1826/K3: the merge writes the held value as the module's own value with its approval kept, before the trunk -// declares the key; it resolves right after the declared-config mirror moves. -func TestTheMergeAppliesAHeldValueAndItResolvesOnceTheTrunkDeclaresTheKey(t *testing.T) { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - approved := func() string { - raw, _ := m.Get(KeptState, "novox.mesh-catalog.434.ace.n8n.media-gid") - // the state kept is the seat's layout, under the seat's key: the checker and the assigner read it with this - k, err := meshconfigclient.DecodeKept("novox.mesh-catalog.434.ace.n8n.media-gid", raw.Value) - if err != nil || string(heldValue(k)) != "2000" || k.Declaration == "" || k.At == nil { - t.Fatalf("the held value is not the seat's: %+v, %v", k, err) - } - return k.Approved - }() - m.events, m.handActs = nil, nil - - said := c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434, Merged: true, HeadSHA: "abc1234def"}, true) - if len(said) == 0 { - t.Fatal("the merge said nothing") - } - v, set := storedValue(t, m, "module.ace.n8n.media-gid") - if !set || string(v.Value) != "2000" || v.Approved != approved || v.Approved == "" || v.By != "the operator" || - !strings.Contains(v.Why, thePull) { - t.Fatalf("the merge wrote %+v", v) - } - if keptCount(m) != 0 { - t.Error("the value is still held after the merge") - } - if p, _ := m.Keys(PullsState); len(p) != 0 { - t.Errorf("the pull request's declarations are still kept: %v", p) - } - if len(m.events) != 1 || m.events[0].Action != "set" || m.events[0].Pull != thePull || - m.events[0].Approved != approved || len(m.handActs) != 1 { - t.Errorf("raised %+v, recorded %q", m.events, m.handActs) - } - // Not resolved before the trunk declares it. - if e, _ := m.Get(ResolvedState, ResolvedKey("ace", "n8n", "media-gid")); e != nil { - t.Errorf("resolved before the trunk declares the key: %s", e.Value) - } - m.declare(t, "n8n", `{"module":"n8n","settings":{"media-gid":{"kind":"","default":null,"why":"",`+ - `"type":"number","required":true,"minimum":1,"maximum":65535}}}`) - if _, err := c.Reconcile(); err != nil { - t.Fatal(err) - } - if res := m.resolved(t, "ace", "n8n", "media-gid"); string(res.Value) != "2000" || res.Source != SourceModule { - t.Errorf("media-gid resolves as %+v", res) - } - l, _ := c.List(Call{Module: "n8n", Node: "ace"}) - if len(l.Set) != 1 || l.Set[0].Approved != approved || len(l.Held) != 0 { - t.Errorf("the listing: set %+v held %+v", l.Set, l.Held) - } - // A merge heard twice sets nothing twice. - m.events = nil - c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434, Merged: true, HeadSHA: "abc1234def"}, true) - if len(m.events) != 0 { - t.Errorf("a second merge raised %+v", m.events) - } -} - -// 1826/K3: a pull request closed unmerged drops its held values and says so; nothing is set or resolved. -func TestAClosedPullRequestDropsItsHeldValuesAndSaysSo(t *testing.T) { - c, m, r, f := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - m.events = nil - f.state[thePull] = [2]bool{false, false} - said := c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434}, false) - if len(said) == 0 || !strings.Contains(strings.Join(said, "\n"), "closed unmerged: dropped, nothing was set") { - t.Errorf("said %v", said) - } - if _, set := storedValue(t, m, "module.ace.n8n.media-gid"); set || keptCount(m) != 0 { - t.Error("a closed pull request left a value") - } - if len(m.events) != 1 || m.events[0].Action != ActionDrop || m.events[0].Pull != thePull || - !strings.Contains(m.events[0].Why, "closed unmerged") { - t.Errorf("raised %+v", m.events) - } - if p, _ := m.Keys(PullsState); len(p) != 0 { - t.Errorf("declarations of a closed pull request kept: %v", p) - } -} - -// 1826/K3: a close event for a pull request the forge says merged is the merge. -func TestACloseEventForAMergedPullRequestIsItsMerge(t *testing.T) { - c, m, r, f := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - f.state[thePull] = [2]bool{false, true} - f.head = "abc1234def" - c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434}, false) - if v, set := storedValue(t, m, "module.ace.n8n.media-gid"); !set || string(v.Value) != "2000" { - t.Errorf("the merge of a pull request announced closed set %+v", v) - } -} - -// 1826/K3: the five-minute look finds a merge, a close, and an open pull request, and says a forge that does not -// answer. -func TestTheLookAtTheForgeFindsAMissedMergeOrCloseAndLeavesAnOpenPullRequest(t *testing.T) { - c, m, r, f := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - if said := c.SweepPulls(); len(said) != 0 || keptCount(m) != 1 { - t.Errorf("an open pull request: said %v, %d held", said, keptCount(m)) - } - f.err = errors.New("the forge is down") - if said := c.SweepPulls(); len(said) != 1 || !strings.Contains(said[0], "does not say whether") || keptCount(m) != 1 { - t.Errorf("a silent forge: said %v", said) - } - f.err = nil - f.head = "abc1234def" - f.state[thePull] = [2]bool{false, true} - c.SweepPulls() - if v, set := storedValue(t, m, "module.ace.n8n.media-gid"); !set || string(v.Value) != "2000" || keptCount(m) != 0 { - t.Errorf("a missed merge: %+v", v) - } - // A missed close. - tell(t, c, "novox/mesh-catalog#440", "abc", n8nPullDeclares()) - f.state["novox/mesh-catalog#440"] = [2]bool{false, false} - c.SweepPulls() - if p, _ := m.Keys(PullsState); len(p) != 0 { - t.Errorf("a missed close left %v", p) - } -} - -// 1826/K1: the new arguments are read strictly and the new actions are the verb's. -func TestThePullArgumentsAreRead(t *testing.T) { - call, err := callOf(map[string]any{"action": "pull-declares", "pull": " " + thePull + " ", "head": "abc", - "declares": map[string]any{"n8n": map[string]any{}}, "pulls": []any{map[string]any{"pull": thePull, "head": "h"}}}) - if err != nil || call.Pull != thePull || call.Head != "abc" || len(call.Declares) != 1 || len(call.Pulls) != 1 || - call.Pulls[0].Head != "h" { - t.Errorf("read %+v (%v)", call, err) - } - if _, err := callOf(map[string]any{"declares": "x"}); err == nil { - t.Error("declares that is not an object was read") - } - if _, err := callOf(map[string]any{"pulls": "x"}); err == nil { - t.Error("pulls that is not a list was read") - } - if _, err := callOf(map[string]any{"bogus": 1}); err == nil || !strings.Contains(err.Error(), "pull") { - t.Errorf("an unknown argument: %v", err) - } - _ = time.Second -} - -// 1826 review r1: the merge applies a value only if it is held at the merged head; otherwise it is dropped and said. -func TestTheMergeAppliesOnlyAValueHeldAtTheMergedHead(t *testing.T) { - for name, head := range map[string]string{"another head": "9999999999", "no head told": ""} { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - said := c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434, Merged: true, HeadSHA: head}, true) - if _, set := storedValue(t, m, "module.ace.n8n.media-gid"); set || keptCount(m) != 0 || - !strings.Contains(strings.Join(said, "\n"), "dropped, nothing was set") { - t.Errorf("%s: set=%v held=%d said %v", name, set, keptCount(m), said) - } - if len(m.events) == 0 || m.events[len(m.events)-1].Action != ActionDrop { - t.Errorf("%s: raised %+v", name, m.events) - } - } -} - -// 1826 review r1: a later head without the declaration drops the value, so the merge has nothing to apply. -func TestALaterHeadWithoutTheDeclarationLeavesNothingToApplyAtTheMerge(t *testing.T) { - c, m, r, _ := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - tell(t, c, thePull, "bbbbbbbbbb", map[string]any{}) - c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434, Merged: true, HeadSHA: "bbbbbbbbbb"}, true) - if _, set := storedValue(t, m, "module.ace.n8n.media-gid"); set { - t.Error("a value held for a declaration the merged head lacks was set") - } -} - -// 1826 review r1: a close the forge cannot be asked about drops nothing; the five-minute look decides. -func TestACloseThatTheForgeCannotBeAskedAboutDropsNothing(t *testing.T) { - c, m, r, f := aHoldingMesh(t) - tell(t, c, thePull, "abc1234def", n8nPullDeclares()) - holdIt(t, c, m, r) - f.err = errors.New("the forge is down") - c.HeardPull(PullEvent{Owner: "novox", Repo: "mesh-catalog", Number: 434}, false) - if keptCount(m) != 1 { - t.Fatal("a close the forge could not confirm dropped the value") - } - f.err = nil - f.state[thePull] = [2]bool{false, false} - c.SweepPulls() - if keptCount(m) != 0 { - t.Error("the look did not drop it") - } -} diff --git a/modules/mesh-config/cmd/mesh-config/quiet_integration_test.go b/modules/mesh-config/cmd/mesh-config/quiet_integration_test.go new file mode 100644 index 000000000..3070fd7e9 --- /dev/null +++ b/modules/mesh-config/cmd/mesh-config/quiet_integration_test.go @@ -0,0 +1,134 @@ +//go:build integration + +package main + +// Issue 1982, against a real bus: mesh-config whole asks the bus for nothing while no input of it changes, and a changed input +// resolves only what it touches. The binary runs as the node's tool runtime plays it (whole_integration_test.go), and every +// request it makes of the runtime is counted: what a state read, a watch and a write ask of the bus. + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" + + "git.novox.be/novox/mesh-sdk/go/testbus" +) + +func (p *player) snapshot() (calls map[string]int, puts []string) { + p.mu.Lock() + defer p.mu.Unlock() + calls = map[string]int{} + for k, v := range p.calls { + calls[k] = v + } + return calls, slices.Clone(p.puts) +} + +// asked is how many requests of these methods the module made between two snapshots. +func asked(before, after map[string]int, methods ...string) int { + n := 0 + for _, m := range methods { + n += after[m] - before[m] + } + return n +} + +func TestConfigWholeAsksTheBusForNothingWhileNoInputChanges(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + bin := filepath.Join(t.TempDir(), Module) + build := exec.Command("go", "build", "-o", bin, ".") + build.Stderr = os.Stderr + if err := build.Run(); err != nil { + t.Fatalf("mesh-config does not build: %v", err) + } + nc, err := nats.Connect(testbus.URL(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(nc.Close) + js, err := jetstream.New(nc) + if err != nil { + t.Fatal(err) + } + buckets := []string{"mesh-delivery-assigner_assignments", "mesh-delivery-assigner_wants", "mesh-delivery-indexer_predefined"} + for _, s := range []string{ValuesState, ResolvedState, PredefinedState, ProposalsState, DeclaredState, + RenamesState, RetiringState, FindingsState} { + buckets = append(buckets, Module+"_"+s) + } + for _, b := range buckets { + if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b, History: 2}); err != nil { + t.Fatal(err) + } + } + haves := map[string]string{"g14.player": fpOf("player", fp1), "novox.player": fpOf("player", fp1), "g14.radio": fpOf("radio", fp1)} + p := start(t, bin, js, newStandIn(), haves, nil) + p.viewsReady() + + const radio = `{"module":"radio","config":{"band":{"type":"number","default":1}}}` + p.manifestIn("player", oldPlayer) + p.manifestIn("radio", radio) + p.buildIn("g14", "player", fpOf("player", fp1), oldPlayer) + p.buildIn("novox", "player", fpOf("player", fp1), oldPlayer) + p.buildIn("g14", "radio", fpOf("radio", fp1), radio) + p.placed("g14", "player", "radio") + p.placed("novox", "player") + p.hearsTheViews() + eventually(t, "every value is resolved", func() bool { + a, okA := resolvedValue(p, "g14", "player", "volume") + b, okB := resolvedValue(p, "novox", "player", "volume") + c, okC := resolvedValue(p, "g14", "radio", "band") + return okA && okB && okC && a == "5" && b == "5" && c == "1" + }) + // The passes the setup moved have ended when the module answers a tool: it takes its lock for none. + if _, err := p.call(ResyncTool, nil); err != nil { + t.Fatal(err) + } + + // No input changes: the delivery says it delivered and a node-engine says what it reads, with no rename window open and no retirement + // waiting. Each is heard and none is a pass: nothing is asked of the bus. (The module has no polling timer; its one deadline + // timer is set for a real deadline, and none is near.) + before, putsBefore := p.snapshot() + for i := 0; i < 20; i++ { + p.event("mesh-delivery-view.delivered", map[string]any{"revision": "r"}) + p.event("node-engine.manifest-reads-changed", map[string]any{"node": "g14"}) + } + after, putsAfter := p.snapshot() + p.noGitAsk() + if n := asked(before, after, "mesh/state.get", "mesh/state.keys", "mesh/state.watch", "mesh/state.put", "mesh/state.create", + "mesh/state.update", "mesh/state.delete", "mesh/ask"); n != 0 || len(putsAfter) != len(putsBefore) { + t.Errorf("40 events that move nothing asked %d requests of the bus (%v); wrote %v", n, after, putsAfter[len(putsBefore):]) + } + + // One input changes: player's manifest declares a second value. Only player's values on its two nodes are written, and `declared` + // for player; radio's resolved values are not written again, and nothing is read key by key. + before, putsBefore = p.snapshot() + const gain = `{"module":"player","config":{"volume":{"type":"number","default":5},"gain":{"type":"number","default":2}}}` + p.manifestIn("player", gain) + eventually(t, "the new value is resolved on both nodes", func() bool { + a, okA := resolvedValue(p, "g14", "player", "gain") + b, okB := resolvedValue(p, "novox", "player", "gain") + return okA && okB && a == "2" && b == "2" + }) + after, putsAfter = p.snapshot() + var wrote []string + for _, w := range putsAfter[len(putsBefore):] { + wrote = append(wrote, strings.TrimPrefix(w, "mesh/state.")) + } + for _, w := range wrote { + if !strings.Contains(w, ResolvedState+"/g14.player.") && !strings.Contains(w, ResolvedState+"/novox.player.") && + !strings.Contains(w, DeclaredState+"/player") { + t.Errorf("a changed manifest of player wrote %q, which is not player's", w) + } + } + if n := asked(before, after, "mesh/state.get", "mesh/state.keys", "mesh/state.watch"); n != 0 { + t.Errorf("a changed manifest read %d keys of the bus's states one by one (%v)", n, after) + } +} diff --git a/modules/mesh-config/cmd/mesh-config/quiet_test.go b/modules/mesh-config/cmd/mesh-config/quiet_test.go new file mode 100644 index 000000000..77861b841 --- /dev/null +++ b/modules/mesh-config/cmd/mesh-config/quiet_test.go @@ -0,0 +1,378 @@ +package main + +// What mesh-config asks of the bus per input (issue 1982): its own states are read from the copy their watches keep, an event +// that moves nothing reads nothing, and the one timer left is a deadline. + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" + oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" + stdio "git.novox.be/novox/mesh-sdk/go" +) + +// countingStore counts the reads of the states by state: what the bus would be asked. +type countingStore struct { + *memStore + mu sync.Mutex + reads map[string]int +} + +func (s *countingStore) Get(state, key string) (*Entry, error) { + s.mu.Lock() + s.reads[state]++ + s.mu.Unlock() + return s.memStore.Get(state, key) +} + +func (s *countingStore) Keys(state string) ([]string, error) { + s.mu.Lock() + s.reads[state]++ + s.mu.Unlock() + return s.memStore.Keys(state) +} + +// readsOf is the reads of every state but those named. +func (s *countingStore) readsExcept(states ...string) map[string]int { + s.mu.Lock() + defer s.mu.Unlock() + out := map[string]int{} + for k, n := range s.reads { + out[k] = n + } + for _, k := range states { + delete(out, k) + } + return out +} + +// **An event that moves nothing reads nothing but what it judges** (design 32 *A config value renamed*, *A value no longer +// read*): with no rename window open, `delivered` and `manifest-reads-changed` read no source, and a `manifest-accepted` +// whose rows are all marked or read again reads none either. Each was a read of every key of every state of the module +// (about 4,000 requests) under a delivery's burst of events. +func TestAnEventThatMovesNothingReadsNoSource(t *testing.T) { + c, m, d, _, _, _ := retiringMesh(t) + cs := &countingStore{memStore: m, reads: map[string]int{}} + c.Store = cs + d.rows = []ReaderRow{{Module: "player", Key: "volume", Kind: KindValue, Readers: []string{"g14"}}} // read: nothing to retire + for name, event := range map[string]func(){ + "delivered": func() { c.Windows("") }, + "manifest-reads-changed": func() { c.Windows("g14") }, + "manifest-accepted": func() { c.Retirements("player") }, + } { + cs.reads = map[string]int{} + event() + if got := cs.readsExcept(RenamesState, RetiringState); len(got) != 0 { + t.Errorf("%s read %v", name, got) + } + } +} + +// An open window is judged, and reads what judging it needs: the same event with a window open reads the sources. +func TestAnEventWithAWindowOpenJudgesIt(t *testing.T) { + c, m, _, _ := aRenamingMesh(t) + m.declare(t, "player", newPlayer) + if _, err := c.Reconcile(); err != nil { + t.Fatal(err) + } + cs := &countingStore{memStore: m, reads: map[string]int{}} + c.Store = cs + c.Windows("") + if cs.reads[ValuesState] == 0 { + t.Errorf("an open window was judged on no source: %v", cs.reads) + } +} + +// **An ask of a retirement that ends with no choice is taken when the router says so** (design 32 *A value no longer read*): +// with no minute's look at the router's record, the `decided` event of an ask that expired moves the retirement. +func TestARetirementWhoseAskExpiredIsTakenOnTheRoutersWord(t *testing.T) { + c, m, d, r, _, _ := retiringMesh(t) + for _, node := range []string{"g14", "novox"} { + m.want(t, node, "player", fp3, donePlayer) + d.haves[node+".player"] = fp3 + } + c.Windows("") + c.Retirements("player") + rows := retiringOf(t, c) + if len(rows) != 1 || rows[0].State != RetireAsked { + t.Fatalf("retiring %+v, want asked", rows) + } + r.choose(t, rows[0].Ask, OptionApprove, func(w *oc.Warrant) { w.Outcome = occ.OutcomeExpired }) + c.HeardEnd(oc.Warrant{Ask: rows[0].Ask, Asker: Module, Outcome: occ.OutcomeExpired}) + if rows = retiringOf(t, c); rows[0].State != RetireUnanswered { + t.Errorf("after the router said the ask expired: %+v", rows) + } +} + +// The next deadline is the earliest of a waiting proposal's (an hour past its ask lapsing, with no record at the router) +// and an unanswered retirement's (asked once more after HeldFinding); none when nothing waits on a time. +func TestTheNextDeadlineIsTheEarliestOfWhatWaitsOnATime(t *testing.T) { + m := newStore() + c := &Config{Store: m, Catalog: m, Logf: t.Logf} + if _, ok := c.NextDeadline(); ok { + t.Fatal("a deadline with nothing waiting") + } + t0 := time.Date(2026, 11, 19, 10, 0, 0, 0, time.UTC) + put := func(state, key string, v any) { + if err := m.Put(state, key, v); err != nil { + t.Fatal(err) + } + } + put(ProposalsState, "p1", Proposal{ID: "p1", State: ProposalWaiting, At: t0.Add(48 * time.Hour)}) + put(ProposalsState, "p2", Proposal{ID: "p2", State: ProposalEnded, At: t0}) + want := t0.Add(48*time.Hour + ProposalLasts + time.Hour) + if at, ok := c.NextDeadline(); !ok || !at.Equal(want) { + t.Errorf("deadline %v, %v; want %v", at, ok, want) + } + put(RetiringState, "player.volume", Retiring{Module: "player", Key: "volume", State: RetireUnanswered, Asked: t0.Add(-6 * 24 * time.Hour)}) + want = t0.Add(HeldFinding - 6*24*time.Hour) + if at, ok := c.NextDeadline(); !ok || !at.Equal(want) { + t.Errorf("deadline %v, %v; want the retirement's %v", at, ok, want) + } +} + +// busOf is a bus of states for the copy's tests: what each state holds, the watches handed out and the requests asked. +type busOf struct { + mu sync.Mutex + held map[string]map[string][]byte + handles map[string]func(stdio.StateChange) error + watches int + gets int + writes int + revision uint64 +} + +func (b *busOf) ownCopy() *ownCopy { + return &ownCopy{ + copy: stdio.WatchedStatesOver(func(state string, handle func(stdio.StateChange) error) error { + b.mu.Lock() + b.watches++ + b.handles[state] = handle + current := map[string][]byte{} + for k, v := range b.held[state] { + current[k] = v + } + b.mu.Unlock() + for k, v := range current { + if err := handle(stdio.StateChange{State: state, Key: k, Op: stdio.OpPut, Value: v, Revision: 1, Current: true}); err != nil { + return err + } + } + return nil + }, func(state, key string) ([]byte, bool, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.gets++ + v, ok := b.held[state][key] + return v, ok, nil + }), + put: func(state, key string, value any) (uint64, error) { + raw, _ := json.Marshal(value) + b.mu.Lock() + defer b.mu.Unlock() + b.writes++ + b.revision++ + if b.held[state] == nil { + b.held[state] = map[string][]byte{} + } + b.held[state][key] = raw + return b.revision + 1, nil + }, + del: func(state, key string) error { + b.mu.Lock() + defer b.mu.Unlock() + b.writes++ + delete(b.held[state], key) + return nil + }} +} + +// **The module's own states are read from a copy, never key by key** (ADR 0580 §1, issue 1982): a whole state read of 1,176 +// keys is one watch and no get, again and again; this process's write is in the copy at once, another's arrives by the watch. +func TestAnOwnStateIsReadFromItsWatchedCopyNotKeyByKey(t *testing.T) { + b := &busOf{held: map[string]map[string][]byte{ValuesState: {}}, handles: map[string]func(stdio.StateChange) error{}} + for i := 0; i < 1176; i++ { + b.held[ValuesState]["mesh.key-"+time.Duration(i).String()] = []byte(`{"value":1}`) + } + n := len(b.held[ValuesState]) + own := b.ownCopy() + for pass := 0; pass < 3; pass++ { + keys, err := own.keys(ValuesState) + if err != nil || len(keys) != n { + t.Fatalf("keys %d, %v; want %d", len(keys), err, n) + } + for _, k := range keys { + if e, err := own.get(ValuesState, k); err != nil || e == nil { + t.Fatalf("get %s: %v, %v", k, e, err) + } + } + } + if b.watches != 1 || b.gets != 0 { + t.Errorf("3 passes over %d keys asked the bus for %d watches and %d gets; want 1 and 0", n, b.watches, b.gets) + } + // Its own write and removal are in the copy at once. + if err := own.write(ValuesState, "mine", map[string]string{"x": "mine"}); err != nil { + t.Fatal(err) + } + if e, _ := own.get(ValuesState, "mine"); e == nil { + t.Error("a key just written is not read") + } + if err := own.remove(ValuesState, "mine"); err != nil { + t.Fatal(err) + } + if e, _ := own.get(ValuesState, "mine"); e != nil { + t.Error("a key just removed is still read") + } + // Another writer's change arrives by the watch. + if err := b.handles[ValuesState](stdio.StateChange{State: ValuesState, Key: "theirs", Op: stdio.OpPut, Value: []byte(`{"value":2}`), Revision: 99}); err != nil { + t.Fatal(err) + } + if e, _ := own.get(ValuesState, "theirs"); e == nil { + t.Error("a change another wrote is not read") + } + if b.gets != 0 { + t.Errorf("%d gets", b.gets) + } +} + +// A write and a removal tell what waits on a deadline, once each. +func TestAWriteTellsWhatWaitsOnADeadline(t *testing.T) { + b := &busOf{held: map[string]map[string][]byte{}, handles: map[string]func(stdio.StateChange) error{}} + own := b.ownCopy() + var told []string + own.changed = func(state string) { told = append(told, state) } + if err := own.write(ProposalsState, "p", Proposal{ID: "p"}); err != nil { + t.Fatal(err) + } + if err := own.remove(ProposalsState, "p"); err != nil { + t.Fatal(err) + } + if len(told) != 2 || told[0] != ProposalsState { + t.Errorf("told %v", told) + } +} + +// The mesh knows no pull request (design 47 G; ADR 0502 ended by the operator's word, record pending): the verb takes no `pull`, +// `head`, `declares` or `pulls`, and does neither `pull-declares` nor `held`. +func TestTheVerbKnowsNoPullRequest(t *testing.T) { + for _, arg := range []string{"pull", "head", "declares", "pulls"} { + if _, err := callOf(map[string]any{"action": "propose", arg: "x"}); err == nil || !strings.Contains(err.Error(), arg) { + t.Errorf("an argument %s was taken: %v", arg, err) + } + } + c, _ := aMesh(t) + for _, action := range []string{"pull-declares", "held"} { + if _, err := c.Do(Call{Action: action}); err == nil || !strings.Contains(err.Error(), action) { + t.Errorf("the action %s was done: %v", action, err) + } + } +} + +// The deadline timer's floor is the setting deadline-floor-seconds, the default for a value that is not a positive number. +func TestTheDeadlineFloorIsTheSettingOrItsDefault(t *testing.T) { + for _, c := range []struct { + raw string + err error + want time.Duration + }{ + {`5`, nil, 5 * time.Second}, {`0`, nil, DefaultDeadlineFloor}, {`"x"`, nil, DefaultDeadlineFloor}, + {``, errors.New("not declared"), DefaultDeadlineFloor}, {`90`, nil, 90 * time.Second}, + } { + if got := floorOf(json.RawMessage(c.raw), c.err); got != c.want { + t.Errorf("floor of %q (%v) = %v, want %v", c.raw, c.err, got, c.want) + } + } +} + +// **A rename window held seven days comes as a finding in a quiet mesh** (lead answer A-490l): the deadline is the window's +// seventh day, the finding is written at it with no resolution pass, and a window that is not yet seven days old writes none. +func TestAHeldWindowIsAFindingAtItsDeadlineWithNoPass(t *testing.T) { + c, m, _, clock := aRenamingMesh(t) + m.declare(t, "player", newPlayer) + if _, err := c.Reconcile(); err != nil { + t.Fatal(err) + } + at, ok := c.NextDeadline() + if !ok || !at.Equal(clock.Add(HeldFinding)) { + t.Fatalf("deadline %v, %v; want the window's seventh day %v", at, ok, clock.Add(HeldFinding)) + } + if err := c.JudgeHeldWindows(); err != nil || len(findingsOf(t, m, FindingWindowHeld)) != 0 { + t.Fatalf("a young window wrote a finding (%v)", err) + } + *clock = at + cs := &countingStore{memStore: m, reads: map[string]int{}} + c.Store = cs + if err := c.JudgeHeldWindows(); err != nil { + t.Fatal(err) + } + if fs := findingsOf(t, m, FindingWindowHeld); len(fs) != 2 { + t.Errorf("findings %+v, want one for each node holding the window", fs) + } + if got := cs.readsExcept(RenamesState); len(got) != 0 { + t.Errorf("judging the held windows read %v", got) + } + if _, ok := c.NextDeadline(); ok { + t.Error("a deadline is still set once the finding is written") + } +} + +// A write of a proposal, a retirement or a rename window sets the deadline timer again, and no other state does: a window opened +// after start, with nothing else waiting on a time, must not leave the timer blocked (A-490l). +func TestAWriteOfARenameWindowRearmsTheDeadlineTimer(t *testing.T) { + for state, want := range map[string]bool{ProposalsState: true, RetiringState: true, RenamesState: true, + ValuesState: false, ResolvedState: false, DeclaredState: false} { + if got := armsDeadline(state); got != want { + t.Errorf("a write of %s arms the timer: %v, want %v", state, got, want) + } + } + // Wired as main wires it: the copy's write of a window tells the channel the timer waits on. + b := &busOf{held: map[string]map[string][]byte{}, handles: map[string]func(stdio.StateChange) error{}} + own := b.ownCopy() + rearm := make(chan struct{}, 1) + own.changed = func(state string) { + if armsDeadline(state) { + select { + case rearm <- struct{}{}: + default: + } + } + } + if err := own.write(RenamesState, "player.level", Rename{Module: "player"}); err != nil { + t.Fatal(err) + } + select { + case <-rearm: + default: + t.Error("a rename window written after start did not rearm the timer") + } +} + +// CONFIG-1/AC1 (design 47 H §763, §764; H-A-49): mesh-config consumes no pull request event and no `manifest-accepted`, +// calls no `git.pull`, and judges the retirements of each module a `catalog-revision` names changed. +func TestARetirementIsJudgedOnACatalogRevisionAndNoPullIsHeard(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + for _, gone := range []string{`"git.pull-merged"`, `"git.pull-closed"`, `"seat:git.pull"`, `"mesh-catalog.manifest-accepted"`} { + if strings.Contains(string(raw), gone) { + t.Errorf("the manifest still names %s", gone) + } + } + c, _, d, _, _, _ := retiringMesh(t) + d.known = false + said := catalogRevisionRetirements(c, []byte(`{"v":1,"revision":4,"kind":"trunk","branch":"main","changed":["player","radio"]}`)) + if len(said) != 2 || !strings.Contains(said[0], "player") || !strings.Contains(said[1], "radio") { + t.Fatalf("a catalog revision naming player and radio judged %q", said) + } + if got := catalogRevisionRetirements(c, []byte(`{"v":1,"revision":5,"kind":"trunk","branch":"main"}`)); len(got) != 0 { + t.Fatalf("a revision naming no module judged %q", got) + } +} diff --git a/modules/mesh-config/cmd/mesh-config/renames.go b/modules/mesh-config/cmd/mesh-config/renames.go index f7338a38a..f82a03879 100644 --- a/modules/mesh-config/cmd/mesh-config/renames.go +++ b/modules/mesh-config/cmd/mesh-config/renames.go @@ -293,14 +293,26 @@ func (c *Config) Windows(node string) []string { return said } +// windowOpen says whether any rename holds a window open on the node named, or on any node when none is named. +func windowOpen(renames map[string]Rename, only string) bool { + for _, r := range renames { + for _, node := range r.Open() { + if only == "" || only == node { + return true + } + } + } + return false +} + // closeWindows is Windows' rename half; the caller holds the lock. func (c *Config) closeWindows(only string) []string { renames, err := c.readRenames() if err != nil { return []string{"the renames cannot be read: " + err.Error()} } - if c.Delivery == nil { - return nil + if c.Delivery == nil || !windowOpen(renames, only) { + return nil // no window to judge: the delivery's word moves nothing, and no source is read for it (issue 1982) } s, err := c.sources() if err != nil { @@ -475,6 +487,20 @@ func (c *Config) RenameClose(module, to, node, why string) (any, error) { return map[string]any{"closed": node, "open": r.Open()}, nil } +// JudgeHeldWindows writes the finding of each window held open past HeldFinding, and clears one that is not, from the renames +// kept: run at start and at the deadline the next window reaches (NextDeadline), so the finding comes in a quiet mesh too (lead +// answer A-490l); it reads no source and asks nothing. +func (c *Config) JudgeHeldWindows() error { + c.mu.Lock() + defer c.mu.Unlock() + renames, err := c.readRenames() + if err != nil { + return err + } + c.sweepRenameFindings(&Sources{Renames: renames}, c.now()) + return nil +} + // sweepRenameFindings writes a finding for each window held open past HeldFinding, naming the node, and clears one // whose window closed. func (c *Config) sweepRenameFindings(s *Sources, now time.Time) { diff --git a/modules/mesh-config/cmd/mesh-config/resolve.go b/modules/mesh-config/cmd/mesh-config/resolve.go index 93cd8191d..070383dff 100644 --- a/modules/mesh-config/cmd/mesh-config/resolve.go +++ b/modules/mesh-config/cmd/mesh-config/resolve.go @@ -140,10 +140,6 @@ type Sources struct { Unresolved []Unresolved Predefined map[string]Published Values map[string]Value - // Pulls is what the controller told of each open pull request's declarations, and Kept the approved values held - // for them (pulls.go); neither is resolved. - Pulls map[string]PullDecl - Kept map[string]KeptValue // Renames are the renames kept, by `.`, whose open windows answer the old name (renames.go). Renames map[string]Rename } diff --git a/modules/mesh-config/cmd/mesh-config/retiring.go b/modules/mesh-config/cmd/mesh-config/retiring.go index 6f6bd2c16..bc28fc157 100644 --- a/modules/mesh-config/cmd/mesh-config/retiring.go +++ b/modules/mesh-config/cmd/mesh-config/retiring.go @@ -3,7 +3,7 @@ package main // A value no longer read (novox/hq ADR 0609, design 32 *A value no longer read*). // // A config value or secret that no manifest on any trunk reads any more is a **retiring value**. mesh-config learns it -// from the indexer's tool `indexer_config_readers`, asked on each of the indexer's `manifest-accepted` (Retirements); +// from the indexer's tool `indexer_config_readers`, asked for each module a `catalog-revision` names changed (Retirements); // a tool the indexer does not serve yet answers "not known" and nothing retires. A value is marked retiring only once no // node-engine reports applied a build that reads it (State draining until then, judged again on each `delivered`); // mesh-config then says `retiring` and asks the operator once, through the operator channel, whether to remove it. It is @@ -148,9 +148,15 @@ func (c *Config) Retirements(module string) []string { if err != nil { return []string{"the retirements cannot be read: " + err.Error()} } - s, err := c.sources() - if err != nil { - return []string{"the retirements cannot be judged: " + err.Error()} + // The sources are read only when a row is one to judge: a row already marked, or read again, needs none (issue 1982). + var s Sources + for _, row := range rows { + if _, has := held[retiringKey(module, row.Key)]; (row.Module == "" || row.Module == module) && (len(row.Readers) == 0 && !has) { + if s, err = c.sources(); err != nil { + return []string{"the retirements cannot be judged: " + err.Error()} + } + break + } } var said []string for _, row := range rows { diff --git a/modules/mesh-config/cmd/mesh-config/sources.go b/modules/mesh-config/cmd/mesh-config/sources.go index 6a05643c7..a63d1e914 100644 --- a/modules/mesh-config/cmd/mesh-config/sources.go +++ b/modules/mesh-config/cmd/mesh-config/sources.go @@ -51,9 +51,6 @@ func (c *Config) sources() (Sources, error) { }); err != nil { return s, fmt.Errorf("the values cannot be read: %w", err) } - if err := c.readPulls(&s); err != nil { - return s, err - } if renames, err := c.readRenames(); err != nil { return s, fmt.Errorf("the renames cannot be read: %w", err) } else { @@ -339,10 +336,8 @@ type Resolution struct { Moved []Moved `json:"moved"` Published string `json:"published,omitempty"` Withheld string `json:"withheld,omitempty"` - // Declared are the modules whose `declared` key was written, and Candidates what the indexer's config candidates - // did after the take-over. - Declared []string `json:"declared,omitempty"` - Candidates []string `json:"candidates,omitempty"` + // Declared are the modules whose `declared` key was written. + Declared []string `json:"declared,omitempty"` // Renamed is what the renames did in this pass. Renamed []string `json:"renamed,omitempty"` // SourceGone is said while the stored switch still names the controller, whose records are no longer read. @@ -383,9 +378,6 @@ func (c *Config) reconcileLocked() (Resolution, error) { } else if len(written) > 0 { r.Declared = written } - if sw, serr := c.source(); serr == nil && sw.Source == SourceIndexer { - r.Candidates = c.takeCandidates() - } return r, err } diff --git a/modules/mesh-config/cmd/mesh-config/switch_tools.go b/modules/mesh-config/cmd/mesh-config/switch_tools.go index f4de6e738..37dec9a14 100644 --- a/modules/mesh-config/cmd/mesh-config/switch_tools.go +++ b/modules/mesh-config/cmd/mesh-config/switch_tools.go @@ -39,7 +39,7 @@ func ownSwitchTools(c *Config) []stdio.Tool { }}, {Name: ResyncTool, Description: "Read every source again and write what differs: the published list of predefined keys, the " + - "resolved values, declared, and the indexer's config candidates.", + "resolved values and declared.", Run: func(map[string]any) (any, error) { return c.Resync() }}, {Name: RenamesTool, Description: "Each config value renamed (renamed-from): from which name to which, when, the nodes its value " + diff --git a/modules/mesh-config/cmd/mesh-config/takeover.go b/modules/mesh-config/cmd/mesh-config/takeover.go index cc22ce6d4..f08bb27dd 100644 --- a/modules/mesh-config/cmd/mesh-config/takeover.go +++ b/modules/mesh-config/cmd/mesh-config/takeover.go @@ -2,7 +2,7 @@ package main // Config's records out of the controller (novox/hq ADR 0565 §3, §15, and the progressive insight of 2026-10-29): // mesh-config keeps each placed module's declarations in its own state `declared`, reads the list of predefined keys -// from the indexer's `predefined` and a pull request's config from the indexer's `config-candidates`. +// from the indexer's `predefined`. A pull request's config is not read: the mesh knows no pull request (design 47 G). // // **Its own sources hold always** (ADR 0590, issue 1126): the controller ended by its unassignment, so its pull-declares, // the take-over that switched away from them, compare and hand-back are gone, and the switch is the indexer's whatever @@ -23,12 +23,11 @@ const ( // DeclaredState is each placed module's declarations at the trunk, one key per module (ADR 0565 §3). DeclaredState = "declared" - // IndexerPredefinedRead and CandidatesRead are the indexer's states (ADR 0565 §2). + // IndexerPredefinedRead is the indexer's state of the predefined list (ADR 0565 §2). IndexerPredefinedRead = indexerModule + "." + catalog.StatePredefined - CandidatesRead = indexerModule + "." + catalog.StateConfigCandidates ) -// SourceIndexer is the one source of a pull request's config and of the predefined list: the indexer's. +// SourceIndexer is the one source of the predefined list: the indexer's. const SourceIndexer = "indexer" // Switch is which source holds: the indexer's, always, since the controller ended (ADR 0590). @@ -105,7 +104,7 @@ func (c *Config) writeDeclared(s Sources) ([]string, error) { return written, errors.Join(problems...) } -// ---- the predefined list and the pull requests from the indexer ------------------------------------------ +// ---- the predefined list from the indexer ----------------------------------------------------------------------------------------- // indexerList is the indexer's predefined list as the mirror's list holds one: the keys, and the commit. func (c *Config) indexerList() (PredefinedList, bool, error) { @@ -128,75 +127,6 @@ func (c *Config) indexerList() (PredefinedList, bool, error) { return list, true, nil } -// candidates is every open pull request's config declarations as the indexer keeps them, by pull key. -func (c *Config) candidates() (map[string]PullDecl, error) { - out := map[string]PullDecl{} - err := c.each(CandidatesRead, func(key string, raw []byte) error { - var cand catalog.ConfigCandidatesByPullValue - if err := json.Unmarshal(raw, &cand); err != nil || cand.Pull == "" { - return fmt.Errorf("the indexer's config candidate %s is not one", key) - } - p := PullDecl{Pull: cand.Pull, Head: cand.Head, Declares: map[string]map[string]Declaration{}, At: timeOf(cand.At)} - for module, keys := range cand.Declares { - raw, _ := json.Marshal(keys) - var d map[string]Declaration - if err := json.Unmarshal(raw, &d); err != nil { - return fmt.Errorf("the indexer's config candidate %s declares %s unreadably", key, module) - } - for k, decl := range d { - if !decl.HasDefault() { - decl.Default = nil - } - d[k] = decl - } - p.Declares[module] = d - } - out[pullKey(cand.Pull)] = p - return nil - }) - return out, err -} - -// takeCandidates is the indexer's config candidates taken in place of pull-declares, after the take-over: each one -// whose head or declarations differ from what `pulls` holds is declared again, its held values judged again (ADR 0502 -// §6). The caller holds the lock. -func (c *Config) takeCandidates() []string { - cands, err := c.candidates() - if err != nil { - return []string{"the indexer's config candidates cannot be read: " + err.Error()} - } - var s Sources - if err := c.readPulls(&s); err != nil { - return []string{err.Error()} - } - var said []string - for _, k := range sortedKeys(cands) { - p := cands[k] - if have, ok := s.Pulls[k]; ok && have.Head == p.Head && declaresDigest(have.Declares) == declaresDigest(p.Declares) { - continue - } - a, err := c.declarePull(p.Pull, p.Head, p.Declares) - if err != nil { - said = append(said, fmt.Sprintf("%s from the indexer: %v", p.Pull, err)) - continue - } - said = append(said, a.Said+" (from the indexer)") - } - return said -} - -// declaresDigest is what a pull request's declarations hold a value to, in one encoding. -func declaresDigest(d map[string]map[string]Declaration) string { - flat := map[string]string{} - for m, keys := range d { - for k, decl := range keys { - flat[m+"."+k] = declDigest(decl) - } - } - raw, _ := json.Marshal(flat) - return string(raw) -} - // Declared is the read of `declared`: every module's key, or one whole. func (c *Config) Declared(module string) (any, error) { if module != "" { @@ -221,20 +151,14 @@ func (c *Config) Declared(module string) (any, error) { return map[string]any{"declared": rows, "count": len(rows), "source": sw}, err } -// Resync reads every source again and writes what differs: the published list, the resolved values, `declared`, and -// the indexer's config candidates (ADR 0565 §15). +// Resync reads every source again and writes what differs: the published list, the resolved values and `declared` +// (ADR 0565 §15). func (c *Config) Resync() (any, error) { r, err := c.Reconcile() if err != nil { return r, err } - c.mu.Lock() - defer c.mu.Unlock() - out := map[string]any{"resolution": r} - if sw, err := c.source(); err == nil && sw.Source == SourceIndexer { - out["candidates"] = c.takeCandidates() - } - return out, nil + return map[string]any{"resolution": r}, nil } // timeOf is an optional time of a seat's value as a time, the zero time when it is absent. diff --git a/modules/mesh-config/cmd/mesh-config/takeover_test.go b/modules/mesh-config/cmd/mesh-config/takeover_test.go index 4f5d6bd62..e05fd48ea 100644 --- a/modules/mesh-config/cmd/mesh-config/takeover_test.go +++ b/modules/mesh-config/cmd/mesh-config/takeover_test.go @@ -15,7 +15,7 @@ const ( oldDeclared = `{"module":"old","settings":{"workers":{"kind":"preference","default":4,"why":"two per core"}}}` ) -// anAgreeingMesh is aProposingMesh with the indexer's predefined list in place and no open pull request. +// anAgreeingMesh is aProposingMesh with the indexer's predefined list in place. func anAgreeingMesh(t *testing.T) (*Config, *memStore, *standIn) { t.Helper() c, m, r := aProposingMesh(t) @@ -34,19 +34,9 @@ func indexerList(t *testing.T, m *memStore, commit, list string) { m.mirror(t, IndexerPredefinedRead, catalog.PredefinedByListKey(), string(raw)) } -// candidate is the indexer's config candidate of a pull request. -func candidate(t *testing.T, m *memStore, pull, head, declares string) { - t.Helper() - key, err := catalog.ConfigCandidatesByPullKey(pullKey(pull)), error(nil) - if err != nil { - t.Fatal(err) - } - m.mirror(t, CandidatesRead, key, `{"v":1,"pull":"`+pull+`","head":"`+head+`","declares":`+declares+`}`) -} - // ADR 0590 (issue 1126): config reads its own sources always, with no take-over: declared is written once per -// manifest, pull-declares is refused naming the indexer's candidates, and the list and a pull request's config come from -// the indexer. compare, take-over and hand-back went with the controller. +// manifest, and the list comes from the indexer. compare, take-over, hand-back and a pull request's config went (the +// mesh knows no pull request, design 47 G). func TestConfigReadsItsOwnSourcesAlways(t *testing.T) { c, m, _ := anAgreeingMesh(t) steps := []struct { @@ -60,11 +50,6 @@ func TestConfigReadsItsOwnSourcesAlways(t *testing.T) { again, _ := c.Reconcile() return strings.Join(first.Declared, ",") + "|" + strings.Join(again.Declared, ","), err }, "dunst|"}, - {"pull-declares refused, naming the indexer", func() (string, error) { - _, err := c.PullDeclares(Call{Caller: ControllerCaller, Pull: "novox/mesh-catalog#8", Head: "h1", - Declares: map[string]any{}}) - return "", err - }, "config-candidates"}, {"the list comes from the indexer", func() (string, error) { indexerList(t, m, "cccccccccccc", `{"font-size":{"type":"number","description":"text size","minimum":6,"maximum":72}, "agent-managed-settings":{"type":"object","description":"managed settings","trusted":true}, @@ -72,11 +57,6 @@ func TestConfigReadsItsOwnSourcesAlways(t *testing.T) { res, err := c.Reconcile() return res.Published, err }, "theme"}, - {"a pull request's config comes from the indexer", func() (string, error) { - candidate(t, m, "novox/mesh-catalog#9", "h9", `{"dunst":{"gap":{"kind":"","type":"number","default":2}}}`) - res, err := c.Reconcile() - return strings.Join(res.Candidates, "; "), err - }, "from the indexer"}, } for _, s := range steps { got, err := s.do() diff --git a/modules/mesh-config/cmd/mesh-config/whole_integration_test.go b/modules/mesh-config/cmd/mesh-config/whole_integration_test.go index 9cc30a578..1609cda12 100644 --- a/modules/mesh-config/cmd/mesh-config/whole_integration_test.go +++ b/modules/mesh-config/cmd/mesh-config/whole_integration_test.go @@ -81,6 +81,12 @@ type player struct { catalog map[string]catalog.CatalogEntry byFp map[string]catalog.CatalogEntry catRev int64 + // calls counts what the module asked of the runtime, by method (and by key for an ask); puts are the keys it wrote, "/". + calls map[string]int + asks map[string]int // the asks of tools and seat verbs, by key + puts []string + // stop ends the module this player runs: the restart of a module is the old process gone and a new one started. + stop func() } // ownedState is one state of an owner (the indexer's modules, the assigner's wants...), kept from its bucket. @@ -232,6 +238,12 @@ func (p *player) handle(m wire) { Bucket string `json:"bucket"` } _ = json.Unmarshal(m.Params, &a) + p.mu.Lock() + p.calls[m.Method]++ + if strings.HasPrefix(m.Method, "mesh/state.") && m.Method != "mesh/state.get" && m.Method != "mesh/state.keys" && m.Method != "mesh/state.watch" { + p.puts = append(p.puts, m.Method+" "+a.State+"/"+a.Key) + } + p.mu.Unlock() kv, kvErr := p.kv(a.State) switch m.Method { case "mesh/state.get": @@ -357,6 +369,9 @@ func (p *player) handle(m wire) { Body json.RawMessage `json:"body"` } _ = json.Unmarshal(m.Params, &q) + p.mu.Lock() + p.asks[q.Key]++ + p.mu.Unlock() p.answer(m.ID, p.asked(q.Key, q.Body), nil) default: p.answer(m.ID, nil, errors.New("nats: no responders available for request")) @@ -675,14 +690,16 @@ func start(t *testing.T, bin string, js jetstream.JetStream, router *standIn, ha stdout, _ := cmd.StdoutPipe() cmd.Stderr = os.Stderr p := &player{t: t, ctx: ctx, js: js, router: router, in: stdin, pending: map[string]chan wire{}, haves: haves, readers: readers, - owned: map[string]*ownedState{}, catalog: map[string]catalog.CatalogEntry{}, byFp: map[string]catalog.CatalogEntry{}} + owned: map[string]*ownedState{}, catalog: map[string]catalog.CatalogEntry{}, byFp: map[string]catalog.CatalogEntry{}, + calls: map[string]int{}, asks: map[string]int{}} for _, f := range followed { p.own(f.Read) } if err := cmd.Start(); err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = stdin.Close(); cancel(); _ = cmd.Wait() }) + p.stop = func() { _ = stdin.Close(); cancel(); _ = cmd.Wait() } + t.Cleanup(p.stop) go p.serve(stdout) t.Cleanup(cancel) return p @@ -708,9 +725,8 @@ func TestConfigWholeRenamesAndRetiresAgainstTheBus(t *testing.T) { t.Fatal(err) } buckets := []string{"mesh-delivery-assigner_assignments", "mesh-delivery-assigner_wants", - "mesh-delivery-indexer_predefined", - "mesh-delivery-indexer_config-candidates"} - for _, s := range []string{ValuesState, ResolvedState, PredefinedState, ProposalsState, PullsState, KeptState, DeclaredState, + "mesh-delivery-indexer_predefined"} + for _, s := range []string{ValuesState, ResolvedState, PredefinedState, ProposalsState, DeclaredState, RenamesState, RetiringState, FindingsState} { buckets = append(buckets, Module+"_"+s) } @@ -785,6 +801,7 @@ func TestConfigWholeRenamesAndRetiresAgainstTheBus(t *testing.T) { // The module restarted inside the window keeps it, and says renamed no more. said := p.publishedCount(EventRenamed) + p.stop() p2 := start(t, bin, js, router, haves, nil) p2.viewsReady() if _, err := p2.call(ResyncTool, nil); err != nil { @@ -833,7 +850,7 @@ func TestConfigWholeRenamesAndRetiresAgainstTheBus(t *testing.T) { p2.mu.Lock() p2.readers = []ReaderRow{{Module: "radio", Key: "band", Kind: KindValue, Readers: []string{}}} p2.mu.Unlock() - p2.event("mesh-catalog.manifest-accepted", map[string]any{"module": "radio"}) + p2.event(catalog.Seat+"."+catalog.EventCatalogRevision+".main", map[string]any{"v": 1, "revision": p2.catRev, "kind": "trunk", "branch": "main", "changed": []string{"radio"}}) eventually(t, "the retirement waits on g14", func() bool { raw, ok := p2.get(RetiringState, "radio.band") return ok && strings.Contains(string(raw), RetireDraining) @@ -869,6 +886,21 @@ func TestConfigWholeRenamesAndRetiresAgainstTheBus(t *testing.T) { p2.conforms(EventRetiring, &meshconfig.RetiringHolderEvent{}, meshconfig.HolderSubjectRetiring) p2.conforms(EventRetired, &meshconfig.RetiredHolderEvent{}, meshconfig.HolderSubjectRetired) eventually(t, "the retirement is dropped", func() bool { _, ok := p2.get(RetiringState, "radio.band"); return !ok }) + p.noGitAsk() + p2.noGitAsk() +} + +// noGitAsk fails when the module asked the seat git for anything over the whole run (ADR 0681 clause 1: it calls no +// `seat:git.pull`, and no other verb of the seat git is its). +func (p *player) noGitAsk() { + p.t.Helper() + p.mu.Lock() + defer p.mu.Unlock() + for key, n := range p.asks { + if strings.HasPrefix(key, "seat:git.") { + p.t.Errorf("the module asked %s %d times: it holds no value for a pull request", key, n) + } + } } // streamCarries says whether the module's manifest names event among its own streams' events. diff --git a/modules/mesh-config/go.mod b/modules/mesh-config/go.mod index 7c48b3524..b6c257cb8 100644 --- a/modules/mesh-config/go.mod +++ b/modules/mesh-config/go.mod @@ -3,7 +3,6 @@ module mesh-config go 1.26.0 require ( - git.novox.be/novox/mesh-contracts/go/clients/meshconfigclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/go/seats/meshconfig v0.0.0-00010101000000-000000000000 diff --git a/modules/mesh-config/module.json b/modules/mesh-config/module.json index 827c0f7cb..e6ac9ed63 100644 --- a/modules/mesh-config/module.json +++ b/modules/mesh-config/module.json @@ -1,6 +1,7 @@ { "module": "mesh-config", "version": "0.1", + "class": "core", "runs-as": "mesh-config", "claims": [ { @@ -19,13 +20,9 @@ "operator-channel" ], "consumes": [ - "git.pull-merged", - "git.pull-closed", "mesh-delivery-view.delivered", "node-engine.manifest-reads-changed", - "mesh-catalog.manifest-accepted", "mesh-delivery-indexer.views.predefined", - "mesh-delivery-indexer.views.config-candidates", "mesh-delivery-assigner.views.assignments", "mesh-delivery-assigner.views.wants", "mesh-catalog.catalog-revision", @@ -36,13 +33,11 @@ "invokes": [ "seat:mesh-hand-acts.hand-act", "seat:mesh-hand-acts.warranted", - "seat:git.pull", "mesh-delivery-view.node_haves", "seat:node-engine.manifest-reads", "mesh-delivery-indexer.indexer_config_readers", "seat:mesh-vault.retire", "mesh-delivery-indexer.indexer_read_predefined", - "mesh-delivery-indexer.indexer_read_config_candidates", "mesh-delivery-assigner.assigner_read_assignments", "mesh-delivery-assigner.assigner_read_wants", "seat:mesh-catalog.revision", @@ -66,8 +61,6 @@ "resolved", "predefined", "proposals", - "pulls", - "kept", "declared", "renames", "retiring", @@ -132,5 +125,16 @@ "max-age-days": 7, "max-mib": 16 } - ] + ], + "config": { + "deadline-floor-seconds": { + "type": "number", + "description": "the least wait, in seconds, of mesh-config's one deadline timer: it is set for the earliest real deadline it holds (a waiting proposal's end, an unanswered retirement's second ask, a rename window's seven-day held finding) and never sooner than this after a look, so a deadline passed and not settled is tried again, not spun on (lead answer A-490l, ADR 0681).", + "minimum": 1, + "maximum": 3600, + "trusted": false, + "default": 60, + "runtime": true + } + } } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go index 7d6726788..65e5fce31 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go @@ -19,6 +19,7 @@ import ( "time" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" + meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" stdio "git.novox.be/novox/mesh-sdk/go" "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats.go" @@ -54,6 +55,10 @@ type testBus struct { answers map[string][]byte // the gate's ledger `records`, as the tool runner keeps it: it outlives one run of the gate, as the bus's does. ledger *ledgerFake + // registrations are what the seat mesh-catalog's verb registrations answers, and heads what the seat git's verb branch + // answers, by `@` (the start pass and the seed read them, design 47 H §768). + registrations []meshcatalog.Registration + heads map[string]string } func newTestBus(t *testing.T) *testBus { @@ -101,7 +106,8 @@ func newTestBus(t *testing.T) *testBus { // The streams the events are on (mesh.mod..event., mesh.seat..event.). if _, err := js.CreateStream(context.Background(), jetstream.StreamConfig{Name: "EVENTS", Subjects: []string{"mesh.seat.git.event.>", "mesh.seat." + oc.Seat + ".event.>", - "mesh.mod.mesh-delivery-forge-bridge.event.>", "mesh.mod.mesh-delivery-indexer.event.>"}}); err != nil { + "mesh.mod.mesh-delivery-forge-bridge.event.>", "mesh.mod.mesh-delivery-indexer.event.>", + "mesh.seat.mesh-pipeline-runner.event.>", "mesh.seat.mesh-wants.event.>", "mesh.seat.node-engine.event.>"}}); err != nil { t.Fatal(err) } return b @@ -163,6 +169,11 @@ type testLog struct{ t *testing.T } func (w testLog) Write(p []byte) (int, error) { defer func() { _ = recover() }() // the bundle may speak after the test ended w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n")) + // Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once + // to one record lost its delivery time). + if strings.Contains(string(p), "WARNING: DATA RACE") { + w.t.Error("the bundle reports a data race, above") + } return len(p), nil } @@ -355,6 +366,29 @@ func (r *runtime) answer(m rpcMessage) { switch a.Key { case "": return nil, errors.New("an ask with no key") + case "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbRegistrations: + r.b.mu.Lock() + defer r.b.mu.Unlock() + return toolAnswer(meshcatalog.RegistrationsAnswer{Registrations: append([]meshcatalog.Registration{}, r.b.registrations...)}), nil + case "seat:git.branch": + repository, _ := a.Body["repository"].(string) + branch, _ := a.Body["branch"].(string) + r.b.mu.Lock() + defer r.b.mu.Unlock() + head, ok := r.b.heads[repository+"@"+branch] + if !ok { + return nil, fmt.Errorf("the forge of this test holds no %s@%s", repository, branch) + } + return toolAnswer(map[string]any{"repository": repository, "branch": branch, "head": head}), nil + case "seat:mesh-hand-acts.hand-act": + return toolAnswer(map[string]any{"id": "hand-act-1"}), nil + case "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbEntry: + // A mover's catalog entry, read once for its class (design 47 H2 §810): a fingerprint of this test opening with + // "core" is a core module's, every other a leaf's. + if fp, _ := a.Body["fingerprint"].(string); strings.HasPrefix(fp, "core") { + return toolAnswer(map[string]any{"entry": map[string]any{"manifest": map[string]any{"class": "core"}}}), nil + } + return toolAnswer(map[string]any{"entry": map[string]any{"manifest": map[string]any{}}}), nil case "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status", "gitea.gitea_merge_pull_request", "gitea.gitea_add_comment": return toolAnswer(map[string]any{}), nil @@ -366,13 +400,33 @@ func (r *runtime) answer(m rpcMessage) { return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key) } switch m.Method { - case buscalls.LedgerApply, buscalls.LedgerGet: + case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove: // The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory. r.b.mu.Lock() defer r.b.mu.Unlock() if r.b.ledger == nil { r.b.ledger = newLedgerFake(r.t) } + if m.Method == buscalls.LedgerQuery { + var in buscalls.QueryRequest + if err := json.Unmarshal(m.Params, &in); err != nil { + return nil, err + } + insts, err := r.b.ledger.Query(in.Index, in.Key) + var a buscalls.QueryAnswer + for _, inst := range insts { + a.Entries = append(a.Entries, buscalls.IndexEntry{Instance: inst}) + } + return a, err + } + if m.Method == buscalls.LedgerRemove { + // An act performed is removed (design 47 H2 §809, H-A-455 (1)), as the tool runner's ledger removal does. + var in buscalls.LedgerRemoveRequest + if err := json.Unmarshal(m.Params, &in); err != nil { + return nil, err + } + return buscalls.LedgerRemoved{}, r.b.ledger.Remove(in.Instance) + } if m.Method == buscalls.LedgerGet { var in buscalls.InstanceRequest if err := json.Unmarshal(m.Params, &in); err != nil { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/conditions.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/conditions.go deleted file mode 100644 index 78f637800..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/conditions.go +++ /dev/null @@ -1,211 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "sort" - "strings" - "time" - - occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" - oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" - stdio "git.novox.be/novox/mesh-sdk/go" -) - -// The gate says its own stalled lines to the operator as conditions (novox/hq issue 1275, met again 2026-10-25; ADR 0437 -// §9: any module says a condition on the operator-channel seat's one subject, and the router alone chooses the channels). -// Until release 6 the controller's self-check read the `stalled` verb and raised each line as `delivery..stalled`; -// release 6 deleted that self-check (mesh-controller dc456d56) and nothing read the verb since, so a half-merged group was -// said to no one. Now, after every look, the gate raises each line `stalled` lists, raises it again when its severity or -// its need changes, and clears each it raised that is listed no more. What it raised is kept in its bucket conditions, so a -// gate that restarts clears what ended while it was away. - -// ConditionStore keeps the conditions the gate has raised: the condition's key to what it said (conditionSaid). -type ConditionStore interface { - Said() (map[string]string, error) - PutSaid(said map[string]string) error -} - -// saidKey is the one key of the bucket conditions. -const saidKey = "said" - -// kvConditions is the bucket conditions over the runtime. -type kvConditions struct{} - -func (kvConditions) Said() (map[string]string, error) { - e, err := stdio.State("conditions").Get(saidKey) - if err != nil || e == nil { - return map[string]string{}, err - } - said := map[string]string{} - if err := json.Unmarshal(e.Value, &said); err != nil { - return nil, fmt.Errorf("the conditions the gate raised are not readable: %w", err) - } - return said, nil -} - -func (kvConditions) PutSaid(said map[string]string) error { - _, err := stdio.State("conditions").Put(saidKey, said) - return err -} - -// sayOnSeat says a condition on the operator-channel seat under the gate's own name. -func sayOnSeat(c oc.Condition) error { - subject, err := occ.ConditionSubject("mesh-delivery-gate") - if err != nil { - return err - } - raw, err := occ.EncodeCondition(c) - if err != nil { - return err - } - return stdio.SeatPublish(subject, json.RawMessage(raw), "") -} - -// conditionKeyOf is the key of a stalled line's condition: its last part is the condition's kind. -func conditionKeyOf(id string) string { return "mesh-delivery-gate.delivery." + id + ".stalled" } - -// conditionSaid is what a raised condition said that, when it changes, raises it again: its severity and what it needs. -// The words of a line hold durations, which change at every look and are no reason to tell the operator again. -func conditionSaid(l StalledLine) string { return severityOfLine(l) + "|" + l.H2 } - -func severityOfLine(l StalledLine) string { - if l.Severity == occ.SeverityUrgent { - return occ.SeverityUrgent - } - return occ.SeverityWarning -} - -// conditionOf is a stalled line as the condition the operator is told. -func conditionOf(l StalledLine) oc.Condition { - headline := "stalled: " + l.ID - if r := []rune(headline); len(r) > occ.HeadlineLength { - headline = string(r[:occ.HeadlineLength-1]) + "…" - } - needs := "read mesh-delivery.show " + l.ID + " and decide" - return oc.Condition{Key: conditionKeyOf(l.ID), Severity: severityOfLine(l), State: occ.StateRaised, - Subject: oc.ConditionSubject{Scope: "delivery", ID: l.ID}, Summary: l.Says, Headline: headline, Needs: needs, - Explanation: occ.NeedsYou + needs + ". " + l.Says + " What ends it: " + l.H2 + ".", - Resolved: "The gate lists " + l.ID + " as stalled no more."} -} - -// sayConditions raises and clears the conditions of the stalled lines (see above). Outside the lock; React runs it after -// the look, so it follows every event. A condition that could not be said is said again at the next look, after -// askAgainAfter at the latest. -func (h *Holder) sayConditions() { - if h.Say == nil || h.Conditions == nil { - return - } - if h.said == nil { - said, err := h.Conditions.Said() - if err != nil { - h.Logf("[mesh-delivery] the conditions raised before cannot be read, so none is said yet: %v; asked again in %s", err, askAgainAfter) - h.again("the conditions the gate raised, read") - return - } - h.said = said - } - if at := h.nextStall(h.Now()); !at.IsZero() { - h.lookAt(at, "a record whose stalled line comes due with no event") - } - lines := map[string]StalledLine{} - for _, l := range h.Stalled() { - // One condition for an id: the most severe of its lines. - if o, ok := lines[l.ID]; !ok || (severityOfLine(o) != occ.SeverityUrgent && severityOfLine(l) == occ.SeverityUrgent) { - lines[l.ID] = l - } - } - ids := make([]string, 0, len(lines)) - for id := range lines { - ids = append(ids, id) - } - sort.Strings(ids) - changed, failed := false, false - for _, id := range ids { - l, key := lines[id], conditionKeyOf(id) - said := conditionSaid(l) - if h.said[key] == said { - continue - } - if err := h.Say(conditionOf(l)); err != nil { - h.Logf("[mesh-delivery] the condition of %s could not be said: %v", id, err) - failed = true - continue - } - h.Logf("[mesh-delivery] %s is said to the operator as %s: %s", id, severityOfLine(l), l.Says) - h.said[key], changed = said, true - } - // Cleared when the line is gone: what it raised is kept in the bucket conditions, so a gate that restarts clears what ended. - var gone []string - for key := range h.said { - id := strings.TrimSuffix(strings.TrimPrefix(key, "mesh-delivery-gate.delivery."), ".stalled") - if _, ok := lines[id]; !ok { - gone = append(gone, key) - } - } - sort.Strings(gone) - for _, key := range gone { - id := strings.TrimSuffix(strings.TrimPrefix(key, "mesh-delivery-gate.delivery."), ".stalled") - c := oc.Condition{Key: key, Subject: oc.ConditionSubject{Scope: "delivery", ID: id}, State: occ.StateCleared, - Resolved: "The gate lists " + id + " as stalled no more."} - if err := h.Say(c); err != nil { - h.Logf("[mesh-delivery] the condition of %s could not be cleared: %v", id, err) - failed = true - continue - } - h.Logf("[mesh-delivery] the condition of %s is cleared: it is stalled no more", id) - delete(h.said, key) - changed = true - } - if changed { - if err := h.Conditions.PutSaid(h.said); err != nil { - h.Logf("[mesh-delivery] the conditions raised cannot be kept: %v", err) - } - } - if !failed { - h.sayFailures = 0 - return - } - // A seat that keeps refusing is tried again after askAgainAfter, up to sayTries looks in a row; then only at the - // next event, and said once, loudly, in the log (the operator hears nothing while the seat refuses). - h.sayFailures++ - switch { - case h.sayFailures < sayTries: - h.again("a condition that could not be said to the operator") - case h.sayFailures == sayTries: - h.Logf("[mesh-delivery] NO CONDITION REACHES THE OPERATOR: the operator-channel seat refused %d looks in a row; "+ - "tried again at each event from now on", sayTries) - } -} - -// sayTries is how many looks in a row a condition that could not be said is tried again on the clock. -const sayTries = 10 - -// nextStall is the earliest time after now when a record's stalled line comes due with nothing else happening: a record open -// past its bound, an act unanswered past its. Zero when none. -func (h *Holder) nextStall(now time.Time) time.Time { - var next time.Time - if h.Records == nil { - return next - } - consider := func(at time.Time) { - if at.After(now) && (next.IsZero() || at.Before(next)) { - next = at - } - } - kept, err := h.Records.Kept() - if err != nil { - return next - } - for _, r := range kept { - if r.Ended == nil { - consider(r.Opened.Add(recordOpenBound).Add(time.Second)) - } - for _, a := range r.Acts { - if a.Outcome == "" { - consider(a.At.Add(owedBound).Add(time.Second)) - } - } - } - return next -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go index 2559e6c2c..f61195ae0 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go @@ -10,6 +10,7 @@ package main // (ADR 0363 §2), and an event a node publishes names that node in its subject and in its x-node header. import ( + "bytes" "encoding/json" "fmt" ownmanifest "mesh-delivery-gate" @@ -17,6 +18,10 @@ import ( "sync" "time" + nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" + wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein" stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -43,7 +48,9 @@ type stepFamily struct { // Event is the event's name after its owner; the node is the token after it when NodeScoped. Event string NodeScoped bool - Decode func(body json.RawMessage, at time.Time) ([]StepOutcome, error) + // Kind is the event's name on its owner's seat, with no subject tokens: what Follow is told it is. + Kind string + Decode func(body json.RawMessage, at time.Time) ([]StepOutcome, error) } // The step events on main the record is built from. A family is added here, with its `consumes` line, when its owner @@ -52,13 +59,34 @@ var stepFamilies = []stepFamily{ // An entry taken in (the holder of the seat mesh-catalog's own `take-in.taken`, ADR 0633 §1): the merges a source // revision took in. Its owner is the one the manifest consumes it from. family(takein.TakeInTakenEvent, decodeTakenIn), + // The record follows its pipeline to the machines (design 47 H §738, H-A-29, H-A-75, H-A-89; recordpipeline.go): the + // runner's pipeline-started, pipeline-ended, wait-held and wait-ended on ., the assigner's wanted on + // . and pipeline-wanted on ., and the node-engine seat's running on .. + seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted), + seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded), + seatFamily(runner.EventWaitHeld, 2, false, decodeWait), + seatFamily(runner.EventWaitEnded, 2, false, decodeWait), + seatFamily(wants.EventWanted, 2, false, decodeWanted), + seatFamily(wants.EventPipelineWanted, 2, false, decodePipelineWanted), + seatFamily(nodeengine.EventRunning, 2, true, decodeRunning), +} + +// seatFamily is a step family of a seat's event its manifest consumes with each token of its subject a wildcard +// (`..*.*`); of a node's event, the node is the first token after the event. +func seatFamily(event string, tokens int, nodeScoped bool, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily { + f := family(event+strings.Repeat(".*", tokens), decode) + f.Kind = event + if nodeScoped { + f.Event, f.NodeScoped = event, true + } + return f } // family is a step family of an event as the manifest consumes it: `.`. func family(event string, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily { pattern := declared(event) owner, _, _ := strings.Cut(pattern, ".") - return stepFamily{Pattern: pattern, Owner: owner, Event: event, Decode: decode} + return stepFamily{Pattern: pattern, Owner: owner, Event: event, Kind: event, Decode: decode} } // consumed is what the gate's manifest consumes (its own manifest): every event it follows is one of them. @@ -90,28 +118,19 @@ func stepPatterns() []string { return out } -// decodeTakenIn reads a `take-in.taken`: each merge taken in is an outcome of the record that merged it, unless the wait -// was dropped by hand, which took nothing in. -func decodeTakenIn(body json.RawMessage, at time.Time) ([]StepOutcome, error) { - t, err := takein.DecodeTakeIn(body) - if err != nil { +// decodeTakenIn reads a take-in.taken in the seat mesh-catalog's form, refusing a field it does not know, and answers no +// outcome: the take-in is written into its record by its key (takenin.go, H-A-29). +func decodeTakenIn(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var t meshcatalog.TakeInTaken + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + if err := dec.Decode(&t); err != nil { return nil, err } - if t.Kind != takein.TakeInTaken { - return nil, fmt.Errorf("a take-in.taken of kind %q", t.Kind) + if t.Branch == "" || t.Source < 1 { + return nil, fmt.Errorf("a take-in.taken names no branch or source revision") } - outcome, why := OutcomeTakenIn, t.Why - if t.Dropped { - outcome, why = OutcomeHeld, "its take-in was dropped: "+t.Why - } - var commits []string - for _, m := range t.Merges { - commits = append(commits, m.Merge) - } - if len(commits) == 0 { - return nil, nil - } - return []StepOutcome{{Commits: commits, Step: "take-in", Outcome: outcome, Why: why, At: at}}, nil + return nil, nil } // StepConsumer applies the step events to the records. @@ -120,8 +139,11 @@ type StepConsumer struct { Families []stepFamily Now func() time.Time Logf func(format string, a ...any) - // Taken opens the record of a take-in.taken and moves its branch's source (takenin.go), before its outcomes are applied. + // Taken writes a take-in.taken into the record of its source revision (takenin.go). Taken func(body json.RawMessage) error + // Follow writes an event of the record's pipeline families into the record of its source revision, told the event's + // kind (recordpipeline.go). + Follow func(kind string, body json.RawMessage) error mu sync.Mutex // heard counts, per family, the events applied, refused and the last applied, since this owner started. @@ -186,6 +208,10 @@ func (c *StepConsumer) Hear(e stdio.Envelope) error { if err := c.Taken(e.Body); err != nil { return fmt.Errorf("the record of %s is not opened yet: %w", e.Key, err) } + } else if f.Event != takein.TakeInTakenEvent && c.Follow != nil { + if err := c.Follow(f.Kind, e.Body); err != nil { + return fmt.Errorf("the record of %s is not written yet: %w", e.Key, err) + } } id := e.Headers["x-event-id"] for _, o := range outcomes { @@ -223,7 +249,7 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string { // apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one // that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown -// away). An open record whose present nodes then all run their entries ends. +// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)). func (c *StepConsumer) apply(o StepOutcome, event string) error { records, err := c.Records.Kept() if err != nil { @@ -245,9 +271,6 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error { return err } } - if _, err := c.Records.EndIfRun(r); err != nil { - return err - } } return nil } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries.go deleted file mode 100644 index d1363a7d2..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries.go +++ /dev/null @@ -1,462 +0,0 @@ -package main - -// The gate keeps a group's members from their announcement (design 47 G §716; A-279, A-236): its states `deliveries` and -// `groups`, written from the seat git's pull-updated, pull-merged and pull-closed, deleted when a record carries a member (the -// take-in, takenin.go) or its pull request closes unmerged, and put right at the gate's start from the seat git's open-pulls and -// pull. A delivery's key is its id `@` escaped as a key name; a group's key is its head branch -// escaped as a key name. Only the gate writes either state. - -import ( - "encoding/json" - "errors" - "fmt" - "sort" - "strings" - - gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" - stdio "git.novox.be/novox/mesh-sdk/go" - "git.novox.be/novox/mesh-sdk/go/keys" -) - -// The two states, by their names in the gate's manifest. -const ( - deliveriesState = "deliveries" - groupsState = "groups" -) - -// The states of a delivery the gate writes; any other state an old table kept counts open (§716). -const ( - deliveryOpen = "open" - deliveryMerged = "merged" -) - -// Delivery is one pull request as the state `deliveries` keeps it. -type Delivery struct { - ID string `json:"id"` - Repository string `json:"repository"` - Number int `json:"number"` - Commit string `json:"commit"` - // Base is the pull request's base branch as the seat git says it (A-279); Branch its head branch, which names its group. - Base string `json:"base,omitempty"` - Branch string `json:"branch,omitempty"` - Group string `json:"group,omitempty"` - State string `json:"state"` -} - -// openOrMerged is a delivery's state as the gate reads it: merged, or else open. -func (d Delivery) openOrMerged() string { - if d.State == deliveryMerged { - return deliveryMerged - } - return deliveryOpen -} - -// keptGroup is one key of the state `groups`: the group, its head branch, and its members' delivery ids. -type keptGroup struct { - Group string `json:"group"` - Members []string `json:"members"` -} - -// DeliveryStore is the gate's two states over the runtime. -type DeliveryStore interface { - Keys(state string) ([]string, error) - Get(state, key string) ([]byte, error) - Put(state, key string, value any) error - Delete(state, key string) error -} - -// ForgeReads is what the gate reads of the seat git: open-pulls and pull. -type ForgeReads interface { - OpenPulls() (gitseat.OpenPullsAnswer, error) - Pull(repository string, number int64) (gitseat.PullAnswer, error) - // Branch is a repository branch's head (the seat git's verb branch). - Branch(repository, branch string) (gitseat.BranchAnswer, error) - // Contains is whether commit is in (or is) the commit in (the seat git's verb contains). - Contains(repository, commit, in string) (bool, error) -} - -// kvKept is the store over the runtime. -type kvKept struct{} - -func (kvKept) Keys(state string) ([]string, error) { return stdio.State(state).Keys() } - -func (kvKept) Get(state, key string) ([]byte, error) { - e, err := stdio.State(state).Get(key) - if err != nil || e == nil { - return nil, err - } - return e.Value, nil -} - -func (kvKept) Put(state, key string, value any) error { - _, err := stdio.State(state).Put(key, value) - return err -} - -func (kvKept) Delete(state, key string) error { return stdio.State(state).Delete(key) } - -// seatGit reads the seat git through the tool runner. -type seatGit struct{ ask asking } - -func (s seatGit) call(verb string, in any, out any) error { - raw, err := s.ask("seat:"+gitseat.Seat+"."+verb, in) - if err != nil { - return err - } - answer, said, ok := answerOf(raw) - if !ok { - return fmt.Errorf("%s refused: %s", verb, lastLine(said)) - } - if err := json.Unmarshal(answer, out); err != nil { - return fmt.Errorf("the answer of %s is not readable: %w", verb, err) - } - return nil -} - -func (s seatGit) OpenPulls() (gitseat.OpenPullsAnswer, error) { - var a gitseat.OpenPullsAnswer - return a, s.call(gitseat.VerbOpenPulls, gitseat.OpenPullsInput{}, &a) -} - -func (s seatGit) Pull(repository string, number int64) (gitseat.PullAnswer, error) { - var a gitseat.PullAnswer - return a, s.call(gitseat.VerbPull, gitseat.PullInput{Repository: repository, Number: number}, &a) -} - -func deliveryKey(id string) string { return keys.EscapeName(id) } - -func samePull(d Delivery, repository string, number int) bool { - return strings.EqualFold(d.Repository, repository) && d.Number == number -} - -// deliveries are every delivery the state keeps by its key; a key that is no delivery (a mark an earlier owner kept) is left. -func (h *Holder) deliveries() (map[string]Delivery, error) { - if h.Kept == nil { - return nil, errors.New("this gate keeps no state deliveries") - } - names, err := h.Kept.Keys(deliveriesState) - if err != nil { - return nil, fmt.Errorf("the state deliveries cannot be read: %w", err) - } - out := map[string]Delivery{} - for _, k := range names { - raw, err := h.Kept.Get(deliveriesState, k) - if err != nil { - return nil, fmt.Errorf("the delivery %s cannot be read: %w", k, err) - } - var d Delivery - if raw == nil || json.Unmarshal(raw, &d) != nil || d.ID == "" || d.Number == 0 { - continue - } - out[k] = d - } - return out, nil -} - -// keptGroups are every group the state keeps by its key. -func (h *Holder) keptGroups() (map[string]keptGroup, error) { - if h.Kept == nil { - return nil, errors.New("this gate keeps no state groups") - } - names, err := h.Kept.Keys(groupsState) - if err != nil { - return nil, fmt.Errorf("the state groups cannot be read: %w", err) - } - out := map[string]keptGroup{} - for _, k := range names { - raw, err := h.Kept.Get(groupsState, k) - if err != nil { - return nil, fmt.Errorf("the group %s cannot be read: %w", k, err) - } - var g keptGroup - if raw == nil || json.Unmarshal(raw, &g) != nil || g.Group == "" { - continue - } - out[k] = g - } - return out, nil -} - -// PullUpdated takes one pull-updated: the delivery is written under its id with its base and head branch, and a newer head of the -// same pull request takes the older's place, in its group too. -func (h *Holder) PullUpdated(body []byte) error { - var e gitseat.PullUpdatedEvent - if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 || e.Head == "" { - h.Refuse(fmt.Errorf("a pull-updated of the seat git is not readable: %v", err)) - return nil - } - h.dmu.Lock() - defer h.dmu.Unlock() - return h.writeDelivery(Delivery{ID: IDOf(e.Repository, e.Head), Repository: e.Repository, Number: int(e.Number), Commit: e.Head, - Base: e.Base, Branch: e.Branch, State: deliveryOpen}) -} - -// writeDelivery writes a delivery in place of any other head of its pull request and puts the groups right; under dmu. -func (h *Holder) writeDelivery(d Delivery) error { - all, err := h.deliveries() - if err != nil { - return err - } - branches := map[string]bool{d.Branch: true} - key := deliveryKey(d.ID) - for k, o := range all { - if k == key || !samePull(o, d.Repository, d.Number) { - continue - } - if err := h.Kept.Delete(deliveriesState, k); err != nil { - return fmt.Errorf("the older delivery %s cannot be deleted: %w", o.ID, err) - } - delete(all, k) - branches[o.Branch] = true - } - if o, ok := all[key]; ok { - d.State = o.openOrMerged() - d.Group = o.Group - } - if err := h.Kept.Put(deliveriesState, key, d); err != nil { - return fmt.Errorf("the delivery %s cannot be written: %w", d.ID, err) - } - return h.refreshGroups(branches) -} - -// DeliveryMerged takes one pull-merged: the delivery of that pull request is merged. A pull request the gate keeps no delivery of is -// left: nothing would delete it. -func (h *Holder) DeliveryMerged(body []byte) error { - var e gitseat.PullMergedEvent - if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 { - h.Refuse(fmt.Errorf("a pull-merged of the seat git is not readable: %v", err)) - return nil - } - h.dmu.Lock() - defer h.dmu.Unlock() - return h.setMerged(e.Repository, int(e.Number), e.Base) -} - -// setMerged sets the state of a pull request's delivery to merged; under dmu. -func (h *Holder) setMerged(repository string, number int, base string) error { - all, err := h.deliveries() - if err != nil { - return err - } - for k, d := range all { - if !samePull(d, repository, number) || d.State == deliveryMerged { - continue - } - d.State = deliveryMerged - if base != "" { - d.Base = base - } - if err := h.Kept.Put(deliveriesState, k, d); err != nil { - return fmt.Errorf("the delivery %s cannot be set merged: %w", d.ID, err) - } - } - return nil -} - -// DeliveryClosed takes one pull-closed: the delivery of a pull request not merged is deleted, and its group put right. -func (h *Holder) DeliveryClosed(body []byte) error { - var e gitseat.PullClosedEvent - if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 { - h.Refuse(fmt.Errorf("a pull-closed of the seat git is not readable: %v", err)) - return nil - } - h.dmu.Lock() - defer h.dmu.Unlock() - return h.dropUnmerged(e.Repository, int(e.Number)) -} - -// dropUnmerged deletes the deliveries of a pull request that are not merged and puts their groups right; under dmu. -func (h *Holder) dropUnmerged(repository string, number int) error { - all, err := h.deliveries() - if err != nil { - return err - } - branches := map[string]bool{} - for k, d := range all { - if !samePull(d, repository, number) || d.State == deliveryMerged { - continue - } - if err := h.Kept.Delete(deliveriesState, k); err != nil { - return fmt.Errorf("the delivery %s cannot be deleted: %w", d.ID, err) - } - branches[d.Branch] = true - } - return h.refreshGroups(branches) -} - -// recordGroupsHeld are the group ids the delivery records carry, ended or not. -func (h *Holder) recordGroupsHeld() (map[string]bool, error) { - out := map[string]bool{} - if h.Records == nil { - return out, nil - } - kept, err := h.Records.Kept() - if err != nil { - return nil, fmt.Errorf("the delivery records cannot be read for the groups: %w", err) - } - for _, r := range kept { - if r.Group != nil && r.Group.Group != "" && len(membersOf(r)) > 0 { - out[r.Group.Group] = true - } - } - return out, nil -} - -// refreshGroups writes, for each head branch, the group key of its deliveries and their `group`: pull requests with one head branch -// form one group; a group of one with no member in a record is no group, its key deleted and its member's `group` cleared; a group -// key once no member remains outside a record is deleted (§716). Under dmu. -func (h *Holder) refreshGroups(branches map[string]bool) error { - inRecords, err := h.recordGroupsHeld() - if err != nil { - return err - } - all, err := h.deliveries() - if err != nil { - return err - } - for branch := range branches { - if branch == "" { - continue - } - var members []string - keysOf := map[string]string{} - for k, d := range all { - if d.Branch == branch { - members = append(members, d.ID) - keysOf[d.ID] = k - } - } - sort.Strings(members) - gkey := keys.EscapeName(branch) - isGroup := len(members) > 1 || len(members) == 1 && inRecords[branch] - if !isGroup { - if err := h.Kept.Delete(groupsState, gkey); err != nil { - return fmt.Errorf("the group %s cannot be deleted: %w", branch, err) - } - } else if err := h.Kept.Put(groupsState, gkey, keptGroup{Group: branch, Members: members}); err != nil { - return fmt.Errorf("the group %s cannot be written: %w", branch, err) - } - for _, id := range members { - k := keysOf[id] - d := all[k] - want := "" - if isGroup { - want = branch - } - if d.Group != want { - d.Group = want - all[k] = d - if err := h.Kept.Put(deliveriesState, k, d); err != nil { - return fmt.Errorf("the delivery %s cannot be put in its group: %w", id, err) - } - } - } - } - return nil -} - -// ReadForge puts right what a missed pull event left, once at the gate's start (§716, after §613's copy): each open pull request -// the seat git's open-pulls says that the gate lacks, or keeps at another head, is written; each delivery kept open that the answer -// does not name is read by pull: merged sets merged, closed deletes it. A read that fails is said in the journal and made again at -// the next start. -func (h *Holder) ReadForge() error { - if h.Forge == nil || h.Kept == nil { - return nil - } - answer, err := h.Forge.OpenPulls() - if err != nil { - return fmt.Errorf("open-pulls: %w", err) - } - if answer.Error != "" { - return fmt.Errorf("open-pulls: %s", answer.Error) - } - h.dmu.Lock() - defer h.dmu.Unlock() - listed := map[string]bool{} - var failed []error - for _, o := range answer.Pulls { - p := o.Pull - if p.Repository == "" || p.Number <= 0 || p.Head == "" { - continue - } - listed[strings.ToLower(p.Repository)+"#"+fmt.Sprint(p.Number)] = true - all, err := h.deliveries() - if err != nil { - return err - } - if d, ok := all[deliveryKey(IDOf(p.Repository, p.Head))]; ok && d.Base == p.Base && d.Branch == p.Branch { - continue - } - if err := h.writeDelivery(Delivery{ID: IDOf(p.Repository, p.Head), Repository: p.Repository, Number: int(p.Number), Commit: p.Head, - Base: p.Base, Branch: p.Branch, State: deliveryOpen}); err != nil { - failed = append(failed, err) - } - } - all, err := h.deliveries() - if err != nil { - return err - } - for _, d := range all { - if d.openOrMerged() != deliveryOpen || listed[strings.ToLower(d.Repository)+"#"+fmt.Sprint(d.Number)] { - continue - } - got, err := h.Forge.Pull(d.Repository, int64(d.Number)) - if err == nil && got.Error != "" { - err = errors.New(got.Error) - } - if err == nil && got.Pull == nil { - err = errors.New("the answer names no pull request") - } - if err != nil { - h.Logf("[mesh-delivery] the pull request %s#%d cannot be read at the start: %v", d.Repository, d.Number, err) - failed = append(failed, err) - continue - } - switch got.Pull.State { - case gitseat.PullStateMerged: - err = h.setMerged(d.Repository, d.Number, got.Pull.Base) - case gitseat.PullStateClosed: - err = h.dropUnmerged(d.Repository, d.Number) - } - if err != nil { - failed = append(failed, err) - } - } - return errors.Join(failed...) -} - -// baseOf is the base of a pull request's delivery, and whether the gate keeps one. -func baseOf(all map[string]Delivery, repository string, number int) (string, bool) { - for _, d := range all { - if samePull(d, repository, number) { - return d.Base, true - } - } - return "", false -} - -// carried puts the deliveries of the pull requests a record carries away, once the record holds them with their base: each delivery -// is deleted and the groups put right. A deletion is made in the old section too (§613): the state's keys are the one table. -func (h *Holder) carried(pulls []RecordPull) error { - if h.Kept == nil { - return nil - } - h.dmu.Lock() - defer h.dmu.Unlock() - all, err := h.deliveries() - if err != nil { - return err - } - branches := map[string]bool{} - for k, d := range all { - for _, p := range pulls { - if samePull(d, p.Repository, p.Number) { - if err := h.Kept.Delete(deliveriesState, k); err != nil { - return fmt.Errorf("the delivery %s cannot be deleted: %w", d.ID, err) - } - branches[d.Branch] = true - } - } - } - return h.refreshGroups(branches) -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries_test.go deleted file mode 100644 index f523fbda9..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/deliveries_test.go +++ /dev/null @@ -1,275 +0,0 @@ -package main - -import ( - "encoding/json" - "errors" - "fmt" - "sort" - "strings" - "testing" - "time" - - gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" -) - -// memKept is the gate's states deliveries and groups in memory. -type memKept struct{ m map[string]map[string][]byte } - -func (k *memKept) Keys(state string) ([]string, error) { - var out []string - for key := range k.m[state] { - out = append(out, key) - } - sort.Strings(out) - return out, nil -} -func (k *memKept) Get(state, key string) ([]byte, error) { return k.m[state][key], nil } -func (k *memKept) Put(state, key string, v any) error { - if k.m == nil { - k.m = map[string]map[string][]byte{} - } - if k.m[state] == nil { - k.m[state] = map[string][]byte{} - } - raw, _ := json.Marshal(v) - k.m[state][key] = raw - return nil -} -func (k *memKept) Delete(state, key string) error { delete(k.m[state], key); return nil } - -// fakeForge is the seat git's reads: the open pull requests and each pull request by its number. -type fakeForge struct { - open []gitseat.OpenPull - pulls map[string]gitseat.Pull - heads map[string]string // "@" -> head - // contains says whether commit is in `in`; nil means every commit is in every other (a straight line forward) - contains func(commit, in string) bool - fail bool -} - -func (f *fakeForge) OpenPulls() (gitseat.OpenPullsAnswer, error) { - if f.fail { - return gitseat.OpenPullsAnswer{}, errors.New("the forge is away") - } - return gitseat.OpenPullsAnswer{Pulls: f.open}, nil -} -func (f *fakeForge) Branch(repository, branch string) (gitseat.BranchAnswer, error) { - if f.fail { - return gitseat.BranchAnswer{}, errors.New("the forge is away") - } - head, ok := f.heads[repository+"@"+branch] - if !ok { - return gitseat.BranchAnswer{Error: "no such branch"}, nil - } - return gitseat.BranchAnswer{Branch: branch, Repository: repository, Head: head}, nil -} -func (f *fakeForge) Contains(repository, commit, in string) (bool, error) { - if f.fail { - return false, errors.New("the forge is away") - } - if f.contains == nil { - return true, nil - } - return f.contains(commit, in), nil -} -func (f *fakeForge) Pull(repository string, number int64) (gitseat.PullAnswer, error) { - p, ok := f.pulls[fmt.Sprintf("%s#%d", repository, number)] - if !ok { - return gitseat.PullAnswer{Error: "no such pull request"}, nil - } - return gitseat.PullAnswer{Pull: &p}, nil -} - -func gateWithDeliveries(t *testing.T) (*Holder, *memKept) { - t.Helper() - k := &memKept{} - h := &Holder{Now: func() time.Time { return time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) }, Kept: k, Logf: func(string, ...any) {}} - h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now} - return h, k -} - -func updated(repository string, number int, head, base, branch string) []byte { - raw, _ := json.Marshal(gitseat.PullUpdatedEvent{Repository: repository, Number: int64(number), Head: head, Base: base, Branch: branch}) - return raw -} - -func groupNamed(t *testing.T, h *Holder, id string) []string { - t.Helper() - a := h.Groups(false, id) - if a.Error != "" || len(a.Groups) != 1 { - t.Fatalf("groups %q: %+v", id, a) - } - var out []string - for _, m := range a.Groups[0].Members { - out = append(out, fmt.Sprintf("%s#%d@%s/%s/%s/%v", m.Repository, m.Number, m.Base, m.State, m.Head[:1], m.Open)) - } - return out -} - -// §716, A-279: a group read before any take-in names its members with their base, from the seat git's pull-updated. -func TestAGroupReadBeforeAnyTakeInNamesItsMembersWithTheirBase(t *testing.T) { - h, k := gateWithDeliveries(t) - a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) - for _, body := range [][]byte{updated("novox/app", 3, a, "main", "feat"), updated("novox/lib", 4, b, "beta", "feat")} { - if err := h.PullUpdated(body); err != nil { - t.Fatal(err) - } - } - got := groupNamed(t, h, "feat") - want := []string{"novox/app#3@main/open/a/true", "novox/lib#4@beta/open/b/true"} - if strings.Join(got, " ") != strings.Join(want, " ") { - t.Fatalf("members %v, wanted %v", got, want) - } - if len(k.m[groupsState]) != 1 || len(k.m[deliveriesState]) != 2 { - t.Fatalf("states %v", k.m) - } - // The delivery's key is its id escaped as a key name, with its group set (§42). - var d Delivery - if err := json.Unmarshal(k.m[deliveriesState]["novox/app=40"+strings.Repeat("a", 12)], &d); err != nil || d.Group != "feat" || d.Base != "main" || d.State != "open" || d.Number != 3 { - t.Fatalf("the delivery %+v %v (keys %v)", d, err, k.m[deliveriesState]) - } -} - -// §716: a newer head of the same pull request takes the older's place in its group, and the older key is deleted. -func TestANewerHeadReplacesTheOlder(t *testing.T) { - h, k := gateWithDeliveries(t) - a, b, c := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("c", 40) - for _, body := range [][]byte{updated("novox/app", 3, a, "main", "feat"), updated("novox/lib", 4, b, "main", "feat"), updated("novox/app", 3, c, "main", "feat")} { - if err := h.PullUpdated(body); err != nil { - t.Fatal(err) - } - } - got := groupNamed(t, h, "feat") - if strings.Join(got, " ") != "novox/app#3@main/open/c/true novox/lib#4@main/open/b/true" || len(k.m[deliveriesState]) != 2 { - t.Fatalf("members %v, deliveries %d", got, len(k.m[deliveriesState])) - } -} - -// §716: a closed unmerged pull request leaves; a group of one with no member in a record is no group, its key deleted and the -// member's group cleared. -func TestAClosedUnmergedPullRequestLeavesItsGroup(t *testing.T) { - h, k := gateWithDeliveries(t) - a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) - _ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat")) - _ = h.PullUpdated(updated("novox/lib", 4, b, "main", "feat")) - closed, _ := json.Marshal(gitseat.PullClosedEvent{Repository: "novox/lib", Number: 4, Head: b, Base: "main", Branch: "feat"}) - if err := h.DeliveryClosed(closed); err != nil { - t.Fatal(err) - } - if len(k.m[groupsState]) != 0 || len(k.m[deliveriesState]) != 1 { - t.Fatalf("states %v", k.m) - } - for _, raw := range k.m[deliveriesState] { - var d Delivery - _ = json.Unmarshal(raw, &d) - if d.Group != "" || d.Number != 3 { - t.Fatalf("the member of a group of one keeps its group: %+v", d) - } - } -} - -// §716, A-279: the take-in copies the delivery's base onto the record's member and deletes the delivery; the member not taken in stays -// in the group, which names both. -func TestTheTakeInCopiesTheBaseAndKeepsTheRestOfTheGroup(t *testing.T) { - h, k := gateWithDeliveries(t) - merge := strings.Repeat("m", 40) - a, b := strings.Repeat("a", 40), strings.Repeat("b", 40) - _ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat")) - _ = h.PullUpdated(updated("novox/lib", 4, b, "beta", "feat")) - merged, _ := json.Marshal(gitseat.PullMergedEvent{Repository: "novox/app", Number: 3, Head: a, Base: "main", Branch: "feat", MergeCommit: merge}) - if err := h.DeliveryMerged(merged); err != nil { - t.Fatal(err) - } - if got := groupNamed(t, h, "feat"); got[0] != "novox/app#3@main/merged/a/false" { - t.Fatalf("a merged member before its take-in: %v", got) - } - body := json.RawMessage(`{"v":1,"kind":"taken","key":"g.feat","what":"group","group":"feat","branch":"main","source":7,` + - `"merges":[{"repository":"novox/app","number":3,"merge":"` + merge + `"}],` + - `"entries":[{"module":"app","commit":"` + merge + `","fingerprint":"f","repository":"novox/app","pull":3}],"since":"2026-11-12T09:00:00Z"}`) - for i := 0; i < 2; i++ { // heard again: the base the record holds stays - if err := h.TakenIn(body); err != nil { - t.Fatal(err) - } - } - kept, _ := h.Records.Kept() - if len(kept) != 1 || kept[0].Group == nil || len(kept[0].Group.Pulls) != 1 || kept[0].Group.Pulls[0].Base != "main" { - t.Fatalf("the record's member lacks its base: %+v", kept) - } - if len(k.m[deliveriesState]) != 1 || len(k.m[groupsState]) != 1 { - t.Fatalf("states after the take-in: %v", k.m) - } - got := groupNamed(t, h, "feat") - if strings.Join(got, " ") != "novox/app#3@main/merged/m/false novox/lib#4@beta/open/b/true" && strings.Join(got, " ") != "novox/app#3@main/merged/a/false novox/lib#4@beta/open/b/true" { - t.Fatalf("members %v", got) - } -} - -// §716: a missed event is put right at the start: an open pull request the gate lacks is written, one kept at another head is -// replaced, and a kept delivery the answer does not name is read: merged is set, closed is deleted; a read that fails is -// said and left. -func TestAMissedEventIsPutRightAtStart(t *testing.T) { - h, k := gateWithDeliveries(t) - a, a2, b, c, d := strings.Repeat("a", 40), strings.Repeat("1", 40), strings.Repeat("b", 40), strings.Repeat("c", 40), strings.Repeat("d", 40) - _ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat")) - _ = h.PullUpdated(updated("novox/gone", 5, c, "main", "feat")) - _ = h.PullUpdated(updated("novox/done", 6, d, "main", "feat")) - _ = h.PullUpdated(updated("novox/away", 7, d, "main", "other")) - h.Forge = &fakeForge{ - open: []gitseat.OpenPull{ - {Pull: gitseat.Pull{Repository: "novox/app", Number: 3, Head: a2, Base: "main", Branch: "feat"}}, - {Pull: gitseat.Pull{Repository: "novox/lib", Number: 4, Head: b, Base: "beta", Branch: "feat"}}}, - pulls: map[string]gitseat.Pull{ - "novox/gone#5": {Repository: "novox/gone", Number: 5, State: gitseat.PullStateClosed, Base: "main"}, - "novox/done#6": {Repository: "novox/done", Number: 6, State: gitseat.PullStateMerged, Base: "main"}}, - } - err := h.ReadForge() - if err == nil || !strings.Contains(err.Error(), "no such pull request") { - t.Fatalf("a pull request the forge does not know is said: %v", err) - } - all, _ := h.deliveries() - got := map[string]string{} - for _, d := range all { - got[fmt.Sprintf("%s#%d", d.Repository, d.Number)] = d.Commit[:1] + "/" + d.State + "/" + d.Base - } - want := map[string]string{"novox/app#3": "1/open/main", "novox/lib#4": "b/open/beta", "novox/done#6": "d/merged/main", "novox/away#7": "d/open/main"} - if fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("deliveries %v, wanted %v", got, want) - } - if len(k.m[groupsState]) != 1 { - t.Fatalf("groups %v", k.m[groupsState]) - } - h.Forge = &fakeForge{fail: true} - if err := h.ReadForge(); err == nil { - t.Fatal("a forge that cannot be read is said") - } -} - -// A-281: the switch runs once; a start, then a pull-updated, then a second start opens no record. -func TestTheSwitchRunsOnceSoDeliveriesNeverBecomeRecordsAtAStart(t *testing.T) { - h, k := gateWithDeliveries(t) - h.Old = kvKeptOld{k} - if _, _, err := h.Switch(); err != nil { - t.Fatal(err) - } - if err := h.PullUpdated(updated("novox/app", 3, strings.Repeat("a", 40), "main", "feat")); err != nil { - t.Fatal(err) - } - opened, found, err := h.Switch() - if err != nil || opened != 0 || found != 0 { - t.Fatalf("the second start switched: %d %d %v", opened, found, err) - } - if kept, _ := h.Records.Kept(); len(kept) != 0 { - t.Fatalf("a delivery became a record: %+v", kept) - } - if done, err := h.Records.SwitchDone(); err != nil || !done { - t.Fatalf("switch.done %v %v", done, err) - } -} - -type kvKeptOld struct{ k *memKept } - -func (o kvKeptOld) Keys(state string) ([]string, error) { return o.k.Keys(state) } -func (o kvKeptOld) Get(state, key string) ([]byte, uint64, error) { - v, err := o.k.Get(state, key) - return v, 1, err -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go index bae72c816..e9c5afe16 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go @@ -2,36 +2,21 @@ package main import ( "context" - "encoding/json" "fmt" - "strconv" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" - gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" stdio "git.novox.be/novox/mesh-sdk/go" - "git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/views" ) // The gate's own findings (design 47 G A-39, A-29, A-37, A-30, §592): they go through one held writer over the gate's own state -// `findings`, whose three events the manifest declares. The first is `approval-carried-open`: for each `approval-carried` the -// gate says, a carried Approve nobody uses is seen, and cleared when the seat `git` says that pull request merged or closed. +// `findings`, whose three events the manifest declares. // Module is the gate's module name, the observer of its findings. const Module = "mesh-delivery-gate" -// The scope and the kind of the finding a carried approval nobody uses is (design 47 §592, A-42: the scope the mesh already uses for the delivery's findings). -const ( - FindingScope = "delivery" - ApprovalCarriedOpen = "approval-carried-open" -) - -// pullMergedEvent and pullClosedEvent are the seat git's events that end a pull request, as the gate's manifest consumes them. -var ( - pullUpdatedEvent = declared(gitseat.EventPullUpdated) - pullMergedEvent = declared(gitseat.EventPullMerged) - pullClosedEvent = declared(gitseat.EventPullClosed) -) +// FindingScope is the scope of the gate's findings (A-42: the scope the mesh already uses for the delivery's findings). +const FindingScope = "delivery" // FindingWriter is what the gate holds of the one held writer (views.NewStdioHeldWriter over its state `findings`). type FindingWriter interface { @@ -44,55 +29,43 @@ type FindingWriter interface { // generated contract of the seat that defines it (A-17). It is started once the runtime serves (A-40). func NewFindingWriter() (*views.HeldWriter[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent], error) { return views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ - Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{ApprovalCarriedOpen, SourceUncompared}}) + Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge}}) } -// approvalID is the id of a pull request's finding: its repository and number, each escaped as a key's name is. -func approvalID(repository string, number int64) string { - return keys.EscapeName(repository) + "." + keys.EscapeName(strconv.FormatInt(number, 10)) -} - -// approvalOpen writes the finding for an `approval-carried` the gate says, naming the head the Approve named, unless it holds it. -func (h *Holder) approvalOpen(repository string, number int, head string) error { +// recordTooLarge raises record-too-large for a delivery record's entry the gate refused over EntryLimit, its subject the +// record (design 47 H2 §809; H-A-460), or clears it when the writer holds it; with no instance it clears every one the +// writer holds whose subject is the record (its end, H-A-455 (3)): the record's records hook. +func (h *Holder) recordTooLarge(record, instance string, bytes int, raised bool) { if h.Findings == nil { - return nil + return } - id := approvalID(repository, int64(number)) + var held []string for _, f := range h.Findings.Held() { - if f.Scope == FindingScope && f.ID == id && f.Kind == ApprovalCarriedOpen { - return nil + if f.Scope != FindingScope || f.Kind != RecordTooLarge { + continue + } + if instance == "" && f.Subject.ID == record || instance != "" && f.ID == instance { + held = append(held, f.ID) } } - at := h.Now().UTC() - pull := fmt.Sprintf("%s#%d", repository, number) - return h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: id, Kind: ApprovalCarriedOpen, - Subject: meshconditions.Subject{Scope: FindingScope, ID: id}, - Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", - Summary: fmt.Sprintf("the Approve of %s at %s, given before G, is carried and no merge or close of that pull request followed", pull, shortOf(head, 12)), - Headline: "An Approve carried over waits for its pull request", - Explanation: "The operator's Approve of this pull request, given before the delivery's switch, counts as its approval step. Nobody has merged or closed the pull request since.", - Needs: "merge the pull request through the seat git's merge-pull, or close it; the finding clears when the seat git says either.", - Source: "approval-carried", Observer: Module, At: at, Since: at}) -} - -// pullEnded clears the finding of a pull request the seat git said merged or closed; a pull request with none changes nothing. -func (h *Holder) pullEnded(body []byte, why string) error { - if h.Findings == nil { - return nil - } - var p struct { - Repository string `json:"repository"` - Number int64 `json:"number"` - } - if err := json.Unmarshal(body, &p); err != nil || p.Repository == "" || p.Number <= 0 { - h.Refuse(fmt.Errorf("a %s of the seat git is not readable: %v", why, err)) - return nil - } - id := approvalID(p.Repository, p.Number) - for _, f := range h.Findings.Held() { - if f.Scope == FindingScope && f.ID == id && f.Kind == ApprovalCarriedOpen { - return h.Findings.Clear(context.Background(), FindingScope, id, ApprovalCarriedOpen, "the pull request was "+why) + var err error + switch { + case raised && len(held) == 0: + now := h.Now().UTC() + err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: instance, Kind: RecordTooLarge, + Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now, + Summary: fmt.Sprintf("%s would hold %d bytes, over the %d one entry holds: the write is refused", instance, bytes, EntryLimit), + Headline: "A delivery record's entry is too large", Subject: meshconditions.Subject{Scope: FindingScope, ID: record}, + Explanation: "The gate keeps one entry per record and one per mover, each within 64 KiB (design 47 H2 §809); " + + "this entry would pass it, so the write is refused. It clears when the entry is next written within 64 KiB or the record ends."}) + case !raised: + for _, id := range held { + if e := h.Findings.Clear(context.Background(), FindingScope, id, RecordTooLarge, "the entry is written within 64 KiB, or its record ended"); e != nil { + err = e + } } } - return nil + if err != nil && h.Logf != nil { + h.Logf("[mesh-delivery] record-too-large of %s (%s) is not said: %v", instance, record, err) + } } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings_test.go deleted file mode 100644 index 20a6418a0..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "strings" - "sync" - "testing" - "time" - - "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" - stdio "git.novox.be/novox/mesh-sdk/go" - "git.novox.be/novox/mesh-sdk/go/views" -) - -// memState is the gate's state `findings` in memory. -type memState struct { - mu sync.Mutex - m map[string][]byte -} - -func (s *memState) Get(key string) (*stdio.StateEntry, error) { - s.mu.Lock() - defer s.mu.Unlock() - if v, ok := s.m[key]; ok { - return &stdio.StateEntry{Key: key, Value: v}, nil - } - return nil, nil -} -func (s *memState) Put(key string, value any) (uint64, error) { - raw, _ := json.Marshal(value) - s.mu.Lock() - defer s.mu.Unlock() - s.m[key] = raw - return 1, nil -} -func (s *memState) Delete(key string) error { s.mu.Lock(); delete(s.m, key); s.mu.Unlock(); return nil } -func (s *memState) Keys() (k []string, _ error) { - s.mu.Lock() - defer s.mu.Unlock() - for key := range s.m { - k = append(k, key) - } - return -} - -type oldFake map[string][]byte - -func (o oldFake) Keys(string) (k []string, _ error) { - for key := range o { - k = append(k, key) - } - return -} -func (o oldFake) Get(_, key string) ([]byte, uint64, error) { return o[key], 1, nil } - -// The gate's own finding (A-39, A-29, A-37, §592): written through the held writer for each approval carried, once, and cleared -// when the seat git says that pull request merged or closed; the writer's events are the manifest's. -func TestTheGatesApprovalCarriedOpenIsWrittenThroughItsHeldWriterAndClearedByTheSeatGit(t *testing.T) { - at := time.Date(2026, 11, 11, 21, 0, 0, 0, time.UTC) - head := strings.Repeat("1", 40) - state := &memState{m: map[string][]byte{}} - var mu sync.Mutex - var said []string - w, err := views.NewHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ - Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: state, Kinds: []string{ApprovalCarriedOpen}, Node: "ace", - Now: func() time.Time { return at }, - Publish: func(_ context.Context, subject string, _ []byte, _ string) error { - mu.Lock() - said = append(said, subject) - mu.Unlock() - return nil - }, - Listen: func(context.Context, string, func([]byte)) (func(), error) { return func() {}, nil }}) - if err != nil { - t.Fatal(err) - } - if err := w.Start(context.Background()); err != nil { - t.Fatal(err) - } - merge, merr := mdc.EncodeMerge(Merge{V: 1, Group: "feat/x", Ask: "merge.feat_x.0123456789ab", Approved: map[string]string{"novox/app@7": head, "novox/web@8": head, "novox/db@9": head}, - Pulls: []MergePull{{Head: mdc.Head{Repository: "novox/db", Number: 9, Head: head}, State: mdc.MergeMerged, Commit: "c0ffee"}}}.stored()) - h := &Holder{Logf: t.Logf, Now: func() time.Time { return at }, Old: oldFake{"feat_x": merge}, Findings: w, SaySeat: func(string, any, string) error { return nil }} - if merr != nil { - t.Fatal(merr) - } - if err := h.carryApprovals(); err != nil { - t.Fatal(err) - } - held := w.Held() - if len(held) != 2 { - t.Fatalf("held %+v", held) - } - for _, f := range held { - if f.Kind != ApprovalCarriedOpen || f.Scope != "delivery" || f.Observer != Module || !strings.Contains(f.Summary, head[:12]) { - t.Fatalf("finding %+v", f) - } - } - if id := approvalID("novox/app", 7); held[0].ID != id && held[1].ID != id { - t.Fatalf("no finding with id %s: %+v", id, held) - } - n := len(said) - if err := h.carryApprovals(); err != nil || len(said) != n { - t.Fatalf("said again: %v, %d events (was %d)", err, len(said), n) - } - // the seat git says one merged and the other closed; one it does not know changes nothing - if err := h.pullEnded([]byte(`{"repository":"novox/app","number":7}`), "merged"); err != nil { - t.Fatal(err) - } - if err := h.pullEnded([]byte(`{"repository":"novox/other","number":1}`), "merged"); err != nil || len(w.Held()) != 1 { - t.Fatalf("held %+v: %v", w.Held(), err) - } - if err := h.pullEnded([]byte(`{"repository":"novox/web","number":8}`), "closed"); err != nil || len(w.Held()) != 0 { - t.Fatalf("held %+v: %v", w.Held(), err) - } - got := strings.Join(said, " ") - for _, ev := range []string{"finding-written", "finding-cleared"} { - if !strings.Contains(got, ev) { - t.Fatalf("no %s said: %v", ev, said) - } - } -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/gate.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/gate.go index 05222b46c..ce7ff0db8 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/gate.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/gate.go @@ -3,8 +3,6 @@ package main import ( "sync" "time" - - oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" ) // The holder of the seat mesh-delivery (novox/hq ADR 0239, to-be 47): from milestone G's delivery it keeps no merge states @@ -20,16 +18,11 @@ type Holder struct { Settings func() Settings Now func() time.Time Logf func(format string, a ...any) - // Merges and Old are the old sections the switch reads (switch.go); Source is the gate's source (merges.go). - Merges MergeStore - // Kept is the gate's states deliveries and groups, and Forge the seat git's reads (deliveries.go, §716). - Kept DeliveryStore + // Forge is the seat git's reads (sourcestart.go). Forge ForgeReads // Catalog reads the seat mesh-catalog's registrations (sourcestart.go); startMu keeps one start of the sources at a time. Catalog Registered startMu sync.Mutex - dmu sync.Mutex - Old OldState Source SourceStore // Owed says what the gate owes the forge as the seat's event owed (owed.go). Owed OwedSayer @@ -41,19 +34,20 @@ type Holder struct { SaySeat SeatSay // Findings is the gate's one held writer of its own findings (findings.go); nil writes none. Findings FindingWriter - // Say says a condition to the operator, and Conditions keeps which the gate raised (conditions.go); nil says none. - Say func(c oc.Condition) error - Conditions ConditionStore - // said is what Conditions keeps, read at the first look; sayFailures the looks in a row a condition could not be said. - // Touched by React alone. - said map[string]string - sayFailures int + // Heads is the state heads of the watchdog (heads.go); nil watches none. + Heads HeadStore mu sync.Mutex started time.Time refusals []string // tried counts the owed effects tried since this owner started, by how each ended (novox/hq issue 407). tried owedTries + // applying keeps one event or tool call at a time on the delivery records the gate holds in memory (issue 721 note 11): + // the runtime hands each event and each call to a goroutine of its own, and each is applied whole under this lock (take, + // applied), so none reads a record another is halfway through writing. A record's entry is written to the ledger and then + // to memory under it, so an event heard once that write lands (a pipeline-wanted after the running it ends on) is applied + // only after memory holds it too. Taken before h.mu, never under it. + applying sync.Mutex // reactMu keeps one React at a time; poke asks for a look (react.go); wanted is when the next is wanted, and its timer. reactMu sync.Mutex poke chan struct{} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads.go new file mode 100644 index 000000000..c2b80d4dd --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads.go @@ -0,0 +1,277 @@ +package main + +// The watchdog (design 47 H §740; ADR 0682 §3; H-A-48): the gate consumes the forge bridge's head-moved and keeps, in its +// template state heads (one key `.`, value {head, since}), each head source. does not name for +// that repository, deleting the key once source. names that head. When untaken-bound passes and source. +// still does not name it, the gate raises head-untaken (scope delivery, id `.`), and clears it when a +// later revision names the repository at the newest head. The gate keeps one deadline timer (react.go), set to the +// earliest since plus the bound, and no other clock. Nothing but a merge call or gate_head_take (§742) delivers a head. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "sort" + "sync" + "time" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/keys" + "git.novox.be/novox/mesh-sdk/go/stateobjects" + "git.novox.be/novox/mesh-sdk/go/views" +) + +// HeadUntaken is the finding of a head no merge call delivered; warning, the operator its resolver (H-A-81). +const HeadUntaken = "head-untaken" + +const untakenSeverity = meshconditions.FindingSeverityWarning + +// WordsUntaken are the words the finding names its cause with (§740). +const WordsUntaken = "moved outside the mesh: delivered by nothing" + +// headMovedEvent is the bridge's head-moved as the gate's manifest consumes it. +var headMovedEvent = consumedFamily(forgemsg.HeadMovedEvents()) + +// HeldHead is one value of the state heads. +type HeldHead = seat.HeadsByRepositoryBranchValue + +// HeadStore is the gate's state heads. +type HeadStore interface { + Get(key string) (*HeldHead, error) + Put(key string, v HeldHead) error + Delete(key string) error + // All are every key held with its value. + All() (map[string]HeldHead, error) +} + +// kvHeads is the state heads over the runtime. +type kvHeads struct{} + +func (kvHeads) Get(key string) (*HeldHead, error) { + e, err := stdio.State(seat.StateHeads).Get(key) + if err != nil || e == nil { + return nil, err + } + v, _, err := seat.DecodeHeadsByRepositoryBranchValue(e.Value) + if err != nil { + return nil, fmt.Errorf("heads %s is not readable: %w", key, err) + } + return &v, nil +} + +func (kvHeads) Put(key string, v HeldHead) error { + _, err := prunedHeads().Put(key, v) + return err +} + +// prunedHeads is the state heads, pruned toward its cap at the gate's own writes (design 47 H2 §812; H-A-411 (3)): past +// prune-mark of its 8 MiB the oldest keys go down to prune-target, in one journal line. A setting that is no percentage +// is said, and the defaults hold. +var prunedHeads = sync.OnceValue(func() *stdio.PrunedState { + p, err := stdio.PruneSettings() + if err != nil { + fmt.Fprintf(os.Stderr, "the prune of heads keeps its defaults (%d %% to %d %%): %v\n", stdio.PruneMarkDefault, stdio.PruneTargetDefault, err) + p = stdio.Prune{Mark: stdio.PruneMarkDefault, Target: stdio.PruneTargetDefault} + } + return stdio.State(seat.StateHeads).Pruned(p) +}) + +// headsPruneTools are the gate's two prune tools over heads, each written in the hand-act log (H-A-380 (3)). +func headsPruneTools(acts views.HandActs) []stdio.Tool { + return stateobjects.PruneTools(Module, []stateobjects.Pruning{{Name: seat.StateHeads, State: prunedHeads()}}, acts) +} + +func (kvHeads) Delete(key string) error { return stdio.State(seat.StateHeads).Delete(key) } + +func (s kvHeads) All() (map[string]HeldHead, error) { + names, err := stdio.State(seat.StateHeads).Keys() + if err != nil { + return nil, err + } + out := map[string]HeldHead{} + for _, k := range names { + v, err := s.Get(k) + if err != nil { + return nil, err + } + if v != nil { + out[k] = *v + } + } + return out, nil +} + +// headKey is a held head's key and the finding's id: `.`, the branch escaped as a key's name is. +func headKey(repository, branch string) string { + return seat.HeadsByRepositoryBranchKey(repository, keys.EscapeName(branch)) +} + +// HeadMoved takes one head-moved: a head source. names is let go, another is held from when it was first heard. +// A body that cannot be read is said and taken; an error only when the state could not be read or written. +func (h *Holder) HeadMoved(e stdio.Envelope) error { + m, err := forgemsg.DecodeHeadMoved(e.Body) + if err != nil { + h.Refuse(fmt.Errorf("a head-moved (%s) is not readable, so no head is watched: %w", e.Key, err)) + return nil + } + return h.holdHead(m.Repository, m.Branch, m.Head) +} + +// holdHead holds a branch's head of a repository until source. names it. +func (h *Holder) holdHead(repository, branch, head string) error { + if h.Heads == nil || h.Source == nil { + return nil + } + src, _, err := h.Source.Read(branch) + if err != nil { + return err + } + key := headKey(repository, branch) + if src != nil && sameCommit(src.Heads[repository], head) { + return h.letHeadGo(key, "source."+branch+" names it") + } + prev, err := h.Heads.Get(key) + if err != nil { + return err + } + next := HeldHead{Head: head, Since: h.Now().UTC()} + if prev != nil { + if prev.Head == head { + return nil + } + next.Since = prev.Since // untaken since the first head no call delivered + } + if err := h.Heads.Put(key, next); err != nil { + return err + } + h.Poke() + return nil +} + +// letHeadGo deletes a held head and clears its finding. +func (h *Holder) letHeadGo(key, why string) error { + held, err := h.Heads.Get(key) + if err != nil || held == nil { + return err + } + if err := h.Heads.Delete(key); err != nil { + return err + } + return h.clearUntaken(key, why) +} + +// sourceNamed lets go every held head of a branch its newest source revision names. +func (h *Holder) sourceNamed(branch string, s Source) error { + if h.Heads == nil { + return nil + } + var errs []error + for repository, commit := range s.Heads { + key := headKey(repository, branch) + held, err := h.Heads.Get(key) + if err != nil { + errs = append(errs, err) + continue + } + if held != nil && sameCommit(commit, held.Head) { + errs = append(errs, h.letHeadGo(key, fmt.Sprintf("source.%s at %d names it", branch, s.Source))) + } + } + return errors.Join(errs...) +} + +// untakenBound is how long a head may stand untaken before head-untaken is raised. +func (h *Holder) untakenBound() time.Duration { + if h.Settings != nil { + if n := h.Settings().UntakenBoundMinutes; n != nil { + return time.Duration(*n) * time.Minute + } + } + return DefaultUntakenBound +} + +// lookAtHeads raises head-untaken for every held head past the bound that its branch's source still does not name, and +// asks the one timer for the earliest one not yet past it; taken by React. +func (h *Holder) lookAtHeads() { + if h.Heads == nil || h.Source == nil { + return + } + held, err := h.Heads.All() + if err != nil { + h.Refuse(fmt.Errorf("the held heads cannot be read: %w", err)) + h.again("heads") + return + } + names := make([]string, 0, len(held)) + for k := range held { + names = append(names, k) + } + sort.Strings(names) + now := h.Now() + for _, key := range names { + v := held[key] + repository, escaped, ok := seat.ParseHeadsByRepositoryBranchKey(key) + branch, uerr := keys.UnescapeName(escaped) + if !ok || uerr != nil { + continue + } + src, _, err := h.Source.Read(branch) + if err != nil { + h.again("heads") + continue + } + if src != nil && sameCommit(src.Heads[repository], v.Head) { + if err := h.letHeadGo(key, "source."+branch+" names it"); err != nil { + h.again("heads") + } + continue + } + due := v.Since.Add(h.untakenBound()) + if now.Before(due) { + h.lookAt(due, "head-untaken") + continue + } + if err := h.raiseUntaken(key, repository, branch, v); err != nil { + h.Refuse(err) + h.again("heads") + } + } +} + +// raiseUntaken writes head-untaken for a held head, unless the writer holds it for that head already. +func (h *Holder) raiseUntaken(key, repository, branch string, v HeldHead) error { + if h.Findings == nil { + return nil + } + summary := fmt.Sprintf("%s %s at %s since %s: %s", repository, branch, shortOf(v.Head, 12), v.Since.UTC().Format(time.RFC3339), WordsUntaken) + for _, f := range h.Findings.Held() { + if f.Scope == FindingScope && f.ID == key && f.Kind == HeadUntaken && f.Summary == summary { + return nil + } + } + raw, _ := json.Marshal(map[string]any{"repository": repository, "branch": branch, "head": v.Head, "since": v.Since}) + f := meshconditions.Finding{Scope: FindingScope, ID: key, Kind: HeadUntaken, Observer: Module, Source: headMovedEvent, + Severity: untakenSeverity, Resolver: "operator", Since: v.Since, At: h.Now().UTC(), Summary: summary, + Headline: "A head no merge call delivered", Subject: meshconditions.Subject{Scope: FindingScope, ID: key}, + Explanation: "The head of " + repository + " on " + branch + " moved outside the mesh and nothing delivers it; " + + "gate_head_take takes it in by hand (" + string(raw) + ")."} + return h.Findings.Write(context.Background(), f) +} + +// clearUntaken clears head-untaken for a key, when the writer holds it. +func (h *Holder) clearUntaken(key, why string) error { + if h.Findings == nil { + return nil + } + for _, f := range h.Findings.Held() { + if f.Scope == FindingScope && f.ID == key && f.Kind == HeadUntaken { + return h.Findings.Clear(context.Background(), FindingScope, key, HeadUntaken, why) + } + } + return nil +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads_test.go new file mode 100644 index 000000000..314ae747e --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/heads_test.go @@ -0,0 +1,173 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "os" + "strings" + "testing" + "time" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" + stdio "git.novox.be/novox/mesh-sdk/go" +) + +// memHeads is the state heads in memory. +type memHeads map[string]HeldHead + +func (m memHeads) Get(key string) (*HeldHead, error) { + if v, ok := m[key]; ok { + return &v, nil + } + return nil, nil +} +func (m memHeads) Put(key string, v HeldHead) error { m[key] = v; return nil } +func (m memHeads) Delete(key string) error { delete(m, key); return nil } +func (m memHeads) All() (map[string]HeldHead, error) { + out := map[string]HeldHead{} + for k, v := range m { + out[k] = v + } + return out, nil +} + +// findingsFake is the gate's held writer: what it holds. +type findingsFake struct { + held map[string]meshconditions.Finding + written int +} + +func (f *findingsFake) Write(_ context.Context, x meshconditions.Finding) error { + f.held[x.Scope+"."+x.ID+"."+x.Kind] = x + f.written++ + return nil +} +func (f *findingsFake) Clear(_ context.Context, scope, id, kind, _ string) error { + delete(f.held, scope+"."+id+"."+kind) + return nil +} +func (f *findingsFake) Held() []meshconditions.Finding { + var out []meshconditions.Finding + for _, x := range f.held { + out = append(out, x) + } + return out +} + +// GATE-6 (design 47 H §740; acceptance test 111's gate half): a head a merge call moved raises nothing; a head pushed outside +// the mesh is held and raises head-untaken once untaken-bound passes, naming the repository, the branch, the head, since when +// and why, and starts nothing; a later merge call taking its repository in clears it. The one timer is asked for the earliest +// held head. +func TestAHeadNoMergeCallDeliveredIsAnUntakenHead(t *testing.T) { + at := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC) + c1, c2 := strings.Repeat("1", 40), strings.Repeat("2", 40) + setup := func() (*Holder, memHeads, *findingsFake, *time.Time) { + now := at + heads := memHeads{} + fw := &findingsFake{held: map[string]meshconditions.Finding{}} + h := &Holder{Now: func() time.Time { return now }, Heads: heads, Findings: fw, + Source: &memSource{vals: map[string]Source{"main": {Source: 4, Call: "00000000000000aa", Heads: map[string]string{"novox/app": c1}}}}} + h.init() + h.SaySeat = func(string, any, string) error { return nil } + return h, heads, fw, &now + } + moved := func(head string) stdio.Envelope { + return stdio.Envelope{Key: "mesh-delivery-forge-bridge.forge.novox.app.main.head-moved", + Body: json.RawMessage(`{"v":1,"repository":"novox/app","branch":"main","head":"` + head + `"}`)} + } + t.Run("a head the source names raises nothing", func(t *testing.T) { + h, heads, fw, now := setup() + if err := h.HeadMoved(moved(c1)); err != nil { + t.Fatal(err) + } + *now = at.Add(time.Hour) + h.React() + if len(heads) != 0 || len(fw.held) != 0 { + t.Fatalf("held %+v, findings %+v", heads, fw.held) + } + }) + t.Run("a head pushed outside the mesh raises head-untaken past the bound and clears on a later merge call", func(t *testing.T) { + h, heads, fw, now := setup() + if err := h.HeadMoved(moved(c2)); err != nil { + t.Fatal(err) + } + h.React() + if heads["novox/app.main"].Head != c2 || len(fw.held) != 0 || !h.wanted.at.Equal(at.Add(DefaultUntakenBound)) { + t.Fatalf("held %+v, findings %+v, next look %s", heads, fw.held, h.wanted.at) + } + *now = at.Add(DefaultUntakenBound) + h.React() + f, ok := fw.held["delivery.novox/app.main."+HeadUntaken] + if !ok || f.Severity != meshconditions.FindingSeverityWarning || f.Resolver != "operator" || !f.Since.Equal(at) || + !strings.Contains(f.Summary, "novox/app main at 222222222222") || !strings.Contains(f.Summary, WordsUntaken) { + t.Fatalf("findings %+v", fw.held) + } + h.React() + if fw.written != 1 { + t.Fatalf("head-untaken written %d times", fw.written) + } + member := `{"repository":"novox/app","number":9,"branch":"main","head":"h","commit":"` + c2 + `"}` + if err := h.MergeCalled(stdio.Envelope{Key: "git.merge-called.0123456789abcdef", Body: json.RawMessage( + `{"call":"0123456789abcdef","by":"lead@shanks","account":"a","at":"2026-11-20T04:30:00Z","members":[` + member + `]}`)}); err != nil { + t.Fatal(err) + } + if len(heads) != 0 || len(fw.held) != 0 { + t.Fatalf("after the merge call: held %+v, findings %+v", heads, fw.held) + } + }) + // GATE-7 (§742): gate_heads reads each held head with since and finding; gate_head_take writes one revision of its own + // call, opens its record marked by hand, writes the hand-act log first and clears the finding. + t.Run("gate_heads reads the held heads; gate_head_take takes one in after the log and clears head-untaken", func(t *testing.T) { + h, heads, fw, now := setup() + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now} + if err := h.HeadMoved(moved(c2)); err != nil { + t.Fatal(err) + } + *now = at.Add(DefaultUntakenBound) + h.React() + out, err := h.HeadsHeld() + lines, _ := out["heads"].([]HeadLine) + if err != nil || len(lines) != 1 || lines[0].Repository != "novox/app" || lines[0].Branch != "main" || lines[0].Head != c2 || + !strings.Contains(lines[0].Finding, WordsUntaken) || lines[0].Since == "" { + t.Fatalf("gate_heads %+v %v", out, err) + } + acts := &handActsFake{refuse: errors.New("log down")} + if _, err := h.HeadTake("novox/app", "main", "pushed by hand", "lead@shanks", acts); err == nil || len(heads) != 1 { + t.Fatalf("taken without the log: %v", err) + } + acts.refuse = nil + if _, err := h.HeadTake("novox/other", "main", "x", "lead@shanks", acts); err == nil { + t.Fatal("a head the gate does not hold is taken") + } + got, err := h.HeadTake("novox/app", "main", "pushed by hand", "lead@shanks", acts) + if err != nil || got["source"] != int64(5) || len(acts.took) != 1 || acts.took[0].Cause != "gate_head_take" { + t.Fatalf("take %+v %v, log %+v", got, err, acts.took) + } + src, _, _ := h.Source.Read("main") + kept, _ := h.Records.Kept() + if src.Heads["novox/app"] != c2 || len(heads) != 0 || len(fw.held) != 0 || len(kept) != 1 || kept[0].Trace == nil || + !kept[0].Trace.Hand || kept[0].Trace.By != "lead@shanks" || kept[0].Heads["novox/app@222222222222"] != c2 { + t.Fatalf("source %+v, held %+v, findings %+v, records %+v", src, heads, fw.held, kept) + } + }) + t.Run("the setting untaken-bound, at least one minute", func(t *testing.T) { + h, _, _, _ := setup() + n := 3 + h.Settings = func() Settings { return Settings{UntakenBoundMinutes: &n} } + if h.untakenBound() != 3*time.Minute { + t.Fatalf("bound %s", h.untakenBound()) + } + for raw, ok := range map[string]bool{`{"untaken-bound":1}`: true, `{"untaken-bound":0}`: false, `{"untaken-bound":1.5}`: false} { + p := t.TempDir() + "/s.json" + if err := writeFile(p, raw); err != nil { + t.Fatal(err) + } + if _, err := readSettings(p); (err == nil) != ok { + t.Errorf("%s: %v", raw, err) + } + } + }) +} + +func writeFile(p, s string) error { return os.WriteFile(p, []byte(s), 0o600) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/headtools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/headtools.go new file mode 100644 index 000000000..3e26a3d01 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/headtools.go @@ -0,0 +1,121 @@ +package main + +// Taking an untaken head in by hand (design 47 H §742; ADR 0682 §3; H-A-24, H-A-48): gate_heads reads the state heads with +// each head's since and finding; gate_head_take, with repository, branch and why, written in the hand-act log first, names +// that head a source revision as a merge call does (§737), its call one of its own and its trace marked by hand with who and +// when, its record's member `@`, and the chain follows. Nothing else delivers an untaken head. + +import ( + "errors" + "fmt" + "sort" + "strings" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/keys" +) + +// HeadLine is one held head as gate_heads reads it. +type HeadLine struct { + Repository string `json:"repository"` + Branch string `json:"branch"` + Head string `json:"head"` + Since string `json:"since"` + // Finding is head-untaken's summary when it is raised. + Finding string `json:"finding,omitempty"` +} + +// HeadsHeld is gate_heads: every held head, ordered by key. +func (h *Holder) HeadsHeld() (map[string]any, error) { + if h.Heads == nil { + return nil, errors.New("this gate watches no heads") + } + held, err := h.Heads.All() + if err != nil { + return nil, err + } + raised := map[string]string{} + if h.Findings != nil { + for _, f := range h.Findings.Held() { + if f.Scope == FindingScope && f.Kind == HeadUntaken { + raised[f.ID] = f.Summary + } + } + } + lines := []HeadLine{} + for key, v := range held { + repository, escaped, ok := seat.ParseHeadsByRepositoryBranchKey(key) + branch, err := keys.UnescapeName(escaped) + if !ok || err != nil { + continue + } + lines = append(lines, HeadLine{Repository: repository, Branch: branch, Head: v.Head, Since: timeText(&v.Since), Finding: raised[key]}) + } + sort.Slice(lines, func(i, j int) bool { + return headKey(lines[i].Repository, lines[i].Branch) < headKey(lines[j].Repository, lines[j].Branch) + }) + return map[string]any{"heads": lines}, nil +} + +// HeadTake is gate_head_take: the held head of a repository on a branch named one source revision, after the hand-act log took it. +func (h *Holder) HeadTake(repository, branch, why, by string, acts handActs) (map[string]any, error) { + if strings.TrimSpace(repository) == "" || strings.TrimSpace(branch) == "" || strings.TrimSpace(why) == "" { + return nil, errors.New("say the repository, the branch and why its head is taken in by hand") + } + if h.Heads == nil || h.Source == nil { + return nil, errors.New("this gate watches no heads or keeps no source") + } + held, err := h.Heads.Get(headKey(repository, branch)) + if err != nil { + return nil, err + } + if held == nil { + return nil, fmt.Errorf("the gate holds no untaken head of %s on %s: gate_heads lists them", repository, branch) + } + if acts == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was taken in") + } + at := h.Now().UTC() + if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("took the head %s of %s on %s in by hand (hand by %s at %s)", + shortOf(held.Head, 12), repository, branch, by, at.Format("2006-01-02T15:04:05Z")), Why: why, Cause: "gate_head_take", + Verb: "head-take"}); err != nil { + return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was taken in: %w", err) + } + call, err := newCall() + if err != nil { + return nil, err + } + member := IDOf(repository, held.Head) + trace := RecordTrace{Call: call, By: by, Hand: true, At: at, Pulls: []string{member}, Commits: []string{held.Head}} + if err := h.deliverRevision(branch, call, []revisionHead{{Repository: repository, Commit: held.Head}}, + map[string]string{member: held.Head}, trace); err != nil { + return nil, err + } + named, _, err := h.Source.Read(branch) + if err != nil || named == nil { + return nil, fmt.Errorf("the head is taken in and source.%s cannot be read back: %v", branch, err) + } + return map[string]any{"repository": repository, "branch": branch, "head": held.Head, "source": named.Source, "call": call, "by": by}, nil +} + +// headTools are the watchdog's tools; acts is the hand-act log. +func headTools(h *Holder, acts handActs) []stdio.Tool { + return []stdio.Tool{ + {Name: "gate_heads", + Description: "Every watched branch's head the gate holds as untaken (design 47 H §740, §742): moved, and named by no source " + + "revision yet, each with its repository, branch, head, since when, and head-untaken's summary once raised. Read, never written.", + Run: func(map[string]any) (any, error) { return h.HeadsHeld() }}, + {Name: "gate_head_take", + Description: "Take one untaken head in by hand (design 47 H §742): the head the gate holds for the repository on the branch is " + + "named one source revision as a merge call does, with its record, and the chain follows; recorded in the hand-act log of " + + "the seat mesh-hand-acts first. Nothing else delivers a head moved outside the mesh.", + Input: map[string]any{"type": "object", "properties": map[string]any{"repository": str("owner/repository"), + "branch": str("the watched branch"), "why": str("why it is taken in by hand, in plain words")}, + "required": []string{"repository", "branch", "why"}}, + Run: func(a map[string]any) (any, error) { + return h.HeadTake(strArg(a, "repository"), strArg(a, "branch"), strArg(a, "why"), stdio.CallerOf(a), acts) + }}, + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps.go index 2ee1d5c80..1c271c859 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps.go @@ -6,7 +6,7 @@ import "git.novox.be/novox/mesh-sdk/go/announce" // issue 1790): the module says it itself, from its code, before it serves, and a reader is granted what it said // (clause 3). A state is readable when another module's manifest reads it (keeps_test.go names the readers). keeps_test.go holds the list to the // manifest's `state`, and keeps_integration_test.go that the module announces it on a bus. -var Kept = []announce.State{{Name: "conditions"}, {Name: "deliveries"}, {Name: "findings"}, {Name: "groups"}, {Name: "merges", Readable: true}, {Name: "owed", Readable: true}, {Name: "source", Readable: true}} +var Kept = []announce.State{{Name: "findings"}, {Name: "heads"}, {Name: "source", Readable: true}} // announceKept says Kept through keeps, which is stdio.Keeps. func announceKept(keeps func(...announce.State) error) error { return keeps(Kept...) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps_test.go index 4694f8f7c..6dc6bd231 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/keeps_test.go @@ -11,16 +11,10 @@ import ( // readers is the gate's own declaration of who reads its states (ADR 0495 clause 3: a read is granted only when the owner // announced the state readable), kept here and not read from other repositories' manifests (clause 1). Each line names -// the modules of mesh-delivery whose manifest reads the state, as of R4e. +// the modules of mesh-delivery whose manifest reads the state; the checker, retired whole in H1 (design 47 H §764), reads +// none. var readers = map[string][]string{ - "asks": {"mesh-delivery-teller", "mesh-delivery-view"}, - "merges": {"mesh-delivery-forge-bridge"}, - "pulls": {"build-agent"}, // in mesh-controller - "owed": {"mesh-delivery-forge-bridge"}, - "source": {"mesh-delivery-indexer", "mesh-delivery-checker"}, - // ADR 0548 §3, §4: the checker reads the merge turns and claims no check of a repository one names; the gate alone writes - // them (a state is written by its owner's account alone, ADR 0495 §3: announcing it readable grants a read, never a write). - "turns": {"mesh-delivery-checker"}, + "source": {"mesh-delivery-indexer"}, } // 1790/S: the states the module announces are the states its manifest declares, no more, no fewer, and the readable @@ -75,8 +69,8 @@ func TestTheStatesTheModuleAnnouncesAreTheStatesItsManifestDeclares(t *testing.T } } -// Design 47 G §613 (A-20): deliveries, groups, owed and conditions are `requires` entries of the template `state` under -// their local names, taking the buckets they already had; merges and source stay in the old `state` section. +// Design 47 G §613 (A-20): conditions is a `requires` entry of the template `state` under its local name, taking the +// bucket it already had; source stays in the old `state` section; merges, the old owed, deliveries and groups go (design 47 H §764). func TestTheFourStatesMoveToTheTemplateAndTwoStayOld(t *testing.T) { raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { @@ -97,12 +91,12 @@ func TestTheFourStatesMoveToTheTemplateAndTwoStayOld(t *testing.T) { } old := string(raw[strings.Index(string(raw), `"state": [`):]) old = old[:strings.Index(old, "]")] - for _, n := range []string{"deliveries", "groups", "owed", "conditions"} { + for _, n := range []string{"heads"} { // the stalled conditions' state went (H-A-48); heads is the watchdog's (§740) if !moved[n] || strings.Contains(old, `"`+n+`"`) { t.Errorf("%s: template state %v, old section lists it %v", n, moved[n], strings.Contains(old, `"`+n+`"`)) } } - for _, n := range []string{"merges", "source"} { + for _, n := range []string{"source"} { if moved[n] || !strings.Contains(old, `"`+n+`"`) { t.Errorf("%s stays in the old section", n) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index ec423fb96..a8658de1f 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -7,6 +7,7 @@ package main import ( "context" + "encoding/json" "errors" "fmt" "os" @@ -32,7 +33,7 @@ func (l *listening) get() string { l.mu.Lock(); defer l.mu.Unlock(); return l.n // The events this owner follows: the forge bridge's word on an act owed, and the step events the delivery records are built // from (consumer.go). -var followed = append(append([]string{owedEndedEvent}, stepPatterns()...), pullUpdatedEvent, pullMergedEvent, pullClosedEvent, registrationChangedEvent, forgeMergedEvent) +var followed = append(append([]string{owedEndedEvent, mergeCalledEvent, headMovedEvent}, stepPatterns()...), registrationChangedEvent) func main() { settingsFile := os.Getenv("MESH_DELIVERY_GATE_SETTINGS") @@ -54,22 +55,19 @@ func main() { h := &Holder{ Settings: settings, Logf: logf, - Merges: kvMerges{}, Source: kvSource{}, Owed: seatOwed{say: stdio.SeatPublish}, - // The gate says what stalled to the operator itself (issue 1275, ADR 0437 §9). - Say: sayOnSeat, - Conditions: kvConditions{}, + Heads: kvHeads{}, } h.init() h.SaySeat = stdio.SeatPublish - h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf} + h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, + Class: seatCatalog{ask: stdio.Ask}.Class} h.Records.Changed = h.recordChanged - h.Old = kvOld{} - h.Kept = kvKept{} h.Forge = seatGit{ask: stdio.Ask} h.Catalog = seatCatalog{ask: stdio.Ask} - h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn} + h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn, + Follow: h.Follow} // The gate's one held writer of its own findings (design 47 G A-39, A-37, A-40): made at once, started once the runtime serves. fw, err := NewFindingWriter() if err != nil { @@ -100,8 +98,6 @@ func main() { // tick, no forge poll, no reconcile loop. Each step is retried, each failure said, never given up on quietly. func run(h *Holder, l *listening) { <-stdio.Served() // Serve first: the state is reached through it, and an event is heard from as soon as it serves - switchToRecords(h, l) - statePins(h, l) go h.Work() for _, pattern := range followed { pattern := pattern @@ -116,48 +112,10 @@ func run(h *Holder, l *listening) { } } l.set("listening") + h.Poke() // the heads held before a stop are looked at, and the one timer armed for them (§740) logf("[mesh-delivery] listening: %s", strings.Join(followed, ", ")) // A watched branch no source key holds starts from the forge, once at each start and at each registration change (A-401). - // then each head is compared with the forge's, and a merge made outside the gate is followed (A-464). - go func() { - startSourcesAtStart(h) - if _, err := h.FollowAtStart(); err != nil { - logf("[mesh-delivery] the sources were not all compared with the forge's heads: %v", err) - } - }() - // A missed pull event is put right from the forge's own record, once at each start (§716). - if err := h.ReadForge(); err != nil { - logf("[mesh-delivery] the open pull requests were not read from the forge, they are read again at the next start: %v", err) - } -} - -// switchToRecords carries the groups in flight into their delivery records (switch.go), retrying until it can: no event is -// taken before, so no outcome reaches a record the switch has not opened yet. -func switchToRecords(h *Holder, l *listening) { - for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { - opened, found, err := h.Switch() - if err == nil { - logf("[mesh-delivery] the switch to the delivery records: %d opened, %d already there", opened, found) - return - } - l.set("not yet: " + err.Error()) - logf("[mesh-delivery] the switch to the delivery records cannot be made yet (%v); asking again in %s", err, wait) - time.Sleep(wait) - } -} - -// statePins says every pin the records hold once at each start (design 47 G §579), retrying until it can. -func statePins(h *Holder, l *listening) { - for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { - n, err := h.Records.StatePins() - if err == nil { - logf("[mesh-delivery] pins stated: %d", n) - return - } - l.set("not yet: " + err.Error()) - logf("[mesh-delivery] the pins cannot be stated yet (%v); asking again in %s", err, wait) - time.Sleep(wait) - } + go startSourcesAtStart(h) } // handle takes one event, then asks for a look at every step the event makes possible (Work, React). An event that cannot be read is @@ -168,29 +126,49 @@ func handle(h *Holder, e stdio.Envelope) error { return taken } +// applied is a call applied whole, one at a time with the events (Holder.applying), its answer taken under the same lock: a +// view of a record the gate keeps is written out before the next event writes that record. A verb that changes a delivery +// asks for a look at what it makes possible (react.go). +func (h *Holder) applied(run func(map[string]any) (any, error)) func(map[string]any) (any, error) { + return func(a map[string]any) (any, error) { + out, err := func() (any, error) { + h.applying.Lock() + defer h.applying.Unlock() + out, err := run(a) + if err != nil || out == nil { + return out, err + } + raw, err := json.Marshal(out) + if err != nil { + return nil, err + } + return json.RawMessage(raw), nil + }() + h.Poke() + return out, err + } +} + +// take applies one event whole, one at a time (Holder.applying). func take(h *Holder, e stdio.Envelope) error { + h.applying.Lock() + defer h.applying.Unlock() if h.Consumer != nil && h.Consumer.Takes(e.Key) { return h.Consumer.Hear(e) } + if stdio.TopicMatches(headMovedEvent, e.Key) { + return h.HeadMoved(e) + } + if stdio.TopicMatches(mergeCalledEvent, e.Key) { + return h.MergeCalled(e) + } if e.Key == owedEndedEvent { return h.OwedEnded(e.Body) } - if e.Key == pullUpdatedEvent { - return h.PullUpdated(e.Body) - } - if e.Key == pullMergedEvent { - return errors.Join(h.DeliveryMerged(e.Body), h.pullEnded(e.Body, "merged")) - } if e.Key == registrationChangedEvent { _, err := h.StartSources() return err } - if forgeMergedEvent != "" && stdio.TopicMatches(forgeMergedEvent, e.Key) { - return h.ForgeMerged(e.Body) - } - if e.Key == pullClosedEvent { - return errors.Join(h.DeliveryClosed(e.Body), h.pullEnded(e.Body, "closed")) - } return nil } @@ -248,12 +226,24 @@ func tools(h *Holder, l *listening) []stdio.Tool { {Name: seat + "deliveries", Description: "Every delivery record the gate keeps, as it is kept (design 47 G A-24): the open ones, and those that ended in " + "the last thirty days (all: every one kept), each with its milestone or group, its pull requests, its entries' outcomes " + - "per node, its acts owed the forge and why it is not ended. Narrowed by state (open or ended), repository or group.", + "per node, its acts owed the forge and why it is not ended. Narrowed by state (open or ended), repository, group, module, " + + "outcome or since while it reads, at most 768 KB a page with capped, total and the next page's cursor (design 47 H2 §811).", Input: map[string]any{"type": "object", "properties": map[string]any{"state": str("open or ended"), "repository": str("owner/repository"), "group": str("a group's id (its branch name)"), - "all": map[string]any{"type": "string", "enum": []string{"true", "false"}}}}, + "all": map[string]any{"type": "string", "enum": []string{"true", "false"}}, + "module": str("only the deliveries that move this module"), "outcome": str("only the deliveries that ended with this outcome"), + "since": str("only the deliveries opened at or after this time, RFC 3339"), "next": str("the cursor the previous page answered")}}, Run: func(a map[string]any) (any, error) { - return h.Deliveries(strArg(a, "state"), strArg(a, "repository"), strArg(a, "group"), boolArg(a, "all")) + f := DeliveriesFilter{State: strArg(a, "state"), Repository: strArg(a, "repository"), Group: strArg(a, "group"), + Module: strArg(a, "module"), Outcome: strArg(a, "outcome"), All: boolArg(a, "all"), Next: strArg(a, "next")} + if since := strArg(a, "since"); since != "" { + t, err := time.Parse(time.RFC3339, since) + if err != nil { + return nil, fmt.Errorf("deliveries: since %q is no RFC 3339 time", since) + } + f.Since = t + } + return h.Deliveries(f) }}, {Name: seat + "show", Description: "One delivery record whole, as it is kept: by its instance, its milestone, its group's id or the id of one of " + @@ -261,15 +251,6 @@ func tools(h *Holder, l *listening) []stdio.Tool { Input: map[string]any{"type": "object", "properties": map[string]any{"id": str("a delivery's id, or a group's")}, "required": []string{"id"}}, Run: func(a map[string]any) (any, error) { return h.Show(strArg(a, "id")) }}, - {Name: seat + "groups", - Description: "Every delivery group, from the delivery records: its members, its state (open or ended), why, and the acts the " + - "gate said it owes the forge for it, each with its id and its recorded outcome (design 47 *What the gate owes the " + - "forge*). With a group, that group alone, ended or not, and no groups for a group it does not know. What reached the " + - "machines is the delivery view's.", - Input: map[string]any{"type": "object", "properties": map[string]any{ - "all": map[string]any{"type": "string", "enum": []string{"true", "false"}, "description": "\"true\": the groups that ended too"}, - "group": str("one group's id: that group alone, ended or not")}}, - Run: func(a map[string]any) (any, error) { return h.Groups(boolArg(a, "all"), strArg(a, "group")), nil }}, {Name: seat + "source", Description: "The source revision the gate holds: every repository it names, its trunk branch and that trunk's head, the " + "group that moved it last and its revision. Read, never written: a node-engine reads the repositories here to call a " + @@ -308,14 +289,12 @@ func tools(h *Holder, l *listening) []stdio.Tool { } list = append(list, recordTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...) list = append(list, sourceTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...) - // A verb that changes a delivery asks for a look at what it makes possible (react.go). + list = append(list, headTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...) + // The prune of heads by hand, now or kept from it (design 47 H2 §812, H-A-380 (3)). + list = append(list, headsPruneTools(meshhandactsclient.Recorder{Ask: stdio.Ask})...) + // Each call is applied whole, one at a time with the events, and asks for a look after (applied). for i := range list { - run := list[i].Run - list[i].Run = func(a map[string]any) (any, error) { - out, err := run(a) - h.Poke() - return out, err - } + list[i].Run = h.applied(list[i].Run) } return list } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go index de4dac66d..304fee87e 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go @@ -9,6 +9,7 @@ import ( "sort" "strings" "testing" + "time" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "git.novox.be/novox/mesh-sdk/go/buscalls" @@ -94,8 +95,9 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { t.Fatal("the manifest declares a seat; mesh-delivery is the mesh's own") } // The verbs the seat keeps: times, what-if, release, stop and retire-history went with the plans (ADR 0539 §17), and - // settle and checks with the merge states (design 47 G §431); recovery is G's (§81, A-23). - if want := []string{"deliveries", "show", "groups", "source", "recovery", "stalled"}; !reflect.DeepEqual(m.Claims[0].Serves, want) { + // settle and checks with the merge states (design 47 G §431); recovery is G's (§81, A-23); groups with the group model + // (H §764, H-A-28). + if want := []string{"deliveries", "show", "source", "recovery", "stalled"}; !reflect.DeepEqual(m.Claims[0].Serves, want) { t.Fatalf("serves %v, wanted %v", m.Claims[0].Serves, want) } // The forge messages' layout is the bridge's published package forgemsg, taken by its series (ADR 0634 §3, design 32). @@ -115,10 +117,14 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { } // The names move (milestone 47/G): the families heard from another module are its manifest's consumes, and no Go // source of the gate names those modules. - if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 1 || - !slices.Contains(m.Consumes, stepFamilies[0].Pattern) || stepFamilies[0].Owner+"."+stepFamilies[0].Event != stepFamilies[0].Pattern { + if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 8 { t.Fatalf("owed.ended is %q and the step families %+v, not the manifest's consumes %v", owedEndedEvent, stepFamilies, m.Consumes) } + for _, f := range stepFamilies { + if f.Pattern == "" || !slices.Contains(m.Consumes, f.Pattern) || !strings.HasPrefix(f.Pattern, f.Owner+"."+f.Kind) { + t.Errorf("the step family %+v is not one the manifest consumes %v", f, m.Consumes) + } + } sources, _ := filepath.Glob("*.go") for _, f := range sources { if strings.HasSuffix(f, "_test.go") { @@ -135,33 +141,29 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { } } // From G's delivery the gate hears neither the bridge's pushed messages nor the teller's answers nor the view's reach - // (design 47 G §592, §593); it hears the bridge's merged message alone, to follow every merge (A-464): it consumes the indexer's take-in.taken and the bridge's owed.ended, and the git events that clear - // an approval carried. + // (design 47 G §592, §593), and from H1 not its merged message either (design 47 H §737, §764): it consumes the indexer's + // take-in.taken and the bridge's owed.ended. if want := append(slices.Clone(followed), meshconditions.Seat+"."+meshconditions.EventFindingsAsked); !reflect.DeepEqual(m.Consumes, want) { t.Fatalf("consumes %v, follows %v", m.Consumes, followed) } for _, c := range m.Consumes { - if c == forgeMergedEvent { - continue // A-464: the source follows every merge, so the gate hears the forge bridge's merged message, and it alone - } for _, gone := range []string{".forge.", "teller", "view", "forge-pull", "forge-status"} { - if strings.Contains(c, gone) { + if strings.Contains(c, gone) && c != headMovedEvent { // the bridge's one message is the watchdog's (H §740) t.Errorf("the manifest still consumes %s, which G's gate does not hear (§431, §592, §593)", c) } } } - // A-30: the events its held writer says are declared in the manifest, and the two events that clear its finding are consumed. - if !strings.Contains(raw, `"finding-written.*"`) || !strings.Contains(raw, `"finding-cleared.*"`) || !strings.Contains(raw, `"findings-stated.*"`) || - pullMergedEvent == "" || pullClosedEvent == "" || pullUpdatedEvent == "" { - t.Fatalf("the finding events are not declared, or the pull events not consumed: %q %q", pullMergedEvent, pullClosedEvent) + // A-30: the events its held writer says are declared in the manifest. + if !strings.Contains(raw, `"finding-written.*"`) || !strings.Contains(raw, `"finding-cleared.*"`) || !strings.Contains(raw, `"findings-stated.*"`) { + t.Fatal("the finding events are not declared") } - if !reflect.DeepEqual(m.Emits, []string{"transition"}) { // `group` and `merged` go with the merge states (§431) + if len(m.Emits) != 0 { // `group` and `merged` go with the merge states (§431), `transition` with H (H-A-48) t.Fatalf("emits %v", m.Emits) } // Two buckets still in the old `state` (merges, source), `pulls` and `asks` gone (§613), the four of the template `state` moved to `requires` (design 47 G §613), and no `asked` (the teller asks, ADR 0437 §6): ADR 0450 §3 and the conditions it raised (issue 1275). No // `turns`, no turn tool and no `check-gates-merge`: no check gates a merge (novox/hq ADR 0661 §1, §2, §6). buckets := m.buckets() - if !reflect.DeepEqual(buckets, []string{"merges", "source"}) { + if !reflect.DeepEqual(buckets, []string{"source"}) { // merges goes (design 47 H §764) t.Fatalf("state %v", buckets) } for _, tool := range m.Tools { @@ -183,10 +185,10 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { t.Fatalf("reads %v", m.Reads) } // It calls no controller verb and no forge verb: the forge's reads and writes are the bridge's (ADR 0437 §8; design 47 §592). - // It uses operator-channel only to say its conditions (ADR 0437 §9, issue 1275): the teller asks no more (§431). - want := []string{"seat:git.branch", "seat:git.open-pulls", "seat:git.pull", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", WantsEntryVerb, EngineCompositionVerb} - if !reflect.DeepEqual(m.Uses, []string{"operator-channel"}) { - t.Fatalf("uses %v: operator-channel, for its conditions alone", m.Uses) + // It uses no operator-channel: its stalled conditions went, the watchman's record-open the one signal (H-A-48). + want := []string{"seat:git.branch", "seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", WantsEntryVerb, EngineCompositionVerb} + if len(m.Uses) != 0 { + t.Fatalf("uses %v", m.Uses) } if !reflect.DeepEqual(m.Invokes, want) { t.Fatalf("invokes %v, wanted %v", m.Invokes, want) @@ -293,7 +295,7 @@ func TestTheGateHoldsTheSeatAsTheSDKsTableOfRelease6HasIt(t *testing.T) { served[verb] = true } } - for _, removed := range []string{"settle", "checks", "table", "recheck", "close"} { // design 47 G §431 + for _, removed := range []string{"settle", "checks", "table", "recheck", "close", "groups"} { // design 47 G §431, H §764 if served[removed] { t.Errorf("the gate serves %s, which G removed with the merge states", removed) } @@ -301,9 +303,79 @@ func TestTheGateHoldsTheSeatAsTheSDKsTableOfRelease6HasIt(t *testing.T) { t.Errorf("the manifest serves %s, which G removed with the merge states", removed) } } - for _, verb := range []string{"deliveries", "show", "groups", "stalled", "recovery"} { + for _, verb := range []string{"deliveries", "show", "stalled", "recovery"} { if !served[verb] { t.Errorf("the gate does not serve %s, which the seat keeps", verb) } } } + +// GATE-1/AC1 (design 47 H §764): the earlier model's states leave the gate, as its manifest, its announced states and its +// code say: no `merges`, `owed` (the old bucket), `asks`, `pulls` or `turns`, and no `approval-carried` said. +func TestTheEarlierModelsStatesAndApprovalAreGone(t *testing.T) { + m, _ := readManifest(t) + kept := []string{} + for _, s := range Kept { + kept = append(kept, s.Name) + } + gone := []string{"merges", "owed", "asks", "pulls", "turns"} + for _, row := range []struct { + where string + names []string + }{{"the manifest's state and requires", m.withTemplateStates()}, {"the announced states", kept}} { + for _, n := range gone { + if slices.Contains(row.names, n) { + t.Errorf("%s still name %s", row.where, n) + } + } + } + sources, _ := filepath.Glob("*.go") + for _, f := range sources { + if strings.HasSuffix(f, "_test.go") { + continue + } + raw, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"approval-carried", "ApprovalCarried", "SwitchedOwed"} { + if strings.Contains(string(raw), name) { + t.Errorf("%s still names %s", f, name) + } + } + } +} + +// GATE-2/AC2 (design 47 H §764): the per-pull-request model goes: the gate consumes no pull request event, keeps no +// `deliveries` or `groups`, reads no open pull request, and `deliveries` and `show` answer from the +// records alone. +func TestTheGroupsFromBranchNamesAreGone(t *testing.T) { + m, _ := readManifest(t) + for _, c := range m.Consumes { + if strings.HasPrefix(c, "git.pull-") { + t.Errorf("the manifest consumes %s", c) + } + } + for _, n := range []string{"deliveries", "groups"} { + if slices.Contains(m.withTemplateStates(), n) { + t.Errorf("the manifest still keeps %s", n) + } + } + for _, v := range []string{"seat:git.open-pulls", "seat:git.pull"} { + if slices.Contains(m.Invokes, v) { + t.Errorf("the manifest still invokes %s", v) + } + } + h := &Holder{Now: func() time.Time { return time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) }, Logf: func(string, ...any) {}} + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now} + if _, _, err := h.Records.Open(opening("main", 7, map[string]string{"novox/app#3": strings.Repeat("a", 40)})); err != nil { + t.Fatal(err) + } + d, err := h.Deliveries(DeliveriesFilter{All: true}) + if err != nil || len(d["deliveries"].([]recordView)) != 1 { + t.Fatalf("deliveries from the records: %v %v", d, err) + } + if s, err := h.Show("main.7"); err != nil || len(s.(map[string]any)["records"].([]recordView)) != 1 { + t.Fatalf("show from the records: %v %v", s, err) + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go new file mode 100644 index 000000000..c21674dd2 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go @@ -0,0 +1,231 @@ +//go:build integration + +package main + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" + meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" + "git.novox.be/novox/mesh-sdk/go/keys" + "github.com/nats-io/nats.go/jetstream" +) + +// The gate whole, over a real bus (design 47 H §737, §738, §740, §742, §768; acceptance tests 110 and 111's gate half): +// a head held past untaken-bound from before a stop raises head-untaken at the start; a merge-called the forge module says +// names one source revision of a branch holding `/` and `.`, opens its delivery record and says source-moved, and the +// head-moved of that merge then holds nothing, the source key read with the escaping it is written with (H-A-87 (2)); a +// head-moved no call delivered is held; the indexer's take-in.taken of the revision writes its movers into the record; +// after gate_source_seed a head-moved at the seeded head holds nothing. The gate asks the controller nothing. +const eventWithin = 20 * time.Second + +func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) { + b := newTestBus(t) + ctx := context.Background() + branch := "release/1.2" // a `/` and a `.`: the dot is escaped in every key + escaped := keys.EscapeName(branch) + heldKey := func(repository, branch string) string { return headKey(repository, branch) } + old := strings.Repeat("0", 40) + // A head held from before a stop, past the bound: the state outlives the gate, as the bus's does. + raw, _ := json.Marshal(HeldHead{Head: old, Since: time.Now().Add(-time.Hour).UTC()}) + if _, err := b.kvs["heads"].Put(ctx, heldKey("novox/old", branch), raw); err != nil { + t.Fatal(err) + } + rt := b.start(t) + evctx, cancel := context.WithCancel(ctx) + defer cancel() + rt.deliverEvents(evctx) + rt.untilListening() + rt.until("head-untaken for the head held past the bound", eventWithin, func() bool { + return findingHeld(ctx, b, "head-untaken", heldKey("novox/old", branch)) + }) + + merge := strings.Repeat("c", 40) + call := "0123456789abcdef" + instance, _ := RecordInstance(recordMilestone(branch, 1)) + member := map[string]any{"repository": "novox/app", "number": 5, "branch": branch, "head": strings.Repeat("d", 40), "commit": merge} + for range 2 { // heard twice: one revision + b.publish(t, "mesh.seat.git.event.merge-called."+call, map[string]any{"call": call, "by": "lead@shanks", "account": "acct-s", + "at": "2026-11-20T03:00:00Z", "members": []any{member}}) + } + sourceKey := mdc.SourceKey(escaped) + rt.until("the record of the merge call and its source revision", eventWithin, func() bool { + e, err := b.kvs["source"].Get(ctx, sourceKey) + if err != nil || !strings.Contains(string(e.Value()), `"call":"`+call+`"`) || !strings.Contains(string(e.Value()), `"source":1`) { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + return b.ledger != nil && b.ledger.states[instance] != nil + }) + headMoved(t, b, "novox/app", branch, merge) // the merge call's head: taken + headMoved(t, b, "novox/push", branch, merge) // a push no call delivered: held + rt.until("the pushed head held", eventWithin, func() bool { return kvHas(ctx, b, "heads", heldKey("novox/push", branch)) }) + if kvHas(ctx, b, "heads", heldKey("novox/app", branch)) { + t.Fatalf("the head of the merge call on %s is held: its source key is not read as it is written", branch) + } + + b.publish(t, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", map[string]any{"branch": branch, "source": 1, "revision": 1, + "call": call, "entries": []any{map[string]any{"module": "app", "commit": merge, "fingerprint": "core-f", "repository": "novox/app"}}}) + rt.until("the take-in's mover in the record", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + mover, _ := MoverInstance(recordMilestone(branch, 1), "app") + return strings.Contains(string(b.ledger.states[mover]), `"module":"app"`) && strings.Contains(string(b.ledger.states[instance]), `"movers":1`) + }) + if e, _ := b.kvs["source"].Get(ctx, sourceKey); e.Revision() != 1 { + t.Fatalf("the merge call heard twice wrote source.%s %d times", escaped, e.Revision()) + } + + // GT2 (design 47 H2 §810; H-A-453 (3)): at its end the record keeps on its head the delivery time, from merge-called to + // its last mover's running, and its class, core for a record that moves a core module. + b.publish(t, "mesh.seat.mesh-wants.event.wanted.test.app", map[string]any{"v": 1, "module": "app", "node": "test", + "fp": "core-f", "pipeline": recordMilestone(branch, 1), "revision": 7}) + b.publish(t, "mesh.seat.node-engine.event.running.test.app", map[string]any{"v": 1, "module": "app", "node": "test", + "fingerprint": "core-f", "at": time.Now().UTC().Format(time.RFC3339)}) + rt.until("app running on test", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + mover, _ := MoverInstance(recordMilestone(branch, 1), "app") + return strings.Contains(string(b.ledger.states[mover]), `"step":"`+StepRunning+`"`) + }) + b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".1", map[string]any{"v": 1, "branch": branch, + "source": 1, "pipeline": recordMilestone(branch, 1), "outcome": "running"}) + var head Record + rt.until("the record ended with its delivery time and class", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + head = Record{} + return json.Unmarshal(b.ledger.states[instance], &head) == nil && head.Ended != nil + }) + took, err := time.ParseDuration(head.DeliveryTime) + if want := time.Since(time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)); err != nil || took < want-time.Minute || took > want || + head.Class != "core" { + t.Errorf("the ended record keeps the delivery time %q and the class %q, want about %s and core", head.DeliveryTime, head.Class, + want.Round(time.Minute)) + } + + // GT1 (design 47 H2 §809; H-A-385, H-A-391, H-A-453 (3), H-A-455): a record of 126 movers writes 127 entries, its head + // and one per mover, and its acts owed the forge each an entry of its own, none over 64 KiB, the head counting 126 and + // holding no act; an entry made too large raises record-too-large, and the record's end clears it. + call2, merge2 := "00000000000000c2", strings.Repeat("e", 40) + instance2, _ := RecordInstance(recordMilestone(branch, 2)) + b.publish(t, "mesh.seat.git.event.merge-called."+call2, map[string]any{"call": call2, "by": "lead@shanks", "account": "acct-s", + "at": time.Now().UTC().Format(time.RFC3339), "members": []any{map[string]any{"repository": "novox/app", "number": 6, + "branch": branch, "head": strings.Repeat("f", 40), "commit": merge2}}}) + rt.until("the record of the second merge call", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.ledger.states[instance2] != nil + }) + var taken []any + for i := range 126 { + module := "mesh-module-" + strings.Repeat("x", 3) + fmt.Sprintf("%03d", i) + taken = append(taken, map[string]any{"module": module, "commit": merge2, "fingerprint": fmt.Sprintf("%064x", i), "repository": "novox/app"}) + } + b.publish(t, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", map[string]any{"branch": branch, "source": 2, "revision": 2, + "call": call2, "entries": taken}) + rt.until("the record's 126 movers taken in", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + last, _ := MoverInstance(recordMilestone(branch, 2), taken[125].(map[string]any)["module"].(string)) + return strings.Contains(string(b.ledger.states[instance2]), `"movers":126`) && + strings.Contains(string(b.ledger.states[last]), `"outcome":"`+OutcomeTakenIn+`"`) + }) + b.mu.Lock() + entries, acts, over := 0, 0, []string{} + for inst, raw := range b.ledger.states { + if string(raw) == "null" { + continue + } + var of struct { + Milestone string `json:"milestone"` + Record string `json:"record"` + } + _ = json.Unmarshal(raw, &of) + if of.Milestone != recordMilestone(branch, 2) && of.Record != recordMilestone(branch, 2) { + continue + } + if strings.HasPrefix(inst, TypeAct+"/") { + acts++ + } else { + entries++ + } + if len(raw) > EntryLimit { + over = append(over, fmt.Sprintf("%s holds %d bytes", inst, len(raw))) + } + } + headRaw := string(b.ledger.states[instance2]) + b.mu.Unlock() + if entries != 127 || acts == 0 || len(over) > 0 || strings.Contains(headRaw, `"acts"`) { + t.Fatalf("the record of 126 movers writes %d entries and %d acts, over 64 KiB: %v; its head: %.300s", entries, acts, over, headRaw) + } + if findingHeld(ctx, b, RecordTooLarge, "") { + t.Fatal("record-too-large is raised for a record whose entries are within 64 KiB") + } + // The first mover's take-in said again with a why past 64 KiB: its entry's write is refused and raises record-too-large; + // the record's end clears it. + first := taken[0].(map[string]any) + tooLarge, _ := MoverInstance(recordMilestone(branch, 2), first["module"].(string)) + b.publish(t, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", map[string]any{"branch": branch, "source": 2, "revision": 2, + "call": call2, "why": strings.Repeat("w", EntryLimit), "entries": []any{first}}) + rt.until("record-too-large raised for the mover's entry", eventWithin, func() bool { return findingHeld(ctx, b, RecordTooLarge, tooLarge) }) + b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".2", map[string]any{"v": 1, "branch": branch, + "source": 2, "pipeline": recordMilestone(branch, 2), "outcome": "running"}) + rt.until("record-too-large cleared at the record's end", eventWithin, func() bool { return !findingHeld(ctx, b, RecordTooLarge, "") }) + + // The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing. + seeded := strings.Repeat("5", 40) + b.mu.Lock() + b.registrations = []meshcatalog.Registration{{Module: "seeded", Origin: "novox/seeded", Branches: []string{"main"}}} + b.heads = map[string]string{"novox/seeded@main": seeded} + b.mu.Unlock() + if out := rt.call(t, "gate_source_seed", map[string]any{"why": "the clean state", "_caller": "lead@shanks"}); !strings.Contains(out, `\"branches\":1`) { + t.Fatalf("gate_source_seed answered %s", out) + } + headMoved(t, b, "novox/seeded", "main", seeded) + headMoved(t, b, "novox/push", "main", seeded) + rt.until("the barrier head held", eventWithin, func() bool { return kvHas(ctx, b, "heads", heldKey("novox/push", "main")) }) + if kvHas(ctx, b, "heads", heldKey("novox/seeded", "main")) { + t.Fatal("the seeded head is held after the seed") + } + rt.noControllerAsk() +} + +// headMoved publishes the forge bridge's head-moved of a repository's branch. +func headMoved(t *testing.T, b *testBus, repository, branch, head string) { + t.Helper() + name, err := forgemsg.HeadMovedEvent(repository, branch) + if err != nil { + t.Fatal(err) + } + b.publish(t, "mesh.mod.mesh-delivery-forge-bridge.event."+name, forgemsg.HeadMoved{V: 1, Repository: repository, Branch: branch, Head: head}) +} + +func kvHas(ctx context.Context, b *testBus, state, key string) bool { + _, err := b.kvs[state].Get(ctx, key) + return err == nil +} + +// findingHeld is whether the gate's state findings holds a finding of a kind and id. +func findingHeld(ctx context.Context, b *testBus, kind, id string) bool { + names, err := b.kvs["findings"].Keys(ctx) + if err != nil && err != jetstream.ErrNoKeysFound { + return false + } + for _, k := range names { + if strings.Contains(k, kind) { + e, err := b.kvs["findings"].Get(ctx, k) + if err == nil && strings.Contains(string(e.Value()), id) { + return true + } + } + } + return false +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled.go new file mode 100644 index 000000000..e27c34bc0 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled.go @@ -0,0 +1,197 @@ +package main + +// The merge call names the merged heads one source revision per watched branch (design 47 H §737; ADR 0682 §1, §2; +// H-A-13, H-A-19, H-A-33): the gate consumes the seat git's merge-called on a durable consumer of its own, writes +// source. once per call by compare-and-set keyed by the call, opens that revision's delivery record and says +// record-opened and source-moved. The gate numbers every source revision; no other part keeps a number of its own. + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "regexp" + "strconv" + "strings" + + gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/keys" +) + +// mergeCalledEvent is the seat git's merge-called as the gate's manifest consumes it (`git.merge-called.*`). +var mergeCalledEvent = consumedFamily(gitseat.EventMergeCalled) + +// consumedFamily is the pattern the manifest consumes an event by whose subject has parts after its name +// (`..*`), or the event itself; empty when the manifest consumes none. +func consumedFamily(event string) string { + for _, c := range consumed { + if _, name, ok := strings.Cut(c, "."); ok && (name == event || strings.HasPrefix(name, event+".")) { + return c + } + } + return "" +} + +// callRe is a merge call: 16 lowercase hex characters, one subject token (H-A-24). +var callRe = regexp.MustCompile(`^[0-9a-f]{16}$`) + +// revisionHead is one repository a source revision moves, at its commit. +type revisionHead struct { + Repository string + Commit string +} + +// nameRevision writes source. once for a call (§737, H-A-33): the branch's previous heads with each head's +// repository at its commit, numbered one above the branch's newest, carrying the call. A newest revision already carrying +// the call writes nothing and is answered as it is, so a call heard again numbers nothing twice (H-A-13). Wrote says it +// was written now. +func (h *Holder) nameRevision(branch, call string, heads []revisionHead) (named Source, wrote bool, err error) { + if h.Source == nil { + return Source{}, false, errors.New("this gate keeps no source") + } + _, err = h.Source.Set(branch, func(prev *Source) (Source, bool) { + if prev != nil && prev.Call == call { + named, wrote = *prev, false + return Source{}, false + } + next := Source{Call: call, Source: 1, Heads: map[string]string{}} + if prev != nil { + next.Source = prev.Source + 1 + for r, c := range prev.Heads { + next.Heads[r] = c + } + } + for _, hd := range heads { + next.Heads[hd.Repository] = hd.Commit + } + named, wrote = next, true + return next, true + }) + if err != nil { + return Source{}, false, fmt.Errorf("source.%s cannot be written for the call %s: %w", branch, call, err) + } + // The heads the revision names are delivered: their held heads go and their head-untaken clears (§740). + if err := h.sourceNamed(branch, named); err != nil { + return named, wrote, fmt.Errorf("source.%s is at %d and its held heads are not let go: %w", branch, named.Source, err) + } + return named, wrote, nil +} + +// saySourceMoved says source-moved on source-moved.. (§737) under the revision's id, so said again for a +// call heard again it is kept once. +func (h *Holder) saySourceMoved(branch string, s Source, start bool, heads []revisionHead) error { + if h.SaySeat == nil { + return nil + } + escaped, number := keys.EscapeName(branch), strconv.FormatInt(s.Source, 10) + e := seat.SourceMovedEvent{V: 1, Branch: branch, Source: s.Source, Call: s.Call, Start: start, + Heads: make([]seat.SourceMovedEventHeadsItem, 0, len(heads))} + for _, hd := range heads { + e.Heads = append(e.Heads, seat.SourceMovedEventHeadsItem{Repository: hd.Repository, Commit: hd.Commit}) + } + return h.SaySeat(seat.SubjectSourceMoved(escaped, number), e, "source-moved."+escaped+"."+number) +} + +// branchOfCall is one watched branch a merge call's members name: its heads in call order, each repository once at its +// last member's commit (H-A-19), and its members by id `@` (H-A-48). +type branchOfCall struct { + Branch string + Heads []revisionHead + Members map[string]string + Pulls []string + Commits []string +} + +// branchesOf groups a merge call's landed members by their base, in the order the call first names each branch. +func branchesOf(m gitseat.MergeCalled) ([]*branchOfCall, error) { + var out []*branchOfCall + by := map[string]*branchOfCall{} + for _, mb := range m.Members { + if mb.Branch == "" || mb.Repository == "" || mb.Commit == "" || mb.Number < 1 { + return nil, fmt.Errorf("a member names no branch, repository, number or commit (%+v)", mb) + } + b := by[mb.Branch] + if b == nil { + b = &branchOfCall{Branch: mb.Branch, Members: map[string]string{}} + by[mb.Branch] = b + out = append(out, b) + } + id := strings.ToLower(mb.Repository) + "@" + strconv.FormatInt(mb.Number, 10) + b.Members[id] = mb.Commit + b.Pulls = append(b.Pulls, id) + b.Commits = append(b.Commits, mb.Commit) + replaced := false + for i := range b.Heads { + if b.Heads[i].Repository == mb.Repository { + b.Heads[i].Commit, replaced = mb.Commit, true + } + } + if !replaced { + b.Heads = append(b.Heads, revisionHead{Repository: mb.Repository, Commit: mb.Commit}) + } + } + return out, nil +} + +// MergeCalled takes one merge-called: for each watched branch its members name, one source revision, one delivery record and +// one source-moved (§737). It answers an error only when a write failed, so the event is offered again; a body that cannot be +// read is said and taken, since offered again it would be refused again. A call that landed no member names nothing. +func (h *Holder) MergeCalled(e stdio.Envelope) error { + var m gitseat.MergeCalled + if err := json.Unmarshal(e.Body, &m); err != nil { + h.Refuse(fmt.Errorf("a merge-called (%s) is not readable, so it names no source revision: %w", e.Key, err)) + return nil + } + if !callRe.MatchString(m.Call) { + h.Refuse(fmt.Errorf("a merge-called (%s) names the call %q, not 16 lowercase hex characters, so it names no source revision", e.Key, m.Call)) + return nil + } + branches, err := branchesOf(m) + if err != nil { + h.Refuse(fmt.Errorf("the merge call %s names no source revision: %w", m.Call, err)) + return nil + } + var errs []error + for _, b := range branches { + trace := RecordTrace{Call: m.Call, By: m.By, Account: m.Account, At: m.At.UTC(), Pulls: b.Pulls, Commits: b.Commits} + if err := h.deliverRevision(b.Branch, m.Call, b.Heads, b.Members, trace); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// deliverRevision names a branch's heads one source revision for a call, opens its record and says source-moved: the one +// path a merge call and a hand take (§742) move a source by. +func (h *Holder) deliverRevision(branch, call string, heads []revisionHead, members map[string]string, trace RecordTrace) error { + named, wrote, err := h.nameRevision(branch, call, heads) + if err != nil { + return err + } + if h.Records != nil { + trace.Source = strconv.FormatInt(named.Source, 10) + if _, _, err := h.Records.Open(RecordOpening{Branch: branch, Source: named.Source, Call: call, Heads: members, Trace: trace}); err != nil { + return fmt.Errorf("the record of %s at %d cannot be opened: %w", branch, named.Source, err) + } + } + if err := h.saySourceMoved(branch, named, false, heads); err != nil { + return fmt.Errorf("source.%s is at %d and its source-moved is not said: %w", branch, named.Source, err) + } + if wrote { + h.logf("[mesh-delivery] source.%s is at %d for the call %s", branch, named.Source, call) + } + return nil +} + +// newCall is a call made by the gate itself, for a start or a seed (H-A-24: 16 lowercase hex characters; who and when +// live in the hand-act log and the trace). +func newCall() (string, error) { + var b [8]byte + if _, err := rand.Read(b[:]); err != nil { + return "", fmt.Errorf("no call can be made: %w", err) + } + return hex.EncodeToString(b[:]), nil +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled_test.go new file mode 100644 index 000000000..cfec0a652 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecalled_test.go @@ -0,0 +1,127 @@ +package main + +import ( + "encoding/json" + "reflect" + "strconv" + "strings" + "testing" + "time" + + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + stdio "git.novox.be/novox/mesh-sdk/go" +) + +// GATE-4 and GATE-5 (design 47 H §737; H-A-13, H-A-19, H-A-25, H-A-33): a merge-called names its landed heads one source +// revision per watched branch, written once per call, numbered one above the branch's newest, opens that revision's record +// keyed `.` and says record-opened on record-opened. and source-moved on source-moved... +func TestAMergeCallNamesOneSourceRevisionAndOneRecordPerBranch(t *testing.T) { + at := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + c1, c2, c3 := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("3", 40) + type said struct { + subject, id string + body any + } + setup := func(t *testing.T) (*Holder, *memSource, *[]said) { + src := &memSource{vals: map[string]Source{"main": {Source: 9, Call: "00000000000000aa", Heads: map[string]string{"novox/old": "c0"}}}} + var events []said + h := &Holder{Now: func() time.Time { return at }, Source: src} + h.init() + h.SaySeat = func(subject string, body any, id string) error { + events = append(events, said{subject, id, body}) + return nil + } + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now, Say: h.SaySeat} + return h, src, &events + } + called := func(call, members string) stdio.Envelope { + return stdio.Envelope{Key: "git.merge-called." + call, Body: json.RawMessage(`{"call":"` + call + + `","by":"lead@shanks","account":"acct-s","at":"2026-11-20T02:59:00Z","members":[` + members + `]}`)} + } + member := func(repository string, number int, branch, commit string) string { + return `{"repository":"` + repository + `","number":` + strconv.Itoa(number) + + `,"branch":"` + branch + `","head":"h","commit":"` + commit + `"}` + } + + t.Run("two members on one branch: one revision, one record, one source-moved; heard twice, one", func(t *testing.T) { + h, src, events := setup(t) + e := called("0123456789abcdef", member("novox/app", 3, "main", c1)+","+member("novox/lib", 4, "main", c2)) + for range 2 { + if err := h.MergeCalled(e); err != nil { + t.Fatal(err) + } + } + got := src.vals["main"] + if got.Source != 10 || got.Call != "0123456789abcdef" || + !reflect.DeepEqual(got.Heads, map[string]string{"novox/old": "c0", "novox/app": c1, "novox/lib": c2}) || src.rev != 1 { + t.Fatalf("source.main %+v (%d writes)", got, src.rev) + } + kept, _ := h.Records.Kept() + if len(kept) != 1 || kept[0].Milestone != recordMilestone("main", 10) || kept[0].Call != "0123456789abcdef" || + !reflect.DeepEqual(kept[0].Heads, map[string]string{"novox/app@3": c1, "novox/lib@4": c2}) || + kept[0].Trace == nil || kept[0].Trace.By != "lead@shanks" || kept[0].Trace.Account != "acct-s" { + t.Fatalf("records %+v", kept) + } + var moved []seat.SourceMovedEvent + ids := map[string]bool{} + for _, s := range *events { + ids[s.id] = true + if m, ok := s.body.(seat.SourceMovedEvent); ok { + if s.subject != seat.SubjectSourceMoved("main", "10") { + t.Fatalf("source-moved on %s", s.subject) + } + moved = append(moved, m) + } else if s.subject != seat.SubjectRecordOpened("0123456789abcdef") { + t.Fatalf("said %s", s.subject) + } + } + want := seat.SourceMovedEvent{V: 1, Branch: "main", Source: 10, Call: "0123456789abcdef", + Heads: []seat.SourceMovedEventHeadsItem{{Repository: "novox/app", Commit: c1}, {Repository: "novox/lib", Commit: c2}}} + if len(moved) != 2 || !reflect.DeepEqual(moved[0], want) || len(ids) != 2 { + t.Fatalf("source-moved %+v under %v: heard twice it is said under the one id", moved, ids) + } + }) + + t.Run("two members of one repository name the last member's commit in call order", func(t *testing.T) { + h, src, _ := setup(t) + if err := h.MergeCalled(called("1111111111111111", member("novox/app", 3, "main", c1)+","+member("novox/app", 5, "main", c3))); err != nil { + t.Fatal(err) + } + if got := src.vals["main"].Heads["novox/app"]; got != c3 { + t.Fatalf("novox/app at %s", got) + } + }) + + t.Run("members on two branches are two revisions and two records, each naming the call", func(t *testing.T) { + h, src, events := setup(t) + if err := h.MergeCalled(called("2222222222222222", member("novox/app", 3, "main", c1)+","+member("novox/app", 6, "feat/x", c2))); err != nil { + t.Fatal(err) + } + if src.vals["main"].Source != 10 || src.vals["feat/x"].Source != 1 || src.vals["feat/x"].Call != "2222222222222222" { + t.Fatalf("sources %+v", src.vals) + } + kept, _ := h.Records.Kept() + if len(kept) != 2 || kept[0].Call != kept[1].Call || len(*events) != 4 { + t.Fatalf("records %+v, %d events", kept, len(*events)) + } + }) + + t.Run("a call that cannot be read, or not 16 lowercase hex, names nothing and is taken", func(t *testing.T) { + h, src, events := setup(t) + for _, e := range []stdio.Envelope{called("NOTHEX", member("novox/app", 3, "main", c1)), + {Key: "git.merge-called.x", Body: json.RawMessage(`{`)}, called("3333333333333333", member("novox/app", 3, "", c1))} { + if err := h.MergeCalled(e); err != nil { + t.Fatal(err) + } + } + if src.rev != 0 || len(*events) != 0 { + t.Fatalf("wrote %d, said %d", src.rev, len(*events)) + } + }) + + t.Run("the manifest consumes merge-called and the gate follows it", func(t *testing.T) { + if mergeCalledEvent != "git.merge-called.*" || !stdio.TopicMatches(mergeCalledEvent, "git.merge-called.0123456789abcdef") { + t.Fatalf("merge-called followed as %q", mergeCalledEvent) + } + }) +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/merges.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/merges.go index 12d88bc9e..0f7098c5f 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/merges.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/merges.go @@ -12,38 +12,19 @@ import ( "git.novox.be/novox/mesh-sdk/go/keys" ) -// The gate merges nothing and hands nothing to the forge (design 47 G §592): `merges` stays an old section the switch reads -// (switch.go, §613), never written; `source` is the gate's source revision per watched branch (§15, §291), served by the verb +// The gate merges nothing and hands nothing to the forge (design 47 G §592; H §764: `merges` goes): `source` is the gate's source revision per watched branch (§15, §291), served by the verb // `source` below. +// Source is the state source's value, the seat mesh-delivery's type used as it is (novox/hq ADR 0634 §2). +type ( + Source = seat.SourceByBranchValue + // Owed is what the forge bridge performs, as the seat's event owed says it. + Owed = seat.OwedByRepositoryNumberHeadActValue +) + // changeAttempts is how often a lost compare-and-set is read and applied again before it is said. const changeAttempts = 10 -// MergeStore is the gate's bucket merges. -type MergeStore interface { - Get(group string) (*Merge, error) -} - -// OldState reads the gate's old state owed, which the switch says again as switched acts (switch.go): each key, and one -// key's value with its revision. -type OldState interface { - Keys(state string) ([]string, error) - Get(state, key string) (value []byte, revision uint64, err error) -} - -// kvOld is the old state over the runtime. -type kvOld struct{} - -func (kvOld) Keys(state string) ([]string, error) { return stdio.State(state).Keys() } - -func (kvOld) Get(state, key string) ([]byte, uint64, error) { - e, err := stdio.State(state).Get(key) - if err != nil || e == nil { - return nil, 0, err - } - return e.Value, e.Revision, nil -} - // SourceStore is the gate's bucket source, one key per watched branch (design 47 G §15), moved by compare-and-set. type SourceStore interface { // Set reads a branch's source key and writes what update makes of it, unless update says nothing is to be written, and answers @@ -55,25 +36,6 @@ type SourceStore interface { Branches() ([]string, error) } -// kvMerges is merges over the runtime. -type kvMerges struct{} - -func (kvMerges) Get(group string) (*Merge, error) { - key, err := mdc.MergesKey(group) - if err != nil { - return nil, err - } - e, err := stdio.State("merges").Get(key) - if err != nil || e == nil { - return nil, err - } - m, err := DecodeMerge(e.Value) - if err != nil { - return nil, fmt.Errorf("the merge of %s is not readable: %w", group, err) - } - return &m, nil -} - // kvSource is source over the runtime. type kvSource struct{} @@ -117,8 +79,9 @@ func (kvSource) Set(branch string, update func(prev *Source) (Source, bool)) (ui return 0, fmt.Errorf("source.%s was written by another writer first %d times: %w", branch, changeAttempts, stdio.ErrChanged) } +// Read reads a branch's key with the escaping Set writes it with (design 47 H H-A-87 (2)). func (kvSource) Read(branch string) (*Source, uint64, error) { - e, err := stdio.State("source").Get(mdc.SourceKey(branch)) + e, err := stdio.State("source").Get(mdc.SourceKey(keys.EscapeName(branch))) if err != nil || e == nil { return nil, 0, err } @@ -151,7 +114,7 @@ func (kvSource) Branches() ([]string, error) { } // SourceRevision is the seat's verb source (§690): given a branch, every repository that branch's source key names, its -// trunk branch and head, the group that moved it last and its revision, or why it cannot be read; given none, `branches`, +// trunk branch and head, the merge call that moved it last (H-A-25) and its source revision, or why it cannot be read; given none, `branches`, // the branch of each source key the gate keeps. The trunk of each repository is the branch asked, the key's own (§428, §507). Outside the lock. func (h *Holder) SourceRevision(branch string) seat.SourceAnswer { if h.Source == nil { @@ -167,14 +130,14 @@ func (h *Holder) SourceRevision(branch string) seat.SourceAnswer { } return seat.SourceAnswer{Branches: branches} } - held, revision, err := h.Source.Read(branch) + held, _, err := h.Source.Read(branch) if err != nil { return seat.SourceAnswer{Error: err.Error()} } if held == nil { return seat.SourceAnswer{Branch: branch} } - out := seat.SourceAnswer{Branch: branch, Group: held.Group, Revision: int64(revision)} + out := seat.SourceAnswer{Branch: branch, Call: held.Call, Revision: held.Source} for repository, head := range held.Heads { out.Repositories = append(out.Repositories, seat.SourceHead{Repository: repository, Trunk: branch, Head: head}) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go new file mode 100644 index 000000000..8e3ca90ea --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go @@ -0,0 +1,257 @@ +package main + +// A record's entries, one per module (design 47 H2 §809; H-A-385, H-A-391): the head entry `record/` keeps +// every record-wide field, its outcome, the count of its movers and §810's times, nothing per module and no act; each +// mover, the catalog half's too, has its own entry `mover/` with its pipeline, version and the +// module's step outcomes per node (its machines and their running times among them); each act owed the forge has its own +// entry `act/`, removed when performed (H-A-455 (1)). No entry names two modules. A record is joined +// from its head and the movers and acts the ledger's indexes `movers` and `acts` name under the record's key, one query +// each. The gate refuses a write over 64 KiB to any entry, the head's, a mover's or an act's, with the finding +// record-too-large, cleared when that entry is next written within 64 KiB or at the record's end (H-A-455 (3)). + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + "time" + + "git.novox.be/novox/mesh-sdk/go/buscalls" + catalogue "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// TypeMover is the ledger type of a mover's entry. +const TypeMover = "mover" + +// MoversIndex is the ledger's index of the movers' entries on their record's key (manifest `requires` records' indexes). +const MoversIndex = "movers" + +// The operations of a mover's entry; the manifest's type mover declares exactly these (record_test.go). +const ( + OpMover = "mover" // set-fields: its record's key, its module, its class, its pipeline and its version + // OpEntry and OpOutcome write its entries and outcomes as they did on the whole record. +) + +// MoverOperations are a mover's operations, in the order the manifest's type allows them. +var MoverOperations = []string{OpMover, OpEntry, OpOutcome} + +// OpMovers is the head entry's count of its movers (set-fields movers). +const OpMovers = "movers" + +// EntryLimit is the most one entry of the ledger holds (§809). +const EntryLimit = 64 << 10 + +// RecordTooLarge is the finding of an entry refused over EntryLimit (scope delivery). +const RecordTooLarge = "record-too-large" + +// Mover is one mover's entry, as apply derives it from its operations. +type Mover struct { + // Instance and Sequence are its path in the ledger and its last operation; not in the state. + Instance string `json:"-"` + Sequence uint64 `json:"-"` + + // Record is its record's key, `.`, the index's field. + Record string `json:"record"` + Module string `json:"module"` + Pipeline string `json:"pipeline,omitempty"` + Version string `json:"version,omitempty"` + // Class is the module's class as its catalog entry said it when the entry opened (core or leaf, H-A-394 (2)). + Class string `json:"class,omitempty"` + Entries map[string]RecordEntry `json:"entries,omitempty"` + Outcomes map[string]RecordOutcome `json:"outcomes,omitempty"` +} + +// Running are the machines the mover runs healthy on, each with when it was first said. +func (m *Mover) Running() map[string]time.Time { + out := map[string]time.Time{} + for _, o := range m.Outcomes { + if o.Outcome == OutcomeRunning && o.Node != "" { + if at, ok := out[o.Node]; !ok || o.At.Before(at) { + out[o.Node] = o.At + } + } + } + return out +} + +// MoverInstance is the entry of a record's mover: `mover/`, each escaped as a name. +func MoverInstance(milestone, module string) (string, error) { + if strings.TrimSpace(module) == "" { + return "", fmt.Errorf("a mover of the record %s names its module", milestone) + } + inst := TypeMover + "/" + milestoneToken(milestone+"."+module) + if !segmentRe.MatchString(strings.TrimPrefix(inst, TypeMover+"/")) { + return "", fmt.Errorf("the mover %s of %s cannot be named: %q", module, milestone, inst) + } + return inst, nil +} + +// moversKey is the index key that names every mover or act of a record: its key's token, then the rest. +func moversKey(milestone string) string { + return strings.TrimSuffix(buscalls.IndexKey([]string{milestone}, "x"), ".x") + ".>" +} + +// movers reads the movers' entries of a record through the index, one query, and each entry. +func (rs *Records) movers(milestone string) ([]*Mover, error) { + insts, err := rs.Ledger.Query(MoversIndex, moversKey(milestone)) + if err != nil { + return nil, fmt.Errorf("the movers of the record %s cannot be read: %w", milestone, err) + } + var out []*Mover + for _, inst := range insts { + raw, seq, err := rs.Ledger.Get(inst) + if err != nil { + return nil, err + } + if raw == nil { + continue + } + var m Mover + if err := json.Unmarshal(raw, &m); err != nil { + return nil, fmt.Errorf("the mover %s is not readable: %w", inst, err) + } + if m.Record != milestone || m.Module == "" { + continue + } + m.Instance, m.Sequence = inst, seq + out = append(out, &m) + } + sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module }) + return out, nil +} + +// join lays a record's movers into it: their entries and outcomes, by module. +func (r *Record) join(ms []*Mover) { + r.movers = map[string]*Mover{} + for _, m := range ms { + r.movers[m.Module] = m + for k, e := range m.Entries { + if r.Entries == nil { + r.Entries = map[string]RecordEntry{} + } + r.Entries[k] = e + } + for k, o := range m.Outcomes { + if r.Outcomes == nil { + r.Outcomes = map[string]RecordOutcome{} + } + r.Outcomes[k] = o + } + } +} + +// Movers are the record's movers' entries, by module. +func (r *Record) Movers() map[string]*Mover { return r.movers } + +// mover is the record's entry of module, opened in the ledger when it has none, and counted on the head entry. +func (rs *Records) mover(r *Record, module, fingerprint string) (*Mover, error) { + if m := r.movers[module]; m != nil { + return m, nil + } + inst, err := MoverInstance(r.Milestone, module) + if err != nil { + return nil, err + } + class := catalogue.ClassLeaf + if rs.Class != nil && fingerprint != "" { + c, err := rs.Class(fingerprint) + if err != nil { + return nil, fmt.Errorf("the class of %s at %s cannot be read from its catalog entry, so its entry is not opened: %w", module, fingerprint, err) + } + class = firstOf(c, catalogue.ClassLeaf) + } + m := &Mover{Instance: inst, Record: r.Milestone, Module: module, Class: class} + seq, err := rs.write(r, inst, OpMover, map[string]any{"record": r.Milestone, "module": module, "class": class}, m) + if err != nil { + return nil, err + } + m.Sequence = seq + if r.movers == nil { + r.movers = map[string]*Mover{} + } + r.movers[module] = m + next := *r + next.MoverCount = len(r.movers) + hseq, err := rs.write(r, r.Instance, OpMovers, map[string]any{"movers": len(r.movers)}, next.head()) + if err != nil { + return m, fmt.Errorf("the mover %s is written and the record %s's count of its movers is not: %w", module, r.Instance, err) + } + r.MoverCount, r.Sequence = len(r.movers), hseq + return m, nil +} + +// SetMover writes a mover's pipeline and version, unless its entry holds them already. +func (rs *Records) SetMover(r *Record, module, fingerprint, pipeline, version string) error { + m, err := rs.mover(r, module, fingerprint) + if err != nil { + return err + } + next := *m + next.Pipeline, next.Version = firstOf(pipeline, m.Pipeline), firstOf(version, m.Version) + if next.Pipeline == m.Pipeline && next.Version == m.Version { + return nil + } + seq, err := rs.write(r, m.Instance, OpMover, map[string]any{"record": r.Milestone, "module": module, "class": m.Class, + "pipeline": next.Pipeline, "version": next.Version}, next) + if err != nil { + return err + } + m.Pipeline, m.Version, m.Sequence = next.Pipeline, next.Version, seq + return nil +} + +// write is one write to an entry of a record, measured first: the entry's state after it (the head's without its movers +// and acts) is refused over EntryLimit with record-too-large, and a write taken clears the entry's finding (§809, H-A-455 +// (3)). +func (rs *Records) write(r *Record, instance, operation string, body, state any) (uint64, error) { + if err := rs.fits(r, instance, state); err != nil { + return 0, err + } + seq, err := rs.Ledger.Apply(instance, operation, body) + if err != nil { + return 0, err + } + rs.fitted(r, instance) + return seq, nil +} + +// recordOf is the instance of r's head entry, the subject of its entries' findings (H-A-460). +func recordOf(r *Record) string { + if r.Instance != "" { + return r.Instance + } + inst, _ := RecordInstance(r.Milestone) + return inst +} + +// fits refuses an entry of r whose state would pass EntryLimit, raising record-too-large for it with its record as the +// finding's subject (§809; H-A-460), so the record's end clears it whichever entry it was (H-A-455 (3)). +func (rs *Records) fits(r *Record, instance string, state any) error { + raw, err := json.Marshal(state) + if err != nil { + return err + } + if len(raw) <= EntryLimit { + return nil + } + if rs.TooLarge != nil { + rs.TooLarge(recordOf(r), instance, len(raw), true) + } + return fmt.Errorf("the delivery record's entry %s would hold %d bytes, over the %d an entry holds: refused (%s)", instance, len(raw), EntryLimit, RecordTooLarge) +} + +// fitted clears record-too-large for an entry of r written within EntryLimit (TooLarge clears only one it holds). +func (rs *Records) fitted(r *Record, instance string) { + if rs.TooLarge != nil { + rs.TooLarge(recordOf(r), instance, 0, false) + } +} + +// clearTooLarge clears, at a record's end, every record-too-large the gate's findings hold whose subject is the record, +// whichever entry it was refused for and whenever it was raised: read from the findings state, nothing kept in process +// memory (§809, H-A-455 (3), H-A-460). +func (rs *Records) clearTooLarge(r *Record) { + if rs.TooLarge != nil { + rs.TooLarge(recordOf(r), "", 0, false) + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owed.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owed.go index 938dd0466..4e52798cd 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owed.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owed.go @@ -48,6 +48,9 @@ func (h *Holder) owe(r *Record, o seat.Owed) error { return errors.New("no seat to say owed on") } now := h.Now().UTC() + // The act names its delivery record by its source revision, ., so the forge bridge keeps it with the act + // and bridge_owed_again finds a record's acts in its own state (design 47 H2 §807, H-A-432 (1)). + o.Record = r.Milestone if had, ok := r.Acts[o.ID]; ok && had.Owed.Said != nil { o.Said = had.Owed.Said } else { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go index e27918d7d..b297ff9dc 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go @@ -12,9 +12,9 @@ import ( // What the gate owes the forge for a change of a delivery record (design 47 G A-39, A-35, §158, §161 to §167): every change of // a record, a step's outcome applied or the record ended, says a line on the commit's note of each member pull request's head -// (` record : ()`) and replaces each member's delivery view with what `show` answers for the -// record; a comment is said only when the record ends failed or held, naming why. Each act goes through owe (owed.go): kept in -// the record's acts, said as the seat's event owed, and ended on owed.ended. +// (` record : ()`) and replaces each member's delivery view with the record's summary, its head's +// fields and a count of its movers per outcome (H-A-459); a comment is said only when the record ends failed or held, naming why. Each act goes through owe (owed.go): kept as +// an entry of its own among the record's acts, said as the seat's event owed, and ended on owed.ended. // RecordChange is one change of a record: what changed and why; Ended when it is the record's end. type RecordChange struct { @@ -39,7 +39,7 @@ func (h *Holder) recordChanged(r *Record, c RecordChange) { } now := h.Now().UTC() line := fmt.Sprintf("%s record %s: %s (%s)", now.Format("2006-01-02T15:04:05Z"), r.Instance, c.What, c.Why) - view, err := json.MarshalIndent(map[string]any{"records": []recordView{viewOf(r)}}, "", " ") + view, err := json.MarshalIndent(map[string]any{"records": []recordSummary{summaryOf(r)}}, "", " ") if err != nil { h.Refuse(fmt.Errorf("the record %s cannot be shown on its pull requests: %w", r.Instance, err)) return @@ -70,6 +70,36 @@ func (h *Holder) recordChanged(r *Record, c RecordChange) { } } +// recordSummary is the record a view act shows (design 47 H2 §809, H-A-455 (2), H-A-459): the head's fields, without its +// acts, and a count of its movers per outcome, never the movers' entries, so a view act of any record fits 64 KiB; the +// whole record stays readable through gate_record. +type recordSummary struct { + recordView + MoversPerOutcome map[string]int `json:"movers-per-outcome,omitempty"` +} + +// summaryOf is the record a view act shows. +func summaryOf(r *Record) recordSummary { + v := viewOf(r) + head := r.head() + v.Record = &head + per := map[string]map[string]bool{} + for _, o := range r.Outcomes { + if per[o.Outcome] == nil { + per[o.Outcome] = map[string]bool{} + } + per[o.Outcome][o.Module] = true + } + out := recordSummary{recordView: v} + for outcome, movers := range per { + if out.MoversPerOutcome == nil { + out.MoversPerOutcome = map[string]int{} + } + out.MoversPerOutcome[outcome] = len(movers) + } + return out +} + // endedFailedOrHeld is the comment a record ended says when one of its outcomes is failed or held, naming why; "" otherwise. func endedFailedOrHeld(r *Record) string { var lines []string diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go index 7e8a04cb5..30c7c83b0 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go @@ -1,11 +1,13 @@ package main import ( + "encoding/json" "strings" "testing" "time" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" ) type sayerFake struct{ said []seat.Owed } @@ -22,7 +24,7 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. f := &sayerFake{} h := &Holder{Now: func() time.Time { return at }, Owed: f, Records: rs} rs.Changed = h.recordChanged - r, _, err := rs.Open("47/G", map[string]string{"novox/app@7": head}, false) + r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@7": head})) if err != nil { t.Fatal(err) } @@ -40,7 +42,7 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. return } t.Run("an outcome applied says the note and the view, no comment", func(t *testing.T) { - _, rs, r, f := setup(t) + h, rs, r, f := setup(t) if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt, Why: "built it"}); err != nil { t.Fatal(err) } @@ -54,10 +56,15 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. if _, ok := r.Acts[o.ID]; !ok { t.Fatalf("act %s not kept in the record", o.ID) } + // H-A-432 (1): each act names its record by its source revision, said and kept alike. + if o.Record != "main.47" || r.Acts[o.ID].Owed.Record != o.Record { + t.Fatalf("act %s names the record %q, kept %q, not main.47", o.ID, o.Record, r.Acts[o.ID].Owed.Record) + } if o.Act == seat.OwedActNote && (o.Line != "2026-11-11T21:00:00Z record "+r.Instance+": mesh-x on ace build built (built it)" || o.Commit != head) { t.Fatalf("note %+v", o) } - if o.Act == seat.OwedActView && !strings.Contains(o.Text, r.Instance) { + // H-A-459: the view is the record's head fields and a count of movers per outcome, never the movers' entries. + if o.Act == seat.OwedActView && (!strings.Contains(o.Text, r.Instance) || !strings.Contains(strings.Join(strings.Fields(o.Text), ""), `"movers-per-outcome":{"built":1}`) || strings.Contains(o.Text, `"outcomes"`) || strings.Contains(o.Text, `"entries"`)) { t.Fatalf("view %q", o.Text) } } @@ -65,6 +72,86 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt, Why: "built it"}); err != nil || len(f.said) != 2 { t.Fatalf("said again: %v %d", err, len(f.said)) } + // Design 47 H2 §809, H-A-455 (1): each act is an entry of its own, act/, naming its record; the + // head entry holds none, and an act performed is removed. + l := rs.Ledger.(*ledgerFake) + for _, o := range f.said { + inst, err := ActInstance(r.Milestone, o.ID) + if err != nil || !strings.Contains(string(l.states[inst]), `"record":"main.47"`) { + t.Fatalf("the act %s has no entry of its own at %s: %s (%v)", o.ID, inst, l.states[inst], err) + } + } + if strings.Contains(string(l.states[r.Instance]), `"acts"`) { + t.Fatalf("the head entry holds acts: %s", l.states[r.Instance]) + } + note := f.said[0] + body, err := forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, Of: seat.Seat, ID: note.ID, Outcome: forgemsg.OwedPerformed, At: at}) + if err != nil { + t.Fatal(err) + } + if err := h.OwedEnded(body); err != nil { + t.Fatal(err) + } + inst, _ := ActInstance(r.Milestone, note.ID) + if string(l.states[inst]) != "null" || h.Status("")["owed"] != 1 { + t.Fatalf("the act performed is kept as %s, %v owed", l.states[inst], h.Status("")["owed"]) + } + // H-A-457: a head written before, its acts embedded, is read for its fields; those acts are ignored. + l.states[r.Instance] = json.RawMessage(strings.Replace(string(l.states[r.Instance]), `{`, `{"acts":{"old":{"id":"old","act":"view"}},`, 1)) + read, err := rs.Read(r.Instance) + if _, old := read.Acts["old"]; err != nil || old || len(read.Acts) != 1 || read.Milestone != "main.47" { + t.Fatalf("an old head's embedded acts are read: %+v (%v)", read.Acts, err) + } + }) + // Design 47 H2 §807, H-A-432 (2): an act whose pull request closed unmerged ends not-needed, kept in the record's acts as + // ended like performed and could not be performed, and no longer owed. + t.Run("an act the forge bridge ends not-needed is ended in the record and owed no more", func(t *testing.T) { + h, rs, r, f := setup(t) + h.Logf = func(string, ...any) {} + if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt, Why: "built it"}); err != nil { + t.Fatal(err) + } + id := f.said[0].ID + body, err := forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, Of: seat.Seat, ID: id, Outcome: forgemsg.OwedNotNeeded, + Words: "novox/app#7 closed unmerged", At: at}) + if err != nil { + t.Fatal(err) + } + if err := h.OwedEnded(body); err != nil { + t.Fatal(err) + } + kept, err := rs.Kept() + if err != nil || len(kept) != 1 { + t.Fatalf("kept %d records: %v", len(kept), err) + } + if a := kept[0].Acts[id]; a.Outcome != forgemsg.OwedNotNeeded || a.Words != "novox/app#7 closed unmerged" { + t.Fatalf("the act is kept as %+v", a) + } + if owed := h.Status("")["owed"]; owed != 1 { + t.Fatalf("%v acts owed, not the one left", owed) + } + // H-A-444: ended not-needed is a fact of the forge, never a refusal: gate_record shows it ended with that outcome, + // and delivery_status says no refusal of it. + views, err := rs.RecordOf(r.Instance, "") + if err != nil || len(views) != 1 || views[0].Record.Acts[id].Outcome != forgemsg.OwedNotNeeded { + t.Fatalf("gate_record shows %+v: %v", views, err) + } + if refused, ok := h.Status("")["refused"]; ok { + t.Fatalf("delivery_status says a not-needed act as refused: %v", refused) + } + // an act that could not be performed is a fault, and stays said as refused + other := f.said[1].ID + body, err = forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, Of: seat.Seat, ID: other, Outcome: forgemsg.OwedCouldNotBePerformed, + Words: "the forge answered 500", At: at}) + if err != nil { + t.Fatal(err) + } + if err := h.OwedEnded(body); err != nil { + t.Fatal(err) + } + if refused, _ := h.Status("")["refused"].([]string); len(refused) != 1 || !strings.Contains(refused[0], "the forge answered 500") { + t.Fatalf("delivery_status's refusals: %v", h.Status("")["refused"]) + } }) t.Run("a record ended failed says a comment naming why; ended healthy says none", func(t *testing.T) { _, rs, r, f := setup(t) @@ -78,6 +165,10 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. t.Fatalf("said %+v", f.said) } for _, o := range f.said { + // H-A-455 (2): the view is the record without its acts, the end's too, which follows the outcome's acts. + if o.Act == seat.OwedActView && strings.Contains(o.Text, `"acts"`) { + t.Fatalf("the view shows the record's acts: %s", o.Text) + } if o.Act == seat.OwedActComment && (!strings.Contains(o.Text, "tests red") || !strings.Contains(o.Text, "never runs")) { t.Fatalf("comment %q", o.Text) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go index 009902462..d8e6e6319 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go @@ -1,7 +1,9 @@ package main import ( + "encoding/json" "fmt" + "strings" "time" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" @@ -14,8 +16,8 @@ var owedEndedEvent = declared(forgemsg.OwedEndedEvent) // OwedEnded takes the forge bridge's outcome of one act this owner said as owed, and writes it into the delivery record that // holds the act (A-35): an act is answered only once its outcome is recorded. An outcome heard twice, or of an id no record -// holds, changes nothing. An outcome other than performed is said. An error leaves the event to be heard again: the record -// could not take it. +// holds, changes nothing. An outcome other than performed or not-needed is said as a refusal. An error leaves the event to +// be heard again: the record could not take it. func (h *Holder) OwedEnded(body []byte) error { e, err := forgemsg.DecodeOwedEnded(body) if err != nil { @@ -41,7 +43,9 @@ func (h *Holder) OwedEnded(body []byte) error { if !ok { continue } - if e.Outcome != forgemsg.OwedPerformed { + // Not-needed (its pull request closed unmerged) is a fact of the forge, not a fault of the act: ended with that + // outcome in the record, never said as a refusal (design 47 H2 §807, H-A-444). + if e.Outcome != forgemsg.OwedPerformed && e.Outcome != forgemsg.OwedNotNeeded { h.Refuse(fmt.Errorf("%s: the %s owed on %s#%d at %s was %s: %s", r.Instance, held.Act, held.Repository, held.Number, shortOf(held.Head, 12), e.Outcome, e.Words)) } @@ -53,8 +57,11 @@ func (h *Holder) OwedEnded(body []byte) error { // RecordAct is one act the gate owes the forge for a pull request a record holds: said, with when (At, while Outcome is empty) // and as the seat's event says it (Owed, which saying it again at the gate's start repeats), then ended with the forge -// bridge's outcome and when (A-35, design 47 §165). +// bridge's outcome and when (A-35, design 47 §165). Each is an entry of its own, `act/`, its record's +// key the index's field, removed when performed (design 47 H2 §809, H-A-455 (1)). type RecordAct struct { + // Record is its record's key, `.`, the index acts's field. + Record string `json:"record,omitempty"` ID string `json:"id"` Act string `json:"act"` Repository string `json:"repository"` @@ -66,22 +73,87 @@ type RecordAct struct { Owed seat.Owed `json:"owed"` } -// Act writes one act into the record: said (no outcome), or ended; nothing when the record holds it so already. +// TypeAct is the ledger type of an act's entry, and ActsIndex the ledger's index of the acts' entries on their record's key +// (manifest `requires` records' types and indexes; H-A-455 (1)). +const ( + TypeAct = "act" + ActsIndex = "acts" +) + +// ActOperations are an act's operations, in the order the manifest's type act allows them. +var ActOperations = []string{OpAct} + +// ActInstance is the entry of a record's act: `act/`, escaped as a name. +func ActInstance(milestone, id string) (string, error) { + if strings.TrimSpace(id) == "" { + return "", fmt.Errorf("an act of the record %s names its id", milestone) + } + inst := TypeAct + "/" + milestoneToken(milestone+".act."+id) + if !segmentRe.MatchString(strings.TrimPrefix(inst, TypeAct+"/")) { + return "", fmt.Errorf("the act %s of %s cannot be named: %q", id, milestone, inst) + } + return inst, nil +} + +// Act writes one act's entry: said (no outcome), or ended; removed when the forge bridge performed it; nothing when the +// record holds it so already. Its write is measured as every entry's is (H-A-455 (3)). func (rs *Records) Act(r *Record, a RecordAct) error { if had, ok := r.Acts[a.ID]; ok && had.Outcome == a.Outcome { return nil } - seq, err := rs.Ledger.Apply(r.Instance, OpAct, a) + inst, err := ActInstance(r.Milestone, a.ID) if err != nil { return err } + if a.Outcome == forgemsg.OwedPerformed { + if err := rs.Ledger.Remove(inst); err != nil { + return err + } + delete(r.Acts, a.ID) + rs.fitted(r, inst) + return nil + } + a.Record = r.Milestone + if _, err := rs.write(r, inst, OpAct, a, a); err != nil { + return err + } if r.Acts == nil { r.Acts = map[string]RecordAct{} } - r.Acts[a.ID], r.Sequence = a, seq + r.Acts[a.ID] = a return nil } +// acts reads the acts' entries of a record through the index, one query, and each entry; nil when it has none. +func (rs *Records) acts(milestone string) (map[string]RecordAct, error) { + insts, err := rs.Ledger.Query(ActsIndex, moversKey(milestone)) + if err != nil { + return nil, fmt.Errorf("the acts of the record %s cannot be read: %w", milestone, err) + } + var out map[string]RecordAct + for _, inst := range insts { + raw, _, err := rs.Ledger.Get(inst) + if err != nil { + return nil, err + } + if raw == nil { + continue + } + var a RecordAct + if err := json.Unmarshal(raw, &a); err != nil { + return nil, fmt.Errorf("the act %s is not readable: %w", inst, err) + } + if a.Record != milestone || a.ID == "" { + continue + } + if out == nil { + out = map[string]RecordAct{} + } + out[a.ID] = a + } + return out, nil +} + // owedBound is how long an act said may wait for its owed.ended before it is stalled: many times a forge call's time, and // short beside the check's hour (design 47 *What the gate owes the forge*). const owedBound = 15 * time.Minute diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/react.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/react.go index 22846e925..aa37b98d1 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/react.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/react.go @@ -55,15 +55,15 @@ func (h *Holder) Work() { } } -// React takes every step the facts allow, after an event that can change what they are: the conditions of what stalled -// (conditions.go), and then the time the next look is wanted at, if any step waits on the clock. Never concurrent with itself. +// React takes every step the facts allow, after an event that can change what they are: the held heads past untaken-bound +// (heads.go), and then the time the next look is wanted at, if any step waits on the clock. Never concurrent with itself. func (h *Holder) React() { h.reactMu.Lock() defer h.reactMu.Unlock() h.wanted.mu.Lock() h.wanted.at, h.wanted.step = time.Time{}, "" h.wanted.mu.Unlock() - h.sayConditions() + h.lookAtHeads() h.arm() } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index 831f3f682..b7f4804ee 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -22,6 +22,7 @@ import ( "time" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/buscalls" ) @@ -31,7 +32,7 @@ const RecordsLedger = "records" // RecordForm is the form of the records' layout (design 47 *A module's kept data on the bus*): raised whenever the gate // changes how it writes them. -const RecordForm = 1 +const RecordForm = 3 // The ledger's two types: a record, and the list of the records opened in one month (the ledger is listed through it, // since a bundle has no listing of a ledger's instances; a month of about 600 records keeps it far under a value's 256 @@ -39,56 +40,30 @@ const RecordForm = 1 const ( TypeRecord = "record" TypeHeld = "held" - // TypeSwitch holds the one key `switch.done` (A-281): the gate's fingerprint and the time of the switch to the records. - TypeSwitch = "switch" ) // The operations of a record, each one effect (ADR 0597 §2), and of the month's list. The manifest's `requires` declares // exactly these (record_test.go). const ( - OpOpen = "open" // set-fields: the milestone, the heads, when, forge-made, the form + OpOpen = "open" // set-fields: the milestone, its branch, source revision and merge call, the heads, when, the form OpGroup = "group" // set-fields: the group's state OpTrace = "trace" // set-fields: the trace - OpEntry = "entry" // set-entry into entries: one entry of the graph difference, by its module, fingerprint and node - OpOutcome = "outcome" // set-entry into outcomes, by the entry, the node and the step + OpEntry = "entry" // a mover's: set-entry into entries, one entry of the graph difference, by its module, fingerprint and node + OpOutcome = "outcome" // a mover's: set-entry into outcomes, by the entry, the node and the step OpAway = "away" // set-entry into away, by node OpBack = "back" // remove from away, by node - OpPin = "pin" // set-entry into pinned, by revision - OpFree = "free" // remove from pinned, by revision OpEnd = "end" // set-fields: ended - OpAct = "act" // set-entry into acts, by id: an act owed the forge with its outcome + OpAct = "act" // an act's entry (TypeAct): set-fields, an act owed the forge with its outcome OpHold = "hold" // a month's list: set-entry into records, by instance OpDrop = "drop" // a month's list: remove from records, by instance - OpDone = "done" // the switch: set-fields, the gate's fingerprint and the time ) // RecordOperations are a record's operations, in the order the manifest's type allows them. -var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpEntry, OpOutcome, OpAway, OpBack, OpPin, OpFree, OpAct, OpEnd} +var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpMovers, OpPhases, OpAway, OpBack, OpEnd} // HeldOperations are the month's list's operations. var HeldOperations = []string{OpHold, OpDrop} -// SwitchOperations are the switch key's operations. -var SwitchOperations = []string{OpDone} - -// switchInstance is the instance of the key `switch.done`, written once the switch has carried today's state in (A-281). -const switchInstance = TypeSwitch + "/done" - -// SwitchDone says whether the key `switch.done` is there: the switch has run, and no later start runs it again (A-281). -func (rs *Records) SwitchDone() (bool, error) { - raw, _, err := rs.Ledger.Get(switchInstance) - if err != nil { - return false, fmt.Errorf("the key switch.done cannot be read: %w", err) - } - return len(raw) > 0 && string(raw) != "null", nil -} - -// MarkSwitched writes the key `switch.done`: the gate's fingerprint and the time (A-281). -func (rs *Records) MarkSwitched(fingerprint string) error { - _, err := rs.Ledger.Apply(switchInstance, OpDone, map[string]any{"fingerprint": fingerprint, "at": rs.now().UTC().Format(time.RFC3339)}) - return err -} - // DefaultRecordRetention is how long a record is kept when the setting record-retention gives none (design 47: 90 days // covers every trace the operator has asked of a past delivery so far). const DefaultRecordRetention = 90 * 24 * time.Hour @@ -100,14 +75,17 @@ type Record struct { // Sequence is the last operation the state holds; not in the state. Sequence uint64 `json:"-"` + // Milestone is the record's key, `.`, each escaped as a name (design 47 H §737, A-33). Milestone string `json:"milestone"` - // Heads are the heads the record is for: each member's id (owner/repository@commit) to its full commit. + // Branch, Source and Call are the watched branch, its source revision and the merge call that named it (§737). + Branch string `json:"branch,omitempty"` + Source int64 `json:"source,omitempty"` + Call string `json:"call,omitempty"` + // Heads are the members the record is for: each member's id (`@` for a merge call's member, + // `@` for a hand take, H-A-48) to its full commit. Heads map[string]string `json:"heads"` Opened time.Time `json:"opened"` - // ForgeMade is a record opened for a merge the forge made with no record's merge-pull (design 47 *What the gate owes - // the forge*): it has no Approve. - ForgeMade bool `json:"forge-made,omitempty"` - Form int `json:"form,omitempty"` + Form int `json:"form,omitempty"` Group *RecordGroup `json:"group,omitempty"` Trace *RecordTrace `json:"trace,omitempty"` @@ -117,13 +95,23 @@ type Record struct { Outcomes map[string]RecordOutcome `json:"outcomes,omitempty"` // Away are the nodes away, by node, each with since when. Away map[string]NodeAway `json:"away,omitempty"` - // Pinned are the graph revisions the record points at, by revision. - Pinned map[string]PinnedRevision `json:"pinned,omitempty"` - // Acts are the acts owed the forge for the record's pull requests, by id, with their outcomes (owedended.go). + // Acts are the acts owed the forge for the record's pull requests, by id, with their outcomes (owedended.go): each an + // entry of its own, joined when read, never on the head entry (design 47 H2 §809, H-A-455 (1)). Acts map[string]RecordAct `json:"acts,omitempty"` Ended *RecordEnded `json:"ended,omitempty"` // Recovery marks the merge its author named a recovery by the seat's verb recovery (design 47 G §81, A-23). Recovery *RecordRecovery `json:"recovery,omitempty"` + // MoverCount is the count of its movers, each with an entry of its own (design 47 H2 §809); Entries and Outcomes above + // are joined from those entries when read. + MoverCount int `json:"movers,omitempty"` + // MergeCalled is the merge-called event's own time, from the record's opening; DeliveryTime (a duration) and Class are + // written at its end, Phases at its pipeline's end (design 47 H2 §810, §785; H-A-394). + MergeCalled time.Time `json:"merge-called,omitzero"` + DeliveryTime string `json:"delivery-time,omitempty"` + Class string `json:"class,omitempty"` + Phases *runner.PipelineEndedPhases `json:"phases,omitempty"` + + movers map[string]*Mover } // RecordRecovery is the field recovery of a record: who named the merge a recovery (the caller the runtime proved), why, @@ -166,6 +154,13 @@ type RecordTrace struct { Source string `json:"source,omitempty"` From string `json:"from,omitempty"` To string `json:"to,omitempty"` + // Call is the merge call, By the caller as who@node and Account the bus account the tool runner proved for it + // (design 47 H §737); Hand marks a head taken in by hand (§742), At when (H-A-24: hand, by and the time live here). + Call string `json:"call,omitempty"` + By string `json:"by,omitempty"` + Account string `json:"account,omitempty"` + Hand bool `json:"hand,omitempty"` + At time.Time `json:"at,omitzero"` } // The outcomes an entry has on a node (ADR 0656 §7, design 47 *The delivery record*). @@ -220,14 +215,6 @@ type NodeAway struct { Since time.Time `json:"since"` } -// PinnedRevision is a graph revision the record points at: its half (catalog or assignment), its revision and, for a catalog -// revision, the watched branch it is numbered on. -type PinnedRevision struct { - Revision string `json:"revision"` - Half string `json:"half"` - Branch string `json:"branch,omitempty"` -} - // RecordEnded is how a record ended: when, why, by whom, and the nodes away it ended without. type RecordEnded struct { At time.Time `json:"at"` @@ -268,34 +255,13 @@ func milestoneToken(milestone string) string { return b.String() + "_" + hex.EncodeToString(sum[:4]) } -// HeadsDigest is the digest of a set of heads: each member's id and full commit, sorted, sixteen hex characters. -func HeadsDigest(heads map[string]string) string { - ids := make([]string, 0, len(heads)) - for id := range heads { - ids = append(ids, id) - } - sort.Strings(ids) - h := sha256.New() - for _, id := range ids { - fmt.Fprintf(h, "%s=%s\n", strings.ToLower(id), strings.ToLower(heads[id])) - } - return hex.EncodeToString(h.Sum(nil))[:16] -} - -// RecordInstance is the instance of the record of a milestone at its heads: `record//`. -func RecordInstance(milestone string, heads map[string]string) (string, error) { +// RecordInstance is the instance of the record of a source revision, by its key `.` alone: +// `record/` (design 47 H §737; H-A-29: a record is read by its key, never by reading every record). +func RecordInstance(milestone string) (string, error) { if strings.TrimSpace(milestone) == "" { return "", errors.New("a delivery record names its milestone") } - if len(heads) == 0 { - return "", fmt.Errorf("the delivery record of %s names no heads", milestone) - } - for id, sha := range heads { - if id == "" || sha == "" { - return "", fmt.Errorf("the delivery record of %s names a head with no id or commit (%q=%q)", milestone, id, sha) - } - } - inst := TypeRecord + "/" + milestoneToken(milestone) + "/" + HeadsDigest(heads) + inst := TypeRecord + "/" + milestoneToken(milestone) for _, p := range strings.Split(inst, "/") { if !segmentRe.MatchString(p) { return "", fmt.Errorf("the delivery record of %s cannot be named: %q", milestone, inst) @@ -314,6 +280,8 @@ type RecordLedger interface { Get(instance string) (json.RawMessage, uint64, error) // Remove removes a record with its operations and its snapshot through the tool runner's ledger removal. Remove(instance string) error + // Query is the instances a declared index names under key (`>` for the rest). + Query(index, key string) ([]string, error) } // sdkLedger is the gate's ledger through the runtime: the tool runner's ledger calls, on the gate's own ledger only @@ -363,6 +331,22 @@ func (sdkLedger) Remove(instance string) error { return nil } +func (sdkLedger) Query(index, key string) ([]string, error) { + out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key}) + if err != nil { + return nil, err + } + var got buscalls.QueryAnswer + if err := json.Unmarshal(out, &got); err != nil { + return nil, fmt.Errorf("the ledger's answer to the query of %s is not readable: %w", index, err) + } + insts := make([]string, 0, len(got.Entries)) + for _, e := range got.Entries { + insts = append(insts, e.Instance) + } + return insts, nil +} + func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) if err != nil { @@ -392,6 +376,12 @@ type Records struct { // Changed is told of every change of a record that owes the forge an act (A-39): a step's outcome applied, the record // ended (owedacts.go); nil owes none. Changed func(r *Record, c RecordChange) + // Class reads a mover's class from its catalog entry by its fingerprint (design 47 H2 §810; H-A-394 (2)), once, when its + // entry opens; nil reads none, every mover a leaf. + Class func(fingerprint string) (string, error) + // TooLarge raises (raised) or clears record-too-large for an entry of the record named by its head's instance, the + // finding's subject (§809; H-A-460); an empty instance clears every one held of the record (its end). nil raises none. + TooLarge func(record, instance string, bytes int, raised bool) // held are the records kept, by instance, read once from the ledger (Current) and kept as the gate writes them: the // gate is their one writer. @@ -501,39 +491,56 @@ func (rs *Records) Read(instance string) (*Record, error) { return nil, nil } r.Instance, r.Sequence = instance, seq + ms, err := rs.movers(r.Milestone) + if err != nil { + return nil, err + } + r.join(ms) + // A head written before the acts had entries of their own is read for its fields; the acts embedded in it are ignored + // (design 47 H2 §809, H-A-457): the record's acts are its act entries alone. + if r.Acts, err = rs.acts(r.Milestone); err != nil { + return nil, err + } return &r, nil } -// Open opens the record of a milestone at its heads, unless one is there already, which is left as it is (the switch -// and a delivery of milestone G again after a revert make no second record and ask nothing again). Opened says it was -// opened now. Each open removes the records past their retention first (the retention needs no timer: records open as -// deliveries do). -func (rs *Records) Open(milestone string, heads map[string]string, forgeMade bool) (r *Record, opened bool, err error) { - return rs.open(milestone, heads, forgeMade, ForgeMerge{}) +// RecordOpening is what a record opens with: the source revision it is the record of, the merge call that named it, its +// members and its trace (design 47 H §737). +type RecordOpening struct { + Branch string + Source int64 + Call string + // Heads are the members, each id to its full commit. + Heads map[string]string + Trace RecordTrace } -// ForgeMerge is the merge a forge-made record is for: what record-opened says of it (design 47 G A-161). -type ForgeMerge struct { - Repository string - Pull int64 - Commit string - Branch string -} - -// OpenForgeMade opens the record of a merge made at the forge, marked forge-made, and says record-opened with the merge's -// repository, pull request, commit and branch, so the teller makes no call per message (A-161). No path of the gate opens one -// from G's delivery (§151): the teller says none while nothing calls this. -func (rs *Records) OpenForgeMade(milestone string, heads map[string]string, m ForgeMerge) (r *Record, opened bool, err error) { - return rs.open(milestone, heads, true, m) -} - -func (rs *Records) open(milestone string, heads map[string]string, forgeMade bool, m ForgeMerge) (r *Record, opened bool, err error) { - inst, err := RecordInstance(milestone, heads) +// Open opens the record of a source revision, unless one is there already, which is left as it is (a merge call heard +// again opens no second record and says nothing new). Opened says it was opened now. Each open removes the records past +// their retention first (the retention needs no timer: records open as deliveries do). +func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { + if o.Branch == "" || o.Source < 1 || o.Call == "" { + return nil, false, fmt.Errorf("a delivery record names its branch, its source revision and its merge call (%q, %d, %q)", o.Branch, o.Source, o.Call) + } + if len(o.Heads) == 0 { + return nil, false, fmt.Errorf("the delivery record of %s at %d names no member", o.Branch, o.Source) + } + for id, sha := range o.Heads { + if id == "" || sha == "" { + return nil, false, fmt.Errorf("the delivery record of %s at %d names a member with no id or commit (%q=%q)", o.Branch, o.Source, id, sha) + } + } + milestone := recordMilestone(o.Branch, o.Source) + inst, err := RecordInstance(milestone) if err != nil { return nil, false, err } - if r, err = rs.Read(inst); err != nil || r != nil { - return r, false, err + if r, err = rs.Read(inst); err != nil { + return nil, false, err + } + if r != nil { + rs.sayOpened(r) + return r, false, nil } now := rs.now() if err := rs.Sweep(now); err != nil { @@ -543,11 +550,13 @@ func (rs *Records) open(milestone string, heads map[string]string, forgeMade boo if err != nil { return nil, false, err } - body := map[string]any{"milestone": milestone, "heads": heads, "opened": now, "form": RecordForm} - if forgeMade { - body["forge-made"] = true + called := o.Trace.At.UTC() + if o.Trace.At.IsZero() { + called = now } - if _, err := rs.Ledger.Apply(inst, OpOpen, body); err != nil { + body := map[string]any{"milestone": milestone, "branch": o.Branch, "source": o.Source, "call": o.Call, "heads": o.Heads, + "opened": now, "form": RecordForm, "merge-called": called} + if _, err := rs.write(&Record{Milestone: milestone}, inst, OpOpen, body, body); err != nil { return nil, false, err } if _, err := rs.Ledger.Apply(heldInstance(now), OpHold, heldEntry{Instance: inst, Opened: now}); err != nil { @@ -556,19 +565,51 @@ func (rs *Records) open(milestone string, heads map[string]string, forgeMade boo if read { rs.sayFilling(inst, before) } - r, err = rs.Read(inst) - if err == nil && r != nil { + if r, err = rs.Read(inst); err != nil || r == nil { + return r, false, err + } + if err := rs.SetTrace(r, o.Trace); err != nil { + return r, true, fmt.Errorf("the record %s is opened and its trace is not written: %w", inst, err) + } + rs.keep(r) + rs.sayOpened(r) + return r, true, nil +} + +// ByKey is the record of a source revision, read by its key `.` (H-A-29); nil when none is kept. +func (rs *Records) ByKey(branch string, source int64) (*Record, error) { + return rs.ByMilestone(recordMilestone(branch, source)) +} + +// ByMilestone is the record of a key `.` (a pipeline's key of its source revision, H-A-89 (5)): the one +// the gate keeps as it writes it when it holds it, so a write through it is seen by every reader, else read from the +// ledger; nil when none is kept. +func (rs *Records) ByMilestone(milestone string) (*Record, error) { + inst, err := RecordInstance(milestone) + if err != nil { + return nil, err + } + rs.mu.Lock() + held := rs.held[inst] + rs.mu.Unlock() + if held != nil { + return held, nil + } + r, err := rs.Read(inst) + if r != nil { rs.keep(r) - // Said once, under the record's id: the watchman times it against 24 hours, ended by record-ended. A say that fails is - // said again by the next write of the record (the id keeps it once). - at := now.UTC() - if serr := rs.say(meshdelivery.SubjectRecordOpened, meshdelivery.RecordOpenedEvent{Record: inst, Milestone: milestone, ForgeMade: forgeMade, At: &at, - Repository: m.Repository, Pull: m.Pull, Commit: m.Commit, Branch: m.Branch}, - "record-opened."+inst); serr != nil && rs.Logf != nil { - rs.Logf("[mesh-delivery] the record %s is opened and its opening is not said: %v", inst, serr) - } + } + return r, err +} + +// sayOpened says record-opened on record-opened., so the session that called waits on its own call (§737). Said under +// the record's id, so a merge call heard again says it once: a say that fails is said again when the call is heard again. +func (rs *Records) sayOpened(r *Record) { + at := r.Opened.UTC() + if err := rs.say(meshdelivery.SubjectRecordOpened(r.Call), meshdelivery.RecordOpenedEvent{Record: r.Instance, + Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at}, "record-opened."+r.Instance); err != nil && rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s is opened and its opening is not said: %v", r.Instance, err) } - return r, err == nil && r != nil, err } // List is every record kept, opened within the retention and a month more, oldest first. @@ -621,9 +662,7 @@ func (rs *Records) heldIn(month string) ([]heldEntry, error) { return out, nil } -// Sweep removes every record opened longer ago than the retention, and says `freed` for each revision it pinned -// (design 47: "When the retention removes a record, the gate says freed for each revision it pinned"). Nothing else is -// removed to make room. +// Sweep removes every record opened longer ago than the retention. Nothing else is removed to make room. func (rs *Records) Sweep(now time.Time) error { cut := now.Add(-rs.retention()) for _, m := range rs.months(now) { @@ -640,8 +679,19 @@ func (rs *Records) Sweep(now time.Time) error { return err } if r != nil { - if err := rs.sayFreedAll(r, "the record is past its retention"); err != nil { - return err + for _, m := range r.movers { + if err := rs.Ledger.Remove(m.Instance); err != nil { + return err + } + } + for id := range r.Acts { + inst, err := ActInstance(r.Milestone, id) + if err != nil { + return err + } + if err := rs.Ledger.Remove(inst); err != nil { + return err + } } if err := rs.Ledger.Remove(e.Instance); err != nil { return err @@ -656,21 +706,14 @@ func (rs *Records) Sweep(now time.Time) error { return nil } -func sortedPins(r *Record) []PinnedRevision { - out := make([]PinnedRevision, 0, len(r.Pinned)) - for _, p := range r.Pinned { - out = append(out, p) - } - sort.Slice(out, func(i, j int) bool { return out[i].Revision < out[j].Revision }) - return out -} - // SetGroup writes the record's group state, unless it holds that state already. func (rs *Records) SetGroup(r *Record, g RecordGroup) error { if r.Group != nil && reflect.DeepEqual(*r.Group, g) { return nil } - seq, err := rs.Ledger.Apply(r.Instance, OpGroup, map[string]any{"group": g}) + next := *r + next.Group = &g + seq, err := rs.write(r, r.Instance, OpGroup, map[string]any{"group": g}, next.head()) if err != nil { return err } @@ -683,7 +726,9 @@ func (rs *Records) SetTrace(r *Record, t RecordTrace) error { if r.Trace != nil && reflect.DeepEqual(*r.Trace, t) { return nil } - seq, err := rs.Ledger.Apply(r.Instance, OpTrace, map[string]any{"trace": t}) + next := *r + next.Trace = &t + seq, err := rs.write(r, r.Instance, OpTrace, map[string]any{"trace": t}, next.head()) if err != nil { return err } @@ -701,14 +746,21 @@ func (rs *Records) Outcome(r *Record, o RecordOutcome) (applied bool, err error) if had, ok := r.Outcomes[o.Key]; ok && (had.Event != "" && had.Event == o.Event || sameOutcome(had, o)) { return false, nil } - seq, err := rs.Ledger.Apply(r.Instance, OpOutcome, o) + m, err := rs.mover(r, o.Module, o.Fingerprint) if err != nil { return false, err } + next := *m + next.Outcomes = withEntry(m.Outcomes, o.Key, o) + seq, err := rs.write(r, m.Instance, OpOutcome, o, next) + if err != nil { + return false, err + } + m.Outcomes, m.Sequence = next.Outcomes, seq if r.Outcomes == nil { r.Outcomes = map[string]RecordOutcome{} } - r.Outcomes[o.Key], r.Sequence = o, seq + r.Outcomes[o.Key] = o if rs.Changed != nil { rs.Changed(r, RecordChange{What: outcomeWords(o), Why: firstOf(o.Why, "the "+o.Step+" step's event")}) } @@ -721,17 +773,40 @@ func (rs *Records) AddEntry(r *Record, e RecordEntry) error { if had, ok := r.Entries[e.Key]; ok && had == e { return nil } - seq, err := rs.Ledger.Apply(r.Instance, OpEntry, e) + m, err := rs.mover(r, e.Module, e.Fingerprint) if err != nil { return err } + next := *m + next.Entries = withEntry(m.Entries, e.Key, e) + seq, err := rs.write(r, m.Instance, OpEntry, e, next) + if err != nil { + return err + } + m.Entries, m.Sequence = next.Entries, seq if r.Entries == nil { r.Entries = map[string]RecordEntry{} } - r.Entries[e.Key], r.Sequence = e, seq + r.Entries[e.Key] = e return nil } +// withEntry is a copy of m with v under k. +func withEntry[V any](m map[string]V, k string, v V) map[string]V { + out := make(map[string]V, len(m)+1) + for key, val := range m { + out[key] = val + } + out[k] = v + return out +} + +// head is the record's head entry as the ledger holds it: every record-wide field, none of a mover's and no act. +func (r Record) head() Record { + r.Entries, r.Outcomes, r.movers, r.Acts = nil, nil, nil, nil + return r +} + // sameOutcome is whether two outcomes say the same, whenever and from whichever event they were taken. func sameOutcome(a, b RecordOutcome) bool { a.At, b.At, a.Event, b.Event = time.Time{}, time.Time{}, "", "" diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index 0cb23b623..513150b59 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -6,17 +6,20 @@ import ( "fmt" "os" "path/filepath" - "reflect" "slices" + "sort" "strings" "testing" "time" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/buscalls" "git.novox.be/novox/mesh-sdk/go/catalogue" + + runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" ) // ledgerFake plays the tool runner's ledger for the gate's `records`, from the types the manifest declares: each operation @@ -151,6 +154,33 @@ func (f *ledgerFake) Remove(instance string) error { return nil } +// Query answers a declared index as the tool runner's watcher keeps it: the key of each instance whose type declares the +// index, from the values of its fields and its path (buscalls.IndexKey), matched with `>` for the rest. +func (f *ledgerFake) Query(index, key string) ([]string, error) { + var out []string + for inst, raw := range f.states { + ty := f.types[strings.SplitN(inst, "/", 2)[0]] + for _, ix := range ty.Indexes { + if ix.Name != index || string(raw) == "null" { + continue + } + state := map[string]any{} + _ = json.Unmarshal(raw, &state) + var vals []string + for _, on := range ix.On { + v, _ := state[on].(string) + vals = append(vals, v) + } + k := buscalls.IndexKey(vals, inst) + if k == key || strings.HasSuffix(key, ">") && strings.HasPrefix(k, strings.TrimSuffix(key, ">")) { + out = append(out, inst) + } + } + } + sort.Strings(out) + return out, nil +} + func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) { s := f.states[instance] if s == nil || string(s) == "null" { @@ -159,50 +189,195 @@ func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) { return s, f.seq[instance], nil } -// W11.1 (ADR 0656 §7, design 47 *The delivery record*): one record per milestone's delivery, a ledger instance keyed by its -// milestone and its heads, kept for its retention, its operations those the manifest's ledger types allow. -func TestTheDeliveryRecordIsALedgerInstanceKeyedByMilestoneAndHeads(t *testing.T) { - heads := map[string]string{"novox/app@111111111111": strings.Repeat("1", 40), "novox/lib@222222222222": strings.Repeat("2", 40)} - same := map[string]string{"novox/lib@222222222222": strings.Repeat("2", 40), "novox/app@111111111111": strings.Repeat("1", 40)} - other := map[string]string{"novox/app@111111111111": strings.Repeat("3", 40), "novox/lib@222222222222": strings.Repeat("2", 40)} +// W11.1 (ADR 0656 §7, design 47 *The delivery record*; H §737, H-A-29): one record per source revision, a ledger +// instance keyed by `.` alone, kept for its retention, its operations those the manifest's ledger types allow. +func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T) { + heads := map[string]string{"novox/app@3": strings.Repeat("1", 40), "novox/lib@4": strings.Repeat("2", 40)} + same := map[string]string{"novox/lib@4": strings.Repeat("2", 40), "novox/app@3": strings.Repeat("1", 40)} at := time.Date(2026, 11, 9, 20, 0, 0, 0, time.UTC) - t.Run("an instance per milestone and heads, a path the tool runner takes", func(t *testing.T) { - a, err := RecordInstance("47/G", heads) + // One entry per module and revision (design 47 H2 §809; H-A-385, H-A-391): 126 movers write 127 entries, none over + // 64 KiB, the head counting 126; an entry made too large is refused with record-too-large, cleared at the record's end. + t.Run("a record of 126 movers writes 127 entries, each within 64 KiB", func(t *testing.T) { + l := newLedgerFake(t) + // The findings are the gate's own findings state (H-A-460): a fresh Records, as after a restart, reads them there. + fw := &findingsFake{held: map[string]meshconditions.Finding{}} + h := &Holder{Findings: fw, Now: func() time.Time { return at }} + found := fw.held + rs := &Records{Ledger: l, Now: func() time.Time { return at }, TooLarge: h.recordTooLarge} + r, _, err := rs.Open(opening("main", 90, heads)) if err != nil { t.Fatal(err) } - b, _ := RecordInstance("47/G", same) - c, _ := RecordInstance("47/G", other) - d, _ := RecordInstance("47_G", heads) - if a != b || a == c || a == d { - t.Fatalf("instances %s %s %s %s: one per milestone and heads, whatever the heads' order", a, b, c, d) + for i := range 126 { + module := fmt.Sprintf("mod-%03d", i) + if err := rs.AddEntry(r, RecordEntry{Module: module, Fingerprint: "src2:f" + module}); err != nil { + t.Fatal(err) + } + if err := rs.SetMover(r, module, "src2:f"+module, "main.90", "0.1.7"); err != nil { + t.Fatal(err) + } + for _, node := range []string{"ace", "g14", "novox", "shanks"} { + if _, err := rs.Outcome(r, RecordOutcome{Module: module, Fingerprint: "src2:f" + module, Node: node, Step: "running", + Outcome: OutcomeRunning, At: at}); err != nil { + t.Fatal(err) + } + } + } + entries := 0 + for inst, raw := range l.states { + if strings.HasPrefix(inst, TypeRecord+"/") || strings.HasPrefix(inst, TypeMover+"/") { + entries++ + if len(raw) > EntryLimit { + t.Errorf("%s holds %d bytes", inst, len(raw)) + } + if strings.HasPrefix(inst, TypeMover+"/") && strings.Count(string(raw), `"module":"mod-`) != 1+1+4 { + t.Errorf("%s names another module: %s", inst, raw) + } + } + } + read, err := rs.Read(r.Instance) + if err != nil || entries != 127 || read.MoverCount != 126 || len(read.Movers()) != 126 || len(read.Outcomes) != 504 || + len(read.Movers()["mod-007"].Running()) != 4 || read.Movers()["mod-007"].Version != "0.1.7" { + t.Fatalf("%d entries, the head counts %d, %d joined, %d outcomes, %v", entries, read.MoverCount, len(read.Movers()), len(read.Outcomes), err) + } + why := strings.Repeat("w", EntryLimit) + if _, err := rs.Outcome(read, RecordOutcome{Module: "mod-001", Fingerprint: "src2:fmod-001", Node: "ace", Step: "build", + Outcome: OutcomeFailed, Why: why, At: at}); err == nil || !strings.Contains(err.Error(), RecordTooLarge) || len(found) != 1 { + t.Fatalf("an entry over 64 KiB was taken (%v), findings %v", err, found) + } + // H-A-455 (3): an act's write is measured as a mover's is, and the record's end clears its finding too. + if err := rs.Act(read, RecordAct{ID: "view@1.a", Act: "view", Repository: "novox/app", Number: 3, Head: heads["novox/app@3"], + Owed: meshdelivery.Owed{Act: meshdelivery.OwedActView, Text: why}}); err == nil || !strings.Contains(err.Error(), RecordTooLarge) || len(found) != 2 { + t.Fatalf("an act over 64 KiB was taken (%v), findings %v", err, found) + } + for _, f := range found { + if f.Subject.ID != read.Instance { + t.Fatalf("a refusal of %s names %q as its subject, not its record %s", f.ID, f.Subject.ID, read.Instance) + } + } + // Another record's refusal is not this record's to clear. + other, _ := RecordInstance("main.other") + h.recordTooLarge(other, "mover/main_other_x", EntryLimit+1, true) + // A fresh Records, as after a restart, ends the record: every refusal of it clears, the act never written among + // them, read from the findings state alone (§809, H-A-455 (3), H-A-460). + restarted := &Records{Ledger: l, Now: func() time.Time { return at }, TooLarge: h.recordTooLarge} + again, err := restarted.Read(r.Instance) + if err != nil { + t.Fatal(err) + } + if err := restarted.End(again, "every present node runs its entries", ""); err != nil || len(found) != 1 { + t.Fatalf("the record's end after a restart left %v (%v)", found, err) + } + if _, ok := found[FindingScope+".mover/main_other_x."+RecordTooLarge]; !ok { + t.Fatalf("the record's end cleared another record's refusal: %v", found) + } + }) + + // A record keeps its delivery time and class; gate_times judges them against the budgets (design 47 H2 §810; H-A-394). + t.Run("a core record ended 11 minutes after merge-called is over its budget", func(t *testing.T) { + now := at + rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return now }, Class: func(fp string) (string, error) { + if fp == "src2:core" { + return catalogue.ClassCore, nil + } + return "", nil + }} + h := &Holder{Records: rs, Now: func() time.Time { return now }} + for i, c := range []struct { + fp string + took time.Duration + }{{"src2:core", 11 * time.Minute}, {"src2:leaf", 2 * time.Minute}, {"src2:core", 4 * time.Minute}} { + o := opening("main", int64(200+i), heads) + o.Trace.At = now + r, _, err := rs.Open(o) + if err != nil { + t.Fatal(err) + } + if err := rs.AddEntry(r, RecordEntry{Module: "m" + c.fp, Fingerprint: c.fp}); err != nil { + t.Fatal(err) + } + p := now.Add(time.Minute) + if err := rs.SetPhases(r, &runner.PipelineEndedPhases{Taken: &now, Placed: &p, Build: &runner.PipelineEndedPhasesBuild{Start: &p, End: ptrTime(p.Add(7 * time.Minute))}}); err != nil { + t.Fatal(err) + } + if _, err := rs.Outcome(r, RecordOutcome{Module: "m" + c.fp, Fingerprint: c.fp, Node: "ace", Step: "running", Outcome: OutcomeRunning, At: now.Add(c.took)}); err != nil { + t.Fatal(err) + } + now = now.Add(c.took) + if err := rs.End(r, WhyAllRun, ""); err != nil { + t.Fatal(err) + } + if r.DeliveryTime != c.took.String() { + t.Fatalf("record %d keeps %q, want %s", i, r.DeliveryTime, c.took) + } + } + times, err := h.Times() + core, leaf := times[catalogue.ClassCore], times[catalogue.ClassLeaf] + if err != nil || core.Budget != "10m0s" || core.Deliveries != 2 || len(core.Over) != 1 || core.Over[0].DeliveryTime != "11m0s" || + core.Over[0].Longest != "build" || core.Worst != "11m0s" || leaf.Deliveries != 1 || len(leaf.Over) != 0 || + core.Last == nil || core.Last.Over || core.Last.DeliveryTime != "4m0s" || leaf.Last == nil || leaf.Last.Over { + t.Fatalf("gate_times %+v %v", times, err) + } + }) + + t.Run("an instance per source revision, a path the tool runner takes", func(t *testing.T) { + a, err := RecordInstance(recordMilestone("feat/x", 7)) + if err != nil { + t.Fatal(err) + } + b, _ := RecordInstance(recordMilestone("feat/x", 8)) + c, _ := RecordInstance(recordMilestone("feat_x", 7)) + if a == b || a == c { + t.Fatalf("instances %s %s %s: one per branch and source revision", a, b, c) } for _, p := range strings.Split(a, "/") { if !segmentRe.MatchString(p) { t.Fatalf("%s has a part the tool runner refuses", a) } } - if _, err := RecordInstance("", heads); err == nil { + if _, err := RecordInstance(""); err == nil { t.Fatal("a record with no milestone is named") } - if _, err := RecordInstance("47/G", nil); err == nil { - t.Fatal("a record with no heads is named") + rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }} + for _, o := range []RecordOpening{{Branch: "main", Source: 1, Call: "0000000000000001"}, {Branch: "main", Call: "0000000000000001", Heads: heads}, + {Branch: "main", Source: 1, Heads: heads}, {Source: 1, Call: "0000000000000001", Heads: heads}} { + if _, _, err := rs.Open(o); err == nil { + t.Fatalf("a record is opened with %+v", o) + } } }) - t.Run("opened once; a second open leaves it as it is", func(t *testing.T) { + t.Run("opened once, said on record-opened.; a second open leaves it as it is and says the same", func(t *testing.T) { l := newLedgerFake(t) now := at - rs := &Records{Ledger: l, Now: func() time.Time { return now }} - r, opened, err := rs.Open("47/G", heads, false) - if err != nil || !opened || r == nil || r.Milestone != "47/G" || len(r.Heads) != 2 || !r.Opened.Equal(at) || r.Form != RecordForm { + type said struct { + subject, id string + body meshdelivery.RecordOpenedEvent + } + var got []said + rs := &Records{Ledger: l, Now: func() time.Time { return now }, Say: func(subject string, body any, id string) error { + got = append(got, said{subject, id, body.(meshdelivery.RecordOpenedEvent)}) + return nil + }} + o := opening("main", 47, heads) + o.Trace = RecordTrace{Call: o.Call, By: "lead@shanks", Account: "acct-s"} + r, opened, err := rs.Open(o) + if err != nil || !opened || r == nil || r.Milestone != recordMilestone("main", 47) || r.Branch != "main" || r.Source != 47 || + r.Call != o.Call || len(r.Heads) != 2 || !r.Opened.Equal(at) || r.Form != RecordForm || r.Trace == nil || r.Trace.By != "lead@shanks" { t.Fatalf("open: %+v %v %v", r, opened, err) } now = at.Add(time.Hour) - again, opened, err := rs.Open("47/G", same, false) + again, opened, err := rs.Open(opening("main", 47, same)) if err != nil || opened || again.Instance != r.Instance || !again.Opened.Equal(at) { - t.Fatalf("a second open of the same heads: %+v %v %v", again, opened, err) + t.Fatalf("a second open of the same revision: %+v %v %v", again, opened, err) + } + if len(got) != 2 || got[0].id != got[1].id || *got[0].body.At != *got[1].body.At || got[0].subject != meshdelivery.SubjectRecordOpened(o.Call) || + got[0].body.Branch != "main" || got[0].body.Source != 47 || got[0].body.Call != o.Call || got[0].body.Record != r.Instance { + t.Fatalf("said %+v", got) + } + if byKey, err := rs.ByKey("main", 47); err != nil || byKey == nil || byKey.Instance != r.Instance { + t.Fatalf("read by its key: %+v %v", byKey, err) } list, err := rs.List() if err != nil || len(list) != 1 || list[0].Instance != r.Instance { @@ -213,7 +388,7 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByMilestoneAndHeads(t *testing.T t.Run("an outcome applied twice changes nothing", func(t *testing.T) { l := newLedgerFake(t) rs := &Records{Ledger: l, Now: func() time.Time { return at }} - r, _, _ := rs.Open("47/G", heads, false) + r, _, _ := rs.Open(opening("main", 47, heads)) o := RecordOutcome{Module: "mesh-delivery-gate", Fingerprint: "src2:abcd", Node: "ace", Step: "build", Outcome: OutcomeBuilt, At: at, Event: "e1"} if applied, err := rs.Outcome(r, o); err != nil || !applied { t.Fatalf("first: %v %v", applied, err) @@ -245,112 +420,29 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByMilestoneAndHeads(t *testing.T } }) - t.Run("a record past its retention is removed at the next open and frees what it pinned", func(t *testing.T) { + t.Run("a record past its retention is removed at the next open", func(t *testing.T) { l := newLedgerFake(t) now := at - var freed []string - rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }, - Say: func(subject string, body any, id string) error { - if subject == meshdelivery.SubjectFreed { - p := body.(meshdelivery.Pins) - freed = append(freed, fmt.Sprint(p.Milestone, " ", p.Catalog, " ", p.Why)) - } - return nil - }} - old, _, _ := rs.Open("46/F", heads, false) - if err := rs.Pin(old, HalfCatalog, "main", 1); err != nil { - t.Fatal(err) - } + rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }} + old, _, _ := rs.Open(opening("main", 46, heads)) now = at.Add(89 * 24 * time.Hour) - kept, _, _ := rs.Open("47/G", heads, false) - if r, _ := rs.Read(old.Instance); r == nil || len(freed) != 0 { - t.Fatalf("a record within its retention is removed (%v)", freed) + kept, _, _ := rs.Open(opening("main", 47, heads)) + if r, _ := rs.Read(old.Instance); r == nil { + t.Fatal("a record within its retention is removed") } now = at.Add(91 * 24 * time.Hour) - if _, _, err := rs.Open("47/H", heads, false); err != nil { + if _, _, err := rs.Open(opening("main", 48, heads)); err != nil { t.Fatal(err) } if r, _ := rs.Read(old.Instance); r != nil { t.Fatal("a record past its retention is kept") } - if !slices.Equal(freed, []string{"46/F [{main 1}] the record is past its retention"}) { - t.Fatalf("freed %v", freed) - } list, _ := rs.List() if len(list) != 2 || list[0].Instance != kept.Instance { t.Fatalf("list %+v", list) } }) - // W11.9: pinned and freed, said under an id of what they say; only a catalog or an assignment revision is pinned. - t.Run("a pin is written once and said as pinned; a free says freed with why", func(t *testing.T) { - l := newLedgerFake(t) - type said struct { - subject, id string - pins meshdelivery.Pins - } - var got []said - rs := &Records{Ledger: l, Now: func() time.Time { return at }, Say: func(subject string, body any, id string) error { - if subject == meshdelivery.SubjectRecordOpened { - return nil - } - got = append(got, said{subject, id, body.(meshdelivery.Pins)}) - return nil - }} - r, _, _ := rs.Open("47/G", heads, false) - for range 2 { - if err := rs.Pin(r, HalfAssignment, "", 9); err != nil { - t.Fatal(err) - } - } - if err := rs.Pin(r, HalfCatalog, "main", 9); err != nil { - t.Fatal(err) - } - // Revisions are numbered per watched branch: the same number on another branch is another pin. - if err := rs.Pin(r, HalfCatalog, "feat/x", 9); err != nil { - t.Fatal(err) - } - pins := 0 - for _, op := range l.history { - if strings.HasSuffix(op, " "+OpPin) { - pins++ - } - } - back, _ := rs.Read(r.Instance) - if pins != 3 || len(back.Pinned) != 3 { - t.Fatalf("%d pins written, the record holds %+v", pins, back.Pinned) - } - if len(got) != 4 || !reflect.DeepEqual(got[0], got[1]) || got[0].subject != meshdelivery.SubjectPinned || - !slices.Equal(got[0].pins.Assignment, []int64{9}) || !slices.Equal(got[2].pins.Catalog, []meshdelivery.PinsCatalogItem{{Branch: "main", Revision: 9}}) || - !slices.Equal(got[3].pins.Catalog, []meshdelivery.PinsCatalogItem{{Branch: "feat/x", Revision: 9}}) || got[0].pins.Record != r.Instance { - t.Fatalf("said %+v", got) - } - got = nil - if err := rs.Free(back, HalfAssignment, "", 9, "removed by hand"); err != nil { - t.Fatal(err) - } - if err := rs.Free(back, HalfAssignment, "", 9, "again"); err != nil { - t.Fatal(err) - } - if len(got) != 1 || got[0].subject != meshdelivery.SubjectFreed || got[0].pins.Why != "removed by hand" || - !slices.Equal(got[0].pins.Assignment, []int64{9}) { - t.Fatalf("said %+v", got) - } - got = nil - if err := rs.Free(back, HalfCatalog, "feat/x", 9, "removed"); err != nil { - t.Fatal(err) - } - if len(got) != 1 || !slices.Equal(got[0].pins.Catalog, []meshdelivery.PinsCatalogItem{{Branch: "feat/x", Revision: 9}}) { - t.Fatalf("said %+v", got) - } - if again, _ := rs.Read(r.Instance); len(again.Pinned) != 1 { - t.Fatalf("pinned after the free %+v", again.Pinned) - } - if err := rs.Pin(r, "trunk", "", 1); err == nil { - t.Fatal("a pin of no half is taken") - } - }) - t.Run("the setting record-retention, in days", func(t *testing.T) { dir := t.TempDir() for _, c := range []struct { @@ -386,7 +478,8 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByMilestoneAndHeads(t *testing.T // W11.1: the manifest's ledger types allow exactly the operations the gate applies, and the ledger is capped at 768 MiB. func TestTheManifestsLedgerTypesAreTheRecordsOperations(t *testing.T) { l := newLedgerFake(t) - for name, want := range map[string][]string{TypeRecord: RecordOperations, TypeHeld: HeldOperations, TypeSwitch: SwitchOperations} { + for name, want := range map[string][]string{TypeRecord: RecordOperations, TypeHeld: HeldOperations, TypeMover: MoverOperations, + TypeAct: ActOperations} { var got []string for _, op := range l.types[name].Operations { got = append(got, op.Name) @@ -396,8 +489,14 @@ func TestTheManifestsLedgerTypesAreTheRecordsOperations(t *testing.T) { } } raw, _ := os.ReadFile(filepath.Join("..", "..", "module.json")) - if !strings.Contains(string(raw), `"max-mib": 768`) { - t.Error("the records ledger is not capped at 768 MiB") + if !strings.Contains(string(raw), `"max-mib": 1024`) { + t.Error("the records ledger is not capped at 1 GiB (design 47 H2 §809)") + } + if ix := l.types[TypeMover].Indexes; len(ix) != 1 || ix[0].Name != MoversIndex || !slices.Equal(ix[0].On, []string{"record"}) { + t.Errorf("the type mover's indexes are %+v, not one %s on its record's key", ix, MoversIndex) + } + if ix := l.types[TypeAct].Indexes; len(ix) != 1 || ix[0].Name != ActsIndex || !slices.Equal(ix[0].On, []string{"record"}) { + t.Errorf("the type act's indexes are %+v, not one %s on its record's key (H-A-455 (1))", ix, ActsIndex) } } @@ -410,7 +509,7 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { setup := func(t *testing.T) (*ledgerFake, *Records, *Record, *StepConsumer) { l := newLedgerFake(t) rs := &Records{Ledger: l, Now: func() time.Time { return at }} - r, _, err := rs.Open("47/G", map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)}, false) + r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)})) if err != nil { t.Fatal(err) } @@ -429,15 +528,20 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { } return []StepOutcome{{Module: b.Module, Fingerprint: b.Fingerprint, Step: StepRunning, Outcome: OutcomeRunning, At: at}}, nil }} - c := &StepConsumer{Records: rs, Families: append(slices.Clone(stepFamilies), running), Now: func() time.Time { return at }} + h := &Holder{Records: rs, Now: func() time.Time { return at }} + h.init() + c := &StepConsumer{Records: rs, Families: append(slices.Clone(stepFamilies), running), Now: func() time.Time { return at }, Taken: h.TakenIn} return l, rs, r, c } - taken := func(id string) stdio.Envelope { - body := `{"v":1,"kind":"taken","key":"m.00000000000000000001","what":"revision","merges":[{"repository":"novox/app","number":7,"merge":"` + - merge + `"}],"since":"2026-11-09T20:00:00Z"}` + takenOf := func(id, body string) stdio.Envelope { return stdio.Envelope{Key: "mesh-delivery-indexer.take-in.taken", Body: json.RawMessage(body), Headers: map[string]string{"x-event-id": id}} } - t.Run("a take-in of the record's merge is its outcome, once", func(t *testing.T) { + taken := func(id string) stdio.Envelope { + return takenOf(id, `{"branch":"main","source":47,"revision":47,"call":"000000000000002f","entries":[{"module":"mesh-y",`+ + `"commit":"`+merge+`","fingerprint":"src2:f2","repository":"novox/app"}]}`) + } + // H §738, H-A-29: the take-in's movers are its record's entries, read by the key .; none ends it. + t.Run("a take-in's movers are its record's entries, taken in, once; a take-in with no mover ends it", func(t *testing.T) { l, rs, r, c := setup(t) if err := c.Hear(taken("e1")); err != nil { t.Fatal(err) @@ -447,12 +551,25 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { t.Fatalf("the same event again: %v, %d operations (was %d)", err, len(l.history), n) } back, _ := rs.Read(r.Instance) - if got := back.Outcomes[OutcomeKey("", "", "", "take-in")]; got.Outcome != OutcomeTakenIn || got.Event != "e1" { - t.Fatalf("outcomes %+v", back.Outcomes) + if _, ok := back.Entries[EntryKey("mesh-y", "src2:f2", "")]; !ok { + t.Fatalf("entries %+v", back.Entries) + } + if got := back.Outcomes[OutcomeKey("mesh-y", "src2:f2", "", "take-in")]; got.Outcome != OutcomeTakenIn || back.Ended != nil { + t.Fatalf("outcomes %+v, ended %+v", back.Outcomes, back.Ended) } if c.Heard()["mesh-delivery-indexer.take-in.taken"].Applied != 2 { t.Fatalf("heard %+v", c.Heard()) } + other, _, _ := rs.Open(opening("main", 48, map[string]string{"novox/app@8": merge})) + if err := c.Hear(takenOf("e4", `{"branch":"main","source":48,"revision":48,"call":"0000000000000030"}`)); err != nil { + t.Fatal(err) + } + if back, _ := rs.Read(other.Instance); back.Ended == nil || back.Ended.Why != WhyNothingToDeliver { + t.Fatalf("a take-in with no mover leaves its record %+v", back.Ended) + } + if back, _ := rs.Read(r.Instance); back.Ended != nil { + t.Fatal("another revision's take-in ended this record") + } }) t.Run("a node's event from its own node is the entry's outcome; from another node it is refused", func(t *testing.T) { _, rs, r, c := setup(t) @@ -479,10 +596,10 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { // away that wakes adds its outcomes and is no longer shown away. t.Run("it ends once every present node runs its entries, and a node away that wakes adds its outcomes", func(t *testing.T) { _, rs, r, c := setup(t) - var ended []recordEnded + var ended []meshdelivery.RecordEndedEvent rs.Say = func(subject string, body any, id string) error { if subject == meshdelivery.SubjectRecordEnded && id == "record-ended."+r.Instance { - ended = append(ended, body.(recordEnded)) + ended = append(ended, body.(meshdelivery.RecordEndedEvent)) } return nil } @@ -518,7 +635,7 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { !back.Ended.Away[0].Since.Equal(at.Add(-time.Hour)) { t.Fatalf("ended %+v", back.Ended) } - if len(ended) != 1 || ended[0].Milestone != "47/G" || len(ended[0].Away) != 1 || ended[0].Away[0].Node != "g14" { + if len(ended) != 1 || ended[0].Milestone != recordMilestone("main", 47) || ended[0].Branch != "main" || ended[0].Source != 47 || ended[0].Call != r.Call || len(ended[0].Away) != 1 || ended[0].Away[0].Node != "g14" { t.Fatalf("record-ended said %+v", ended) } if err := c.Hear(running("g14")); err != nil { @@ -542,7 +659,7 @@ func TestTheRecordsOutcomesArriveThroughTheGatesConsumer(t *testing.T) { if h := c.Heard()["mesh-delivery-indexer.take-in.taken"]; h.Refused != 1 { t.Fatalf("heard %+v", h) } - l.failOn = OpOutcome + l.failOn = OpEntry if err := c.Hear(taken("e3")); err == nil { t.Fatal("an outcome the ledger did not take is taken") } @@ -581,7 +698,7 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { var said []string rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }, Say: func(subject string, body any, id string) error { said = append(said, subject+" "+id); return nil }} - r, _, err := rs.Open("47/G", heads, false) + r, _, err := rs.Open(opening("main", 47, heads)) if err != nil { t.Fatal(err) } @@ -596,18 +713,18 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { t.Run("gate_record and gate_records read a record whole and its fill", func(t *testing.T) { rs, r, said := setup(t) // W9.3: the record's opening is said once, under its id, for the watchman to time against 24 hours. - if !slices.Contains(*said, meshdelivery.SubjectRecordOpened+" record-opened."+r.Instance) { + if !slices.Contains(*said, meshdelivery.SubjectRecordOpened(r.Call)+" record-opened."+r.Instance) { t.Fatalf("the record's opening is not said: %v", *said) } got, err := rs.RecordOf(r.Instance, "") - if err != nil || len(got) != 1 || got[0].Record.Milestone != "47/G" || got[0].Waits != "waiting for mesh-x on ace" || - got[0].Bytes == 0 || got[0].Of != 256<<10 { + if err != nil || len(got) != 1 || got[0].Record.Milestone != recordMilestone("main", 47) || got[0].Waits != "waiting for mesh-x on ace" || + got[0].Bytes == 0 || got[0].Of != EntryLimit { t.Fatalf("%+v %v", got, err) } - if byMilestone, err := rs.RecordOf("", "47/G"); err != nil || len(byMilestone) != 1 { + if byMilestone, err := rs.RecordOf("", recordMilestone("main", 47)); err != nil || len(byMilestone) != 1 { t.Fatalf("by milestone %+v %v", byMilestone, err) } - if _, err := rs.RecordOf("", "46/F"); err == nil { + if _, err := rs.RecordOf("", recordMilestone("main", 46)); err == nil { t.Fatal("a milestone with no record answers nothing") } lines, err := rs.Lines() @@ -615,6 +732,69 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { t.Fatalf("%+v %v", lines, err) } }) + // deliveries filters while it reads and pages at 768 KB with capped, total and a cursor (design 47 H2 §811, §779). + t.Run("deliveries by repository over 4 MB of records answers under 768 KB, page by page", func(t *testing.T) { + rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }} + big := make([]string, 400) + for i := range big { + big[i] = strings.Repeat("c", 40) + } + for i := range 300 { + repo := "novox/app" + if i%2 == 1 { + repo = "novox/other" + } + r, _, err := rs.Open(opening("main", int64(i+1), map[string]string{fmt.Sprintf("%s@%d", repo, i): strings.Repeat("1", 40)})) + if err != nil { + t.Fatal(err) + } + if err := rs.SetTrace(r, RecordTrace{Commits: big}); err != nil { + t.Fatal(err) + } + if i == 4 { + if err := rs.AddEntry(r, RecordEntry{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace"}); err != nil { + t.Fatal(err) + } + } + } + h := &Holder{Records: rs, Now: func() time.Time { return at }} + kept, _ := rs.Kept() + raw, _ := json.Marshal(kept) + if whole, _ := h.Deliveries(DeliveriesFilter{All: true}); len(raw) < 4<<20 || !whole["capped"].(bool) || whole["total"].(int) != 300 { + t.Fatalf("the records hold %d bytes in all, total %v", len(raw), whole["total"]) + } + seen, next := map[string]bool{}, "" + for pages := 0; ; pages++ { + page, err := h.Deliveries(DeliveriesFilter{Repository: "novox/app", All: true, Next: next}) + if err != nil { + t.Fatal(err) + } + if raw, _ := json.Marshal(page); len(raw) > 768<<10 || page["total"].(int) != 150 { + t.Fatalf("a page of %d bytes, total %v", len(raw), page["total"]) + } + for _, v := range page["deliveries"].([]recordView) { + if seen[v.Instance] || !holdsRepository(v.Record, "novox/app") { + t.Fatalf("%s answered twice or of another repository", v.Instance) + } + seen[v.Instance] = true + } + if next = page["next"].(string); next == "" || pages > 20 { + break + } + } + if len(seen) != 150 { + t.Errorf("the pages answered %d of 150 records", len(seen)) + } + if m, _ := h.Deliveries(DeliveriesFilter{Module: "mesh-x", All: true}); m["total"].(int) != 1 { + t.Errorf("by module: %v", m["total"]) + } + if s, _ := h.Deliveries(DeliveriesFilter{Since: at.Add(time.Hour), All: true}); s["total"].(int) != 0 { + t.Errorf("since an hour after every opening: %v", s["total"]) + } + if _, err := h.Deliveries(DeliveriesFilter{Next: "not-a-cursor"}); err == nil { + t.Error("a cursor this verb never answered was taken") + } + }) t.Run("gate_record_end ends a record only once the hand-act log took it", func(t *testing.T) { rs, r, said := setup(t) log := &handActsFake{refuse: errors.New("no responders")} @@ -639,6 +819,42 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { t.Fatal("a record ended is ended again") } }) + // Design 47 H, H-A-121: the clean state's all form ends every open record after one hand act, and answers them counted. + t.Run("gate_record_end with all ends every open record once the hand-act log took it, counted", func(t *testing.T) { + rs, r, said := setup(t) + other, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)})) + if err != nil { + t.Fatal(err) + } + log := &handActsFake{refuse: errors.New("no responders")} + if _, err := rs.EndAllByHand("", "jochen@shanks", log); err == nil { + t.Fatal("ended all with no reason") + } + if _, err := rs.EndAllByHand("the clean state", "jochen@shanks", log); err == nil { + t.Fatal("ended all though the hand-act log refused it") + } + for _, inst := range []string{r.Instance, other.Instance} { + if back, _ := rs.Read(inst); back.Ended != nil { + t.Fatalf("%s ended while no hand act was recorded", inst) + } + } + log.refuse = nil + got, err := rs.EndAllByHand("the clean state", "jochen@shanks", log) + if err != nil || got["count"] != 2 || len(got["ended"].([]string)) != 2 || len(log.took) != 1 { + t.Fatalf("%+v %v (log %+v)", got, err, log.took) + } + for _, inst := range []string{r.Instance, other.Instance} { + if back, _ := rs.Read(inst); back.Ended == nil || back.Ended.Why != "the clean state" { + t.Fatalf("%s not ended: %+v", inst, back.Ended) + } + if !slices.Contains(*said, meshdelivery.SubjectRecordEnded+" record-ended."+inst) { + t.Fatalf("%s's end is not said: %v", inst, *said) + } + } + if again, err := rs.EndAllByHand("again", "jochen@shanks", log); err != nil || again["count"] != 0 || len(log.took) != 1 { + t.Fatalf("with none open: %+v %v, log %d", again, err, len(log.took)) + } + }) t.Run("gate_record_repair asks the owners for the outcomes an entry lacks, applies what they answer, and ends the record", func(t *testing.T) { rs, r, said := setup(t) owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"} @@ -725,7 +941,7 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { return nil }} commit := strings.Repeat("2", 40) - r, _, err := rs.Open(recordMilestone("feat/x", 4), map[string]string{"novox/app@222222222222": commit}, false) + r, _, err := rs.Open(opening("feat/x", 4, map[string]string{"novox/app@222222222222": commit})) if err != nil { t.Fatal(err) } @@ -773,31 +989,6 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { }) } -// A-161: record-opened says what its hearers need to tell a forge-made record: the repository, the pull request, the merge -// commit and the branch; an ordinary record says none of them. -func TestRecordOpenedCarriesAForgeMadeRecordsMerge(t *testing.T) { - var said []meshdelivery.RecordOpenedEvent - rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return time.Date(2026, 11, 12, 5, 0, 0, 0, time.UTC) }, - Say: func(subject string, body any, id string) error { - if subject == meshdelivery.SubjectRecordOpened { - said = append(said, body.(meshdelivery.RecordOpenedEvent)) - } - return nil - }} - commit := strings.Repeat("3", 40) - if _, _, err := rs.OpenForgeMade("main.5", map[string]string{"novox/app@333333333333": commit}, - ForgeMerge{Repository: "novox/app", Pull: 12, Commit: commit, Branch: "main"}); err != nil { - t.Fatal(err) - } - if _, _, err := rs.Open("47/G", map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)}, false); err != nil { - t.Fatal(err) - } - if len(said) != 2 || !said[0].ForgeMade || said[0].Repository != "novox/app" || said[0].Pull != 12 || said[0].Commit != commit || - said[0].Branch != "main" || said[1].ForgeMade || said[1].Repository != "" || said[1].Pull != 0 || said[1].Commit != "" || said[1].Branch != "" { - t.Fatalf("said %+v", said) - } -} - // W11.20 (design 47 *The delivery record*: a store filling is said before it is full): the gate reads its ledger's fill, // says filling when a record takes it past 80 % of its cap, refuses the next record as full and holds its merge, and // says room and hands the merge once the ledger is below 80 % again; the read tool says the fill. @@ -814,7 +1005,7 @@ func TestTheRecordsLedgerSaysFillingFullAndRoom(t *testing.T) { } saying := func(out *[]said) SeatSay { return func(subject string, body any, id string) error { - if subject == meshdelivery.SubjectRecordOpened { + if strings.HasPrefix(subject, meshdelivery.SubjectRecordOpened("")) { return nil // the opening of a record, not a fill } f, _ := body.(meshdelivery.Fill) @@ -828,7 +1019,7 @@ func TestTheRecordsLedgerSaysFillingFullAndRoom(t *testing.T) { var events []said rs := &Records{Ledger: l, Now: func() time.Time { return at }, Say: saying(&events)} l.fill = filled(capBytes * 7 / 10) - r, opened, err := rs.Open("47/G", heads, false) + r, opened, err := rs.Open(opening("main", 47, heads)) if err != nil || !opened { t.Fatalf("open below the mark: %v %v", opened, err) } @@ -844,16 +1035,16 @@ func TestTheRecordsLedgerSaysFillingFullAndRoom(t *testing.T) { } // Already past the mark: a next record is opened and says nothing again. events = nil - if _, opened, err := rs.Open("47/H", heads, false); err != nil || !opened || len(events) != 0 { + if _, opened, err := rs.Open(opening("main", 48, heads)); err != nil || !opened || len(events) != 0 { t.Fatalf("a record past the mark: %v %v, said %+v", opened, err, events) } // No room for one more record: refused, said as full naming what it refuses, nothing opened. l.fill = filled(capBytes - RecordRoom/2) n := len(l.history) - if _, opened, err := rs.Open("47/I", heads, false); !errors.Is(err, ErrRecordsFull) || opened || len(l.history) != n { + if _, opened, err := rs.Open(opening("main", 49, heads)); !errors.Is(err, ErrRecordsFull) || opened || len(l.history) != n { t.Fatalf("a full ledger opened %v (%v), %d operations", opened, err, len(l.history)-n) } - if len(events) != 1 || events[0].subject != meshdelivery.SubjectFull || !strings.Contains(events[0].body.Refused, "47/I") { + if len(events) != 1 || events[0].subject != meshdelivery.SubjectFull || !strings.Contains(events[0].body.Refused, recordMilestone("main", 49)) { t.Fatalf("full said as %+v", events) } if line, _ := rs.Lines(); !strings.HasPrefix(fmt.Sprint(line["fill"].(map[string]any)["state"]), "full") { @@ -861,7 +1052,7 @@ func TestTheRecordsLedgerSaysFillingFullAndRoom(t *testing.T) { } // A ledger that says no fill (a runner before the call): the record is opened, and the read tool says why. l.fill = nil - if _, opened, err := rs.Open("47/J", heads, false); err != nil || !opened { + if _, opened, err := rs.Open(opening("main", 50, heads)); err != nil || !opened { t.Fatalf("an unread fill refused the record: %v %v", opened, err) } if line, _ := rs.Lines(); line["fill"].(map[string]any)["unread"] == nil { @@ -885,3 +1076,10 @@ func (o *ownersFake) Running(node, module string) (string, string, error) { o.asked = append(o.asked, "running "+node+" "+module) return o.fp, o.phase, nil } + +// opening is a record's opening for a test: the source revision of a branch, its call made of its number. +func opening(branch string, source int64, heads map[string]string) RecordOpening { + return RecordOpening{Branch: branch, Source: source, Call: fmt.Sprintf("%016x", source), Heads: heads} +} + +func ptrTime(t time.Time) *time.Time { return &t } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index d5a34a740..5d5bc3640 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -1,26 +1,17 @@ package main -// What a delivery record says on the seat `mesh-delivery` (design 47 *The delivery record*): `pinned` and `freed` for the -// graph revisions it starts and stops pointing at, `heads-replaced` for a candidate whose heads were replaced or whose pull -// request closed, and `record-ended` once every present node runs its entries. Only the gate's account publishes them +// What a delivery record says on the seat `mesh-delivery` (design 47 *The delivery record*): `record-ended` once every +// present node runs its entries; the pins are the indexer's (design 47 H §749, H-A-48). Only the gate's account publishes them // (ADR 0363 §2); each is said under an id of what it says, so said again it is kept once, and a say that failed is said // again at the next write of the record. import ( "fmt" "sort" - "strconv" "strings" "time" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - "git.novox.be/novox/mesh-sdk/go/keys" -) - -// The halves of the revision view a record pins (design 47 *Two graphs, one source of truth*). -const ( - HalfCatalog = "catalog" - HalfAssignment = "assignment" ) // StepRunning is the step whose outcome OutcomeRunning says an entry runs healthy on its node: from the node-engine seat's @@ -40,110 +31,6 @@ func (rs *Records) say(subject string, body any, id string) error { return rs.Say(subject, body, id) } -// pinKey is a pinned revision's key in the record: its half, for a catalog revision its watched branch (revisions are numbered -// per branch, A-171) escaped as a name with its slashes escaped too, and its number, so no two revisions' keys meet. -func pinKey(half, branch string, revision int64) string { - key := half + "-" - if half == HalfCatalog { - key += strings.ReplaceAll(keys.EscapeName(branch), "/", "=2f") + "-" - } - return key + strconv.FormatInt(revision, 10) -} - -// number is the revision's number on its half's seat: what follows the key's last dash. -func (p PinnedRevision) number() (int64, bool) { - i := strings.LastIndex(p.Revision, "-") - if i < 0 || !strings.HasPrefix(p.Revision, p.Half+"-") { - return 0, false - } - n, err := strconv.ParseInt(p.Revision[i+1:], 10, 64) - return n, err == nil -} - -// pinsOf is the seat's Pins of a record for these revisions. -func pinsOf(r *Record, pins []PinnedRevision, why string) meshdelivery.Pins { - out := meshdelivery.Pins{Record: r.Instance, Milestone: r.Milestone, Why: why} - for _, p := range pins { - n, ok := p.number() - if !ok { - continue - } - switch p.Half { - case HalfCatalog: - out.Catalog = append(out.Catalog, meshdelivery.PinsCatalogItem{Branch: p.Branch, Revision: n}) - case HalfAssignment: - out.Assignment = append(out.Assignment, n) - } - } - return out -} - -func checkHalf(half string) error { - if half != HalfCatalog && half != HalfAssignment { - return fmt.Errorf("a record pins a catalog or an assignment graph revision, not a %q one", half) - } - return nil -} - -// Pin writes that the record points at a graph revision, unless it does already, and says `pinned` (again, when written -// before: the id keeps it once). A catalog revision names its watched branch, which the record keeps and the event says. -func (rs *Records) Pin(r *Record, half, branch string, revision int64) error { - if err := checkHalf(half); err != nil { - return err - } - if half == HalfCatalog && branch == "" { - return fmt.Errorf("a catalog revision is pinned by its watched branch and its number") - } - if half != HalfCatalog { - branch = "" - } - p := PinnedRevision{Revision: pinKey(half, branch, revision), Half: half, Branch: branch} - if _, ok := r.Pinned[p.Revision]; !ok { - seq, err := rs.Ledger.Apply(r.Instance, OpPin, p) - if err != nil { - return err - } - if r.Pinned == nil { - r.Pinned = map[string]PinnedRevision{} - } - r.Pinned[p.Revision], r.Sequence = p, seq - } - return rs.say(meshdelivery.SubjectPinned, pinsOf(r, []PinnedRevision{p}, ""), "pinned."+r.Instance+"."+p.Revision) -} - -// Free writes that the record no longer points at a graph revision and says `freed` with why; a revision it does not -// point at frees nothing and says nothing. -func (rs *Records) Free(r *Record, half, branch string, revision int64, why string) error { - if err := checkHalf(half); err != nil { - return err - } - p, ok := r.Pinned[pinKey(half, branch, revision)] - if !ok { - return nil - } - if err := rs.say(meshdelivery.SubjectFreed, pinsOf(r, []PinnedRevision{p}, why), "freed."+r.Instance+"."+p.Revision); err != nil { - return err - } - seq, err := rs.Ledger.Apply(r.Instance, OpFree, map[string]any{"revision": p.Revision}) - if err != nil { - return err - } - delete(r.Pinned, p.Revision) - r.Sequence = seq - return nil -} - -// sayFreedAll says `freed` for every revision a record pins, before the record is removed: said first, so a removal never -// leaves a revision pinned by nobody that the indexer or the assigner still keeps. -func (rs *Records) sayFreedAll(r *Record, why string) error { - pins := sortedPins(r) - if len(pins) == 0 { - return nil - } - return rs.say(meshdelivery.SubjectFreed, pinsOf(r, pins, why), "freed."+r.Instance) -} - -// NodeAway writes a node away since when, unless the record holds it already, and ends the record when every other node // runs its entries: a node away holds nothing (ADR 0603 §7). func (rs *Records) NodeAway(r *Record, node string, since time.Time) error { if node == "" { @@ -151,7 +38,9 @@ func (rs *Records) NodeAway(r *Record, node string, since time.Time) error { } if _, ok := r.Away[node]; !ok { a := NodeAway{Node: node, Since: since.UTC()} - seq, err := rs.Ledger.Apply(r.Instance, OpAway, a) + next := *r + next.Away = withEntry(r.Away, node, a) + seq, err := rs.write(r, r.Instance, OpAway, a, next.head()) if err != nil { return err } @@ -169,7 +58,14 @@ func (rs *Records) NodeBack(r *Record, node string) error { if _, ok := r.Away[node]; !ok { return nil } - seq, err := rs.Ledger.Apply(r.Instance, OpBack, map[string]any{"node": node}) + next := *r + next.Away = map[string]NodeAway{} + for n, a := range r.Away { + if n != node { + next.Away[n] = a + } + } + seq, err := rs.write(r, r.Instance, OpBack, map[string]any{"node": node}, next.head()) if err != nil { return err } @@ -245,53 +141,46 @@ func (rs *Records) End(r *Record, why, by string) error { func (rs *Records) end(r *Record, why, by string) error { e := RecordEnded{At: rs.now(), Why: why, By: by, Away: awayList(r)} - seq, err := rs.Ledger.Apply(r.Instance, OpEnd, map[string]any{"ended": e}) + body := map[string]any{"ended": e} + var took time.Duration + var class string + if why == WhyAllRun { + // Every mover runs: the record keeps its delivery time and class (design 47 H2 §810). + if took, class = timesAtEnd(r); took > 0 { + body["delivery-time"], body["class"] = took.String(), class + } + } + next := *r + next.Ended = &e + if took > 0 { + next.DeliveryTime, next.Class = took.String(), class + } + seq, err := rs.write(r, r.Instance, OpEnd, body, next.head()) if err != nil { return err } r.Ended, r.Sequence = &e, seq + if took > 0 { + r.DeliveryTime, r.Class = took.String(), class + } rs.keep(r) if rs.Changed != nil { rs.Changed(r, RecordChange{What: "ended", Why: why, Ended: true}) } + // The end clears record-too-large of every entry of the record, the acts its end owed among them (§809, H-A-455 (3)). + rs.clearTooLarge(r) return nil } -// recordEnded is the seat's `record-ended` body. -type recordEnded struct { - Record string `json:"record"` - Milestone string `json:"milestone"` - ForgeMade bool `json:"forge-made,omitempty"` - Away []NodeAway `json:"away,omitempty"` - At time.Time `json:"at"` -} - func (rs *Records) sayEnded(r *Record) error { if r.Ended == nil { return nil } - return rs.say(meshdelivery.SubjectRecordEnded, recordEnded{Record: r.Instance, Milestone: r.Milestone, - ForgeMade: r.ForgeMade, Away: r.Ended.Away, At: r.Ended.At}, "record-ended."+r.Instance) -} - -// StatePins says `pinned` again for every revision each record it keeps pins, then once `pins-stated` (design 47 G §579): the -// indexer's consumer of the seat's events hears pins said before it existed or older than the stream keeps, and the set form -// absorbs the repeats. Each repeat has an id of its own, since the bus keeps one message under one id inside its duplicate window. -func (rs *Records) StatePins() (int, error) { - kept, err := rs.Kept() - if err != nil { - return 0, err + at := r.Ended.At + e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at} + for _, a := range r.Ended.Away { + since := a.Since + e.Away = append(e.Away, meshdelivery.RecordEndedEventAwayItem{Node: a.Node, Since: &since}) } - at := rs.Now().UTC() - stated := 0 - for _, r := range kept { - for _, p := range sortedPins(r) { - id := "pinned." + r.Instance + "." + p.Revision + ".stated." + strconv.FormatInt(at.UnixNano(), 10) - if err := rs.say(meshdelivery.SubjectPinned, pinsOf(r, []PinnedRevision{p}, ""), id); err != nil { - return stated, err - } - stated++ - } - } - return stated, rs.say(meshdelivery.SubjectPinsStated, meshdelivery.PinsStatedEvent{At: at}, "pins-stated."+strconv.FormatInt(at.UnixNano(), 10)) + return rs.say(meshdelivery.SubjectRecordEnded, e, "record-ended."+r.Instance) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go new file mode 100644 index 000000000..aec852ae0 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go @@ -0,0 +1,317 @@ +package main + +// A delivery record follows its pipeline to the machines (design 47 H §738; G §141 to §147; H-A-29, H-A-75, H-A-89). +// The record a merge call opened (§737), read by its key `.`, takes the runner's `pipeline-started` and +// `pipeline-ended` of its source revision and of the pipelines a package's publish starts from it (§747), the runner's +// `wait-held` and `wait-ended`, the assigner's `wanted` and `pipeline-wanted`, and the node-engine seat's `running` +// (consumer.go), on the gate's own durable consumer: +// +// - `pipeline-started`: each mover is an entry (module, fingerprint, no node); +// - `pipeline-ended`: each mover's step result is one outcome of its entry, its step the result's step, its outcome the +// result's own word, its why the result's (H-A-89 (1)); a pipeline that did not pass ends the record failed, naming +// the pipeline's why (H-A-89 (3)); +// - `wait-held`: the waiting step's outcome is held, with what it waits on; `wait-ended` writes over it the wait's how +// (H-A-89 (2)); +// - `wanted`: each want is an entry (module, fingerprint, node) with the outcome wanted, and the trace's from and to are +// the lowest and the highest assignment graph revision of the record's wants; a removed want writes nothing +// (H-A-89 (5)); +// - `running`: a healthy running is the running-healthy outcome of every entry it is (consumer.go apply), and ends +// nothing (H-A-89 (4)); +// - `pipeline-wanted`: `running` ends the record, every tier's movers running on every present placing machine; +// `tier-late` ends it failed, naming the movers and machines not running (H-A-75, H-A-89 (4); §751). +// +// A pipeline of a run on request delivers nothing, so its events write nothing. An event of a source revision with no +// record (a seed's or a start's, H-A-47), or of a record ended, writes nothing; each write is safe to repeat. + +import ( + "bytes" + "encoding/json" + "fmt" + "sort" + "strconv" + "strings" + "time" + + nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" + wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" +) + +// WhyFailed opens the why of a record that ended failed (H-A-89 (3), (4)). +const WhyFailed = "failed: " + +// strictly reads an event's body in its owner's form, refusing a field it does not know. +func strictly(body json.RawMessage, into any) error { + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + return dec.Decode(into) +} + +func decodePipelineStarted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var p runner.PipelineStartedEvent + if err := strictly(body, &p); err != nil { + return nil, err + } + return nil, namesSource(p.Branch, p.Source, p.Run) +} + +func decodePipelineEnded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var p runner.PipelineEndedEvent + if err := strictly(body, &p); err != nil { + return nil, err + } + return nil, namesSource(p.Branch, p.Source, p.Run) +} + +func decodeWait(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var w runner.WaitHeldEvent + if err := strictly(body, &w); err != nil { + return nil, err + } + if w.Step == "" { + return nil, fmt.Errorf("a wait names no step") + } + return nil, namesSource(w.Branch, w.Source, w.Run) +} + +func decodeWanted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var w wants.WantedEvent + if err := strictly(body, &w); err != nil { + return nil, err + } + if w.Module == "" || w.Node == "" { + return nil, fmt.Errorf("a wanted names no module or node") + } + return nil, nil +} + +func decodePipelineWanted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + var p wants.PipelineWantedEvent + if err := strictly(body, &p); err != nil { + return nil, err + } + if p.Outcome != wants.PipelineWantedOutcomeRunning && p.Outcome != wants.PipelineWantedOutcomeTierLate { + return nil, fmt.Errorf("a pipeline-wanted says the outcome %q", p.Outcome) + } + return nil, namesSource(p.Branch, p.Source, "") +} + +// decodeRunning is a healthy running's outcome, running-healthy, of the entry it is on its node (the subject's, which the +// consumer checks against the node it came from); a running unhealthy or stopped writes nothing. +func decodeRunning(body json.RawMessage, at time.Time) ([]StepOutcome, error) { + var r nodeengine.RunningEvent + if err := strictly(body, &r); err != nil { + return nil, err + } + if r.Module == "" { + return nil, fmt.Errorf("a running names no module") + } + if r.Stopped || r.Fingerprint == "" || r.Healthy != nil && !*r.Healthy { + return nil, nil + } + return []StepOutcome{{Module: r.Module, Fingerprint: r.Fingerprint, Step: StepRunning, + Outcome: OutcomeRunning, At: at}}, nil +} + +// namesSource refuses an event of a pipeline that names no branch or source revision, unless it is a run on request's. +func namesSource(branch string, source int64, run string) error { + if run == "" && (branch == "" || source < 1) { + return fmt.Errorf("it names no branch or source revision") + } + return nil +} + +// Follow writes one event of the record's pipeline families into the record of its source revision. Called with an +// event its family decoded; an error only when the record could not be read or written, so the event is offered again. +func (h *Holder) Follow(event string, body json.RawMessage) error { + if h.Records == nil { + return nil + } + switch event { + case runner.EventPipelineStarted: + var p runner.PipelineStartedEvent + if err := json.Unmarshal(body, &p); err != nil || p.Run != "" { + return nil + } + return h.pipelineStarted(p) + case runner.EventPipelineEnded: + var p runner.PipelineEndedEvent + if err := json.Unmarshal(body, &p); err != nil || p.Run != "" { + return nil + } + return h.pipelineEnded(p) + case runner.EventWaitHeld, runner.EventWaitEnded: + var w runner.WaitHeldEvent + if err := json.Unmarshal(body, &w); err != nil || w.Run != "" { + return nil + } + return h.wait(w, event == runner.EventWaitEnded) + case wants.EventWanted: + var w wants.WantedEvent + if err := json.Unmarshal(body, &w); err != nil || w.Removed || w.Pipeline == "" { + return nil + } + return h.wantWritten(w) + case wants.EventPipelineWanted: + var p wants.PipelineWantedEvent + if err := json.Unmarshal(body, &p); err != nil { + return nil + } + return h.pipelineWanted(p) + } + return nil +} + +// openRecord is the record of a source revision while it is open, or nil. +func (h *Holder) openRecord(branch string, source int64) (*Record, error) { + r, err := h.Records.ByKey(branch, source) + if err != nil { + return nil, fmt.Errorf("the record of %s at %d cannot be read: %w", branch, source, err) + } + if r == nil || r.Ended != nil { + return nil, nil + } + return r, nil +} + +func (h *Holder) pipelineStarted(p runner.PipelineStartedEvent) error { + r, err := h.openRecord(p.Branch, p.Source) + if err != nil || r == nil { + return err + } + for _, m := range p.Movers { + if m.Module == "" { + continue + } + if err := h.Records.AddEntry(r, RecordEntry{Module: m.Module, Fingerprint: m.Fingerprint}); err != nil { + return err + } + if err := h.Records.SetMover(r, m.Module, m.Fingerprint, p.Pipeline, m.Version); err != nil { + return err + } + } + return nil +} + +func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error { + r, err := h.openRecord(p.Branch, p.Source) + if err != nil || r == nil { + return err + } + at := h.Now().UTC() + if p.Ended != nil { + at = p.Ended.UTC() + } + for _, m := range p.Movers { + if m.Module == "" { + continue + } + if err := h.Records.AddEntry(r, RecordEntry{Module: m.Module, Fingerprint: m.Fingerprint}); err != nil { + return err + } + if err := h.Records.SetMover(r, m.Module, m.Fingerprint, p.Pipeline, m.Version); err != nil { + return err + } + for _, s := range m.Steps { + if s.Step == "" || s.Outcome == "" { + continue + } + when := at + if s.Ended != nil { + when = s.Ended.UTC() + } + if _, err := h.Records.Outcome(r, RecordOutcome{Module: m.Module, Fingerprint: m.Fingerprint, Step: s.Step, + Outcome: s.Outcome, Why: s.Why, At: when}); err != nil { + return err + } + } + } + if err := h.Records.SetPhases(r, p.Phases); err != nil { + return err + } + if p.Outcome == runner.PipelineEndedOutcomePassed { + return nil + } + why := strings.TrimSpace(p.Why) + if why == "" { + why = "the pipeline " + p.Pipeline + " ended " + p.Outcome + } + return h.Records.End(r, WhyFailed+why, "") +} + +func (h *Holder) wait(w runner.WaitHeldEvent, ended bool) error { + r, err := h.openRecord(w.Branch, w.Source) + if err != nil || r == nil { + return err + } + o := RecordOutcome{Module: w.Module, Fingerprint: w.Fingerprint, Step: w.Step, Outcome: OutcomeHeld, Why: w.On, + At: w.Since.UTC()} + if w.Who != "" { + o.Why += " (" + w.Who + ")" + } + if ended { + if w.How == "" { + h.logf("[mesh-delivery] a wait-ended of %s says no how, so the record %s keeps its wait", w.Pipeline, r.Instance) + return nil + } + o.Outcome, o.At = w.How, h.Now().UTC() + } + _, err = h.Records.Outcome(r, o) + return err +} + +func (h *Holder) wantWritten(w wants.WantedEvent) error { + milestone, _, _ := strings.Cut(w.Pipeline, ".published.") + r, err := h.Records.ByMilestone(milestone) + if err != nil { + return fmt.Errorf("the record of the pipeline %s cannot be read: %w", w.Pipeline, err) + } + if r == nil || r.Ended != nil { + return nil + } + if err := h.Records.AddEntry(r, RecordEntry{Module: w.Module, Fingerprint: w.Fp, Node: w.Node}); err != nil { + return err + } + at := h.Now().UTC() + if w.At != nil { + at = w.At.UTC() + } + if _, err := h.Records.Outcome(r, RecordOutcome{Module: w.Module, Fingerprint: w.Fp, Node: w.Node, Step: StepWanted, + Outcome: OutcomeWanted, At: at}); err != nil { + return err + } + var t RecordTrace + if r.Trace != nil { + t = *r.Trace + } + rev := strconv.FormatInt(w.Revision, 10) + if from, err := strconv.ParseInt(t.From, 10, 64); err != nil || w.Revision < from { + t.From = rev + } + if to, err := strconv.ParseInt(t.To, 10, 64); err != nil || w.Revision > to { + t.To = rev + } + return h.Records.SetTrace(r, t) +} + +func (h *Holder) pipelineWanted(p wants.PipelineWantedEvent) error { + r, err := h.openRecord(p.Branch, p.Source) + if err != nil || r == nil { + return err + } + if p.Outcome == wants.PipelineWantedOutcomeRunning { + return h.Records.End(r, WhyAllRun, "") + } + var late []string + for _, n := range p.NotRunning { + machines := append([]string(nil), n.Machines...) + sort.Strings(machines) + late = append(late, n.Module+" on "+strings.Join(machines, ", ")) + } + sort.Strings(late) + why := "a tier is late" + if len(late) > 0 { + why += ": not running " + strings.Join(late, "; ") + } + return h.Records.End(r, WhyFailed+why, "") +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go new file mode 100644 index 000000000..89d4e6b71 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go @@ -0,0 +1,248 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/catalogue" +) + +// pipelineBed is a gate with one record open, of main at source revision 1, and its consumer. +func pipelineBed(t *testing.T) (*Holder, *StepConsumer, *Record, *[]string) { + t.Helper() + now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + var ended []string + h := &Holder{Now: func() time.Time { return now }} + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now, Say: func(subject string, body any, id string) error { + if strings.Contains(subject, ".record-ended") { + ended = append(ended, id) + } + return nil + }} + if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { + t.Fatal(err) + } + if _, err := h.Records.Kept(); err != nil { // the records as the gate keeps them, read once + t.Fatal(err) + } + r, err := h.Records.ByKey("main", 1) + if err != nil || r == nil { + t.Fatalf("the record is %v (%v)", r, err) + } + c := &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} + return h, c, r, &ended +} + +func hear(t *testing.T, c *StepConsumer, key, node, body string) { + t.Helper() + if !c.Takes(key) { + t.Fatalf("the consumer takes no %s", key) + } + if err := c.Hear(stdio.Envelope{Key: key, Node: node, Body: json.RawMessage(body)}); err != nil { + t.Fatalf("%s: %v", key, err) + } +} + +// GATE-5/AC (design 47 H §738, H-A-89): the record follows its pipeline to the machines: pipeline-started's movers are +// entries, a wait is held then ended with its how, pipeline-ended's step results are outcomes, each want is an entry with +// wanted and moves the trace's from and to, a healthy running is running-healthy and ends nothing, and pipeline-wanted +// running ends the record; a run on request's events and a removed want write nothing. +func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) { + h, c, r, ended := pipelineBed(t) + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`) + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","run":"r1","movers":[{"module":"other","commit":"c","fingerprint":"g","repository":"novox/o","tier":1}]}`) + if _, ok := r.Entries[EntryKey("app", "f", "")]; !ok || len(r.Entries) != 1 { + t.Fatalf("entries %v: the mover is one, a run's none", r.Entries) + } + hear(t, c, "mesh-pipeline-runner.wait-held.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","module":"app","fingerprint":"f","step":"approval","on":"person","who":"the operator","since":"2026-11-20T03:01:00Z"}`) + held := r.Outcomes[OutcomeKey("app", "f", "", "approval")] + if held.Outcome != OutcomeHeld || held.Why != "person (the operator)" { + t.Fatalf("the wait is %+v", held) + } + hear(t, c, "mesh-pipeline-runner.wait-ended.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","module":"app","fingerprint":"f","step":"approval","on":"person","how":"answered","since":"2026-11-20T03:01:00Z"}`) + if o := r.Outcomes[OutcomeKey("app", "f", "", "approval")]; o.Outcome != "answered" { + t.Fatalf("the wait ended as %+v", o) + } + hear(t, c, "mesh-pipeline-runner.pipeline-ended.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"passed","movers":[{"module":"app","fingerprint":"f","tier":1,"steps":[{"step":"build","status":"required","outcome":"passed"},{"step":"review","status":"optional","outcome":"nothing to run","why":"no reviewer"}]}]}`) + if o := r.Outcomes[OutcomeKey("app", "f", "", "review")]; o.Outcome != "nothing to run" || o.Why != "no reviewer" || + r.Outcomes[OutcomeKey("app", "f", "", "build")].Outcome != "passed" || r.Ended != nil { + t.Fatalf("the steps are %+v and the record ended %+v", r.Outcomes, r.Ended) + } + for _, w := range []string{ + `{"v":1,"node":"ace","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12}`, + `{"v":1,"node":"g14","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":11}`, + `{"v":1,"node":"novox","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":30,"removed":true}`, + } { + hear(t, c, "mesh-wants.wanted.x.app", "", w) + } + if r.Trace == nil || r.Trace.From != "11" || r.Trace.To != "12" { + t.Fatalf("the trace is %+v: from 11 to 12, a removed want moves nothing", r.Trace) + } + if o := r.Outcomes[OutcomeKey("app", "f", "ace", StepWanted)]; o.Outcome != OutcomeWanted { + t.Fatalf("the want on ace is %+v", o) + } + if _, ok := r.Entries[EntryKey("app", "f", "novox")]; ok { + t.Fatal("a removed want is an entry") + } + hear(t, c, "node-engine.running.ace.app", "ace", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"ace","fingerprint":"f","healthy":true}`) + hear(t, c, "node-engine.running.g14.app", "g14", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"g14","fingerprint":"f","healthy":true}`) + if o := r.Outcomes[OutcomeKey("app", "f", "g14", StepRunning)]; o.Outcome != OutcomeRunning || r.Ended != nil || len(*ended) != 0 { + t.Fatalf("running is %+v and the record ended %+v: running ends nothing", o, r.Ended) + } + hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`) + if r.Ended == nil || r.Ended.Why != WhyAllRun || len(*ended) != 1 { + t.Fatalf("the record ended %+v, said %v", r.Ended, *ended) + } + if got, _ := h.Records.ByKey("main", 1); got != r { + t.Fatal("the record read by its key is not the one the gate keeps") + } +} + +// hookedLedger is the ledger fake, told after each operation it took. +type hookedLedger struct { + *ledgerFake + after func(instance, operation string, body any) +} + +func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, error) { + seq, err := l.ledgerFake.Apply(instance, operation, body) + if err == nil && l.after != nil { + l.after(instance, operation, body) + } + return seq, err +} + +// 721/AC1 (issue 721 note 11; design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so +// one can be heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits +// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it +// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer +// taken before the next event writes the record. +func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { + running := func(node string) stdio.Envelope { + return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage( + `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"` + node + `","fingerprint":"f","healthy":true}`)} + } + for _, tc := range []struct { + name string + heard func(h *Holder) (any, error) + check func(t *testing.T, h *Holder, answer any) + }{ + {"pipeline-wanted", func(h *Holder) (any, error) { + return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage( + `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)}) + }, func(t *testing.T, h *Holder, _ any) { + r, err := h.Records.ByKey("main", 1) + if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q (%v); want 5m0s and core", r.Ended, + r.DeliveryTime, r.Class, err) + } + }}, + {"the call show", func(h *Holder) (any, error) { + for _, tool := range tools(h, &listening{}) { + if tool.Name == Seat+".show" { + return tool.Run(map[string]any{"id": "main.1"}) + } + } + return nil, fmt.Errorf("the gate serves no %s.show", Seat) + }, func(t *testing.T, h *Holder, answer any) { + if err := take(h, running("g14")); err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(answer) + if !strings.Contains(string(raw), OutcomeKey("app", "f", "ace", StepRunning)) || strings.Contains(string(raw), "g14") { + t.Fatalf("show answered %.600s: want the running on ace, and nothing the next event wrote", raw) + } + // Every call runs under the lock the events take. + if _, err := h.applied(func(map[string]any) (any, error) { + if h.applying.TryLock() { + h.applying.Unlock() + return nil, errors.New("a call runs while an event can write the records") + } + return nil, nil + })(nil); err != nil { + t.Fatal(err) + } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + h := &Holder{Now: func() time.Time { return now }} + ledger := &hookedLedger{ledgerFake: newLedgerFake(t)} + h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }} + h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} + if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { + t.Fatal(err) + } + if _, err := h.Records.Kept(); err != nil { + t.Fatal(err) + } + if err := take(h, stdio.Envelope{Key: "mesh-pipeline-runner.pipeline-started.main.1", Body: json.RawMessage( + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`)}); err != nil { + t.Fatal(err) + } + now = now.Add(5 * time.Minute) + type heardOut struct { + answer any + err error + } + heard := make(chan heardOut, 1) + ledger.after = func(_, operation string, body any) { + if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning { + return + } + ledger.after = nil + // Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's + // goroutines allow, else on a goroutine of its own, as the runtime hands it. + hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} } + if h.applying.TryLock() { + h.applying.Unlock() + hear() + return + } + go hear() + } + if err := take(h, running("ace")); err != nil { + t.Fatal(err) + } + out := <-heard + if out.err != nil { + t.Fatal(out.err) + } + tc.check(t, h, out.answer) + }) + } +} + +// GATE-5/AC (design 47 H §738, §751; H-A-75, H-A-89 (3), (4)): a pipeline-ended not passed ends the record failed naming +// the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running. +func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) { + for _, tc := range []struct{ name, key, body, why string }{ + {"pipeline failed", "mesh-pipeline-runner.pipeline-ended.main.1", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"failed","why":"build failed","movers":[{"module":"app","fingerprint":"f","tier":1,"steps":[{"step":"build","status":"required","outcome":"failed"}]}]}`, + "failed: build failed"}, + {"pipeline cancelled, no why", "mesh-pipeline-runner.pipeline-ended.main.1", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"cancelled","movers":[]}`, + "failed: the pipeline main.1 ended cancelled"}, + {"tier late", "mesh-wants.pipeline-wanted.main.1", + `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"tier-late","not-running":[{"module":"app","machines":["g14","ace"]}]}`, + "failed: a tier is late: not running app on ace, g14"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, c, r, ended := pipelineBed(t) + hear(t, c, tc.key, "", tc.body) + if r.Ended == nil || r.Ended.Why != tc.why || len(*ended) != 1 { + t.Fatalf("the record ended %+v, said %v; want %q", r.Ended, *ended, tc.why) + } + }) + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go index a0077a8a7..c8ab68e22 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go @@ -15,12 +15,9 @@ import ( stdio "git.novox.be/novox/mesh-sdk/go" ) -// valueLimit is the bus's limit of one value, which a record's state is held under (design 47: a record of 30 modules on -// four nodes is about 30 KiB of it). -const valueLimit = 256 << 10 - -// recordView is one record as gate_record answers it: its state, the sequence of its last operation, its size against -// the value limit, and while open why it has not ended. +// recordView is one record as gate_record answers it, joined from its head entry and its movers' entries (design 47 H2 +// §809): its state, the sequence of its head's last operation, its head entry's size against the 64 KiB an entry holds, +// and while open why it has not ended. type recordView struct { Instance string `json:"instance"` Sequence uint64 `json:"sequence"` @@ -31,8 +28,8 @@ type recordView struct { } func viewOf(r *Record) recordView { - raw, _ := json.Marshal(r) - v := recordView{Instance: r.Instance, Sequence: r.Sequence, Bytes: len(raw), Of: valueLimit, Record: r} + raw, _ := json.Marshal(r.head()) + v := recordView{Instance: r.Instance, Sequence: r.Sequence, Bytes: len(raw), Of: EntryLimit, Record: r} if r.Ended == nil { v.Waits = allRun(r) } @@ -76,11 +73,10 @@ type recordLine struct { Milestone string `json:"milestone"` Opened string `json:"opened"` Ended string `json:"ended,omitempty"` - ForgeMade bool `json:"forge-made,omitempty"` + Call string `json:"call,omitempty"` Entries int `json:"entries"` Outcomes int `json:"outcomes"` Away int `json:"away,omitempty"` - Pinned int `json:"pinned,omitempty"` Bytes int `json:"bytes"` Of int `json:"of-bytes"` Waits string `json:"waits,omitempty"` @@ -96,8 +92,8 @@ func (rs *Records) Lines() (map[string]any, error) { open := 0 for _, r := range list { v := viewOf(r) - l := recordLine{Instance: r.Instance, Milestone: r.Milestone, Opened: timeText(&r.Opened), ForgeMade: r.ForgeMade, - Entries: len(r.Entries), Outcomes: len(r.Outcomes), Away: len(r.Away), Pinned: len(r.Pinned), Bytes: v.Bytes, + l := recordLine{Instance: r.Instance, Milestone: r.Milestone, Opened: timeText(&r.Opened), Call: r.Call, + Entries: len(r.Entries), Outcomes: len(r.Outcomes), Away: len(r.Away), Bytes: v.Bytes, Of: v.Of, Waits: v.Waits} if r.Ended != nil { l.Ended = timeText(&r.Ended.At) + ": " + r.Ended.Why @@ -140,6 +136,44 @@ func (rs *Records) EndByHand(instance, why, by string, acts handActs) (recordVie return viewOf(r), nil } +// EndAllByHand ends every open record by hand, with the reason (design 47 H, H-A-121: the clean state's `all` form), +// recorded in the hand-act log first as one act naming how many: nothing is ended when the log did not take it. It answers +// what it ended, counted; a record that could not be ended stops it, said with what was ended before it. +func (rs *Records) EndAllByHand(why, by string, acts handActs) (map[string]any, error) { + if strings.TrimSpace(why) == "" { + return nil, errors.New("say why every open record is ended by hand, such as the clean state") + } + list, err := rs.List() + if err != nil { + return nil, err + } + var open []*Record + for _, r := range list { + if r.Ended == nil { + open = append(open, r) + } + } + ended := []string{} + if len(open) == 0 { + return map[string]any{"ended": ended, "count": 0}, nil + } + if acts == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was ended") + } + if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("ended every open delivery record by hand (%d)", len(open)), + Why: why, Cause: "gate_record_end", Verb: "record-end"}); err != nil { + return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was ended: %w", err) + } + for _, r := range open { + if err := rs.End(r, why, by); err != nil { + return map[string]any{"ended": ended, "count": len(ended)}, fmt.Errorf("the record %s was not ended, after %d were: %w", r.Instance, len(ended), err) + } + rs.keep(r) + ended = append(ended, r.Instance) + } + return map[string]any{"ended": ended, "count": len(ended)}, nil +} + // handActs records an act in the hand-act log (meshhandactsclient.Recorder). type handActs interface { Record(q meshhandactsclient.Request) (meshhandactsclient.Taken, error) @@ -161,6 +195,17 @@ func recordTools(h *Holder, acts handActs) []stdio.Tool { } return h.Records.RecordOf(strArg(a, "instance"), strArg(a, "milestone")) }}, + {Name: "gate_times", + Description: "Delivery times against their budgets (design 47 H2 §810; ADR 0282 §6): for the classes core and leaf, the " + + "budget (the settings budget-core and budget-leaf), the last seven days' median and worst delivery time from " + + "merge-called to the last running of its movers, every delivery over its budget, newest first, with its longest phase, " + + "and the newest delivery (last) with whether it was over.", + Run: func(map[string]any) (any, error) { + if h.Records == nil { + return none() + } + return h.Times() + }}, {Name: "gate_records", Description: "Every delivery record kept, oldest first: its milestone, when it opened and ended, its entries, " + "outcomes, nodes away and pins, its size against the bus's value limit, and while open what it waits for; and " + @@ -197,14 +242,26 @@ func recordTools(h *Holder, acts handActs) []stdio.Tool { }}, {Name: "gate_record_end", Description: "End a delivery record left open by hand (a node gone for good, an entry that never runs), with the " + - "reason; recorded in the hand-act log of the seat mesh-hand-acts first, and said as record-ended.", + "reason; or, with all, every open record (the clean state), answering what it ended, counted. Recorded in the " + + "hand-act log of the seat mesh-hand-acts first, and each said as record-ended.", Input: map[string]any{"type": "object", "properties": map[string]any{ - "instance": str("the record's instance"), "why": str("why it is ended by hand, in plain words")}, - "required": []string{"instance", "why"}}, + "instance": str("the record's instance; or give all"), + "all": map[string]any{"type": "boolean", "description": "end every open record instead of one"}, + "why": str("why it is ended by hand, in plain words")}, + "required": []string{"why"}}, Run: func(a map[string]any) (any, error) { if h.Records == nil { return none() } + all, _ := a["all"].(bool) + switch instance := strArg(a, "instance"); { + case all && instance != "": + return nil, errors.New("give an instance or all, not both") + case all: + return h.Records.EndAllByHand(strArg(a, "why"), stdio.CallerOf(a), acts) + case instance == "": + return nil, errors.New("give the record's instance, or all for every open record") + } return h.Records.EndByHand(strArg(a, "instance"), strArg(a, "why"), stdio.CallerOf(a), acts) }}, } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recovery.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recovery.go index 3259ce5a1..a6a931398 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recovery.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recovery.go @@ -31,7 +31,9 @@ func (rs *Records) Recovery(repository, commit, why, by string) (meshdelivery.Re if r.Recovery != nil && *r.Recovery == want { return meshdelivery.RecoveryAnswer{By: by, Commit: head, Recovery: true, Repository: repository}, nil } - seq, err := rs.Ledger.Apply(r.Instance, OpTrace, map[string]any{"recovery": want}) + next := *r + next.Recovery = &want + seq, err := rs.write(r, r.Instance, OpTrace, map[string]any{"recovery": want}, next.head()) if err != nil { return meshdelivery.RecoveryAnswer{}, err } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/seed.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/seed.go new file mode 100644 index 000000000..7681a11a9 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/seed.go @@ -0,0 +1,98 @@ +package main + +// The clean state seeds every watched branch's first source revision (design 47 H §768; H-A-15, H-A-76; ADR 0682 §12): +// gate_source_seed, with why, written in the hand-act log first, writes for every watched branch the registrations name +// one source revision at each registered repository's current head, read through the seat git's verb branch, with start +// true and a call of its own, and says source-moved; it opens no record (H-A-47). It numbers from 1, the source bucket +// dropped before it, and refuses to run while a key of the earlier form (or any key it cannot read) is held, naming it. + +import ( + "errors" + "fmt" + "sort" + "strings" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" +) + +// SourceSeed is the tool gate_source_seed: it answers the branches and the repositories it wrote, counted, and those left +// out because their head could not be read. +func (h *Holder) SourceSeed(why, by string, acts handActs) (map[string]any, error) { + if strings.TrimSpace(why) == "" { + return nil, errors.New("say why the sources are seeded") + } + if h.Source == nil || h.Catalog == nil || h.Forge == nil { + return nil, errors.New("this gate keeps no source, reads no registrations or reads no forge") + } + if acts == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was seeded") + } + h.startMu.Lock() + defer h.startMu.Unlock() + regs, err := h.Catalog.Registrations() + if err != nil { + return nil, fmt.Errorf("%w: %w", errRegistrationsUnread, err) + } + watched := watchedRepositories(regs.Registrations) + branches := make([]string, 0, len(watched)) + for b := range watched { + branches = append(branches, b) + } + sort.Strings(branches) + var unreadable []string + for _, b := range branches { + if _, _, err := h.Source.Read(b); err != nil { + unreadable = append(unreadable, fmt.Sprintf("source.%s (%v)", b, err)) + } + } + if len(unreadable) > 0 { + return nil, fmt.Errorf("nothing was seeded: a key of the earlier form is held, drop the source bucket first (§765): %s", + strings.Join(unreadable, "; ")) + } + at := h.Now().UTC() + if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("seeded the first source revision of every watched branch "+ + "(seed by %s at %s)", by, at.Format("2006-01-02T15:04:05Z")), Why: why, Cause: "gate_source_seed", Verb: "source-seed"}); err != nil { + return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was seeded: %w", err) + } + var written, leftOut []string + repositories := 0 + var errs []error + for _, branch := range branches { + var heads []revisionHead + for _, repository := range watched[branch] { + a, err := h.Forge.Branch(repository, branch) + if err == nil && a.Error != "" { + err = errors.New(a.Error) + } + if err == nil && a.Head == "" { + err = errors.New("the forge named no head") + } + if err != nil { + leftOut = append(leftOut, repository+"@"+branch) + h.logf("[mesh-delivery] the seed of source.%s leaves out %s: its head cannot be read (%v)", branch, repository, err) + continue + } + heads = append(heads, revisionHead{Repository: repository, Commit: a.Head}) + } + if len(heads) == 0 { + continue + } + call, err := newCall() + if err != nil { + errs = append(errs, err) + continue + } + named, _, err := h.nameRevision(branch, call, heads) + if err != nil { + errs = append(errs, err) + continue + } + if err := h.saySourceMoved(branch, named, true, heads); err != nil { + errs = append(errs, fmt.Errorf("source.%s is seeded at %d and its source-moved is not said: %w", branch, named.Source, err)) + } + written = append(written, branch) + repositories += len(heads) + } + return map[string]any{"branches": len(written), "repositories": repositories, "written": written, "left-out": leftOut, + "by": by}, errors.Join(errs...) +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go index 289049ce0..becf0c8f7 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go @@ -17,8 +17,14 @@ type Settings struct { // RecordRetentionDays is how many days a delivery record is kept from when it opened (design 47 *The delivery // record*); nil keeps DefaultRecordRetention. RecordRetentionDays *int `json:"record-retention"` + // UntakenBoundMinutes is how many minutes a head may stand untaken before head-untaken is raised (design 47 H §740); nil + // keeps DefaultUntakenBound. + UntakenBoundMinutes *int `json:"untaken-bound"` } +// DefaultUntakenBound is untaken-bound when the setting gives none (§740). +const DefaultUntakenBound = 10 * time.Minute + // readSettings reads the settings file; a value that is not a whole number of days, from 1 to 3650, is refused. func readSettings(path string) (Settings, error) { var s Settings @@ -44,6 +50,17 @@ func readSettings(path string) (Settings, error) { default: return Settings{}, errors.New("record-retention is not a number") } + switch v := loose["untaken-bound"].(type) { + case nil: + case float64: + n := int(v) + if v < 1 || v != float64(n) { + return Settings{}, errors.New("untaken-bound is not a whole number of minutes, at least 1") + } + s.UntakenBoundMinutes = &n + default: + return Settings{}, errors.New("untaken-bound is not a number") + } return s, nil } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow.go deleted file mode 100644 index 6fef43a91..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow.go +++ /dev/null @@ -1,278 +0,0 @@ -package main - -// The gate's source of a watched branch follows every merge into that branch, whoever made it (design 47 G A-464, A-464b, amending -// A-463): on the forge bridge's `merged` of a repository the source names, at the branch the source watches, the gate moves that -// repository's head to the merge and says source-moved, as a take-in moves it; at its start it compares each head with the -// forge's branch head, asked of the seat git, and moves every one behind it the same way, so a merge whose message was lost is -// followed too; gate_source_follow does the same for one repository now. A head the source does not name, or a branch it does -// not watch, is left: only a start or a registration change adds them (sourcestart.go). - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "sort" - "strconv" - "strings" - "time" - - "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" - "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" - "git.novox.be/novox/mesh-sdk/go/keys" -) - -// forgeMergedEvent is the forge bridge's merged message of any repository, as the manifest consumes it. -var forgeMergedEvent = declared("forge.*.*.merged") - -// moveHead moves the head the branch's source names for repository to head, and says source-moved with the key's revision. It -// answers false, and writes nothing, when the branch has no source key, the key does not name the repository or names the head -// already. group is the group that made the merge, empty for a merge no group of the gate made. -func (h *Holder) moveHead(branch, repository, head, group string) (moved bool, err error) { - if h.Source == nil || head == "" { - return false, nil - } - held, _, err := h.Source.Read(branch) - if err != nil || held == nil { - return false, err - } - name := "" - for r := range held.Heads { - if trunk.SameRepository(r, repository) { - name = r - } - } - if name == "" || held.Heads[name] == head { - return false, nil // not named, or no change: no revision and no source-moved (A-464c) - } - was := held.Heads[name] - // Only forward (A-464c): the head held must be contained in the merge, asked of the seat git. - if h.Forge == nil { - return false, errors.New("this gate reads no forge, so it cannot tell whether the merge is ahead of the head") - } - ahead, err := h.Forge.Contains(name, was, head) - if err != nil { - return false, fmt.Errorf("whether %.12s is in %.12s of %s cannot be read, so the head stays: %w", was, head, name, err) - } - if !ahead { - h.logf("[mesh-delivery] source.%s keeps %s at %.12s: the merge %.12s does not contain it (heard again, late or out of order), left without effect", branch, name, was, head) - return false, nil - } - rev, err := h.Source.Set(branch, func(prev *Source) (Source, bool) { - moved = false - if prev == nil || prev.Heads[name] != was { - return Source{}, false // another writer moved it first - } - next := Source{Group: group, Heads: map[string]string{}} - for r, c := range prev.Heads { - next.Heads[r] = c - } - next.Heads[name] = head - moved = true - return next, true - }) - if err != nil { - return false, fmt.Errorf("source.%s cannot be moved: %w", branch, err) - } - if !moved || h.SaySeat == nil { - return moved, nil - } - at := h.Now().UTC() - return true, h.SaySeat(seat.SubjectSourceMoved(keys.EscapeName(branch)), - seat.SourceMovedEvent{Branch: branch, Group: group, Revision: int64(rev), At: &at}, - "source-moved."+keys.EscapeName(branch)+"."+strconv.FormatUint(rev, 10)) -} - -// ForgeMerged takes one merged message of the forge bridge: the head of its repository in the source of the branch it landed on -// moves to the merge. A merge no delivery group made (the message names no group) is said so. A message that cannot be read, or -// names no branch or merge, is said and taken: heard again it would be refused again. -func (h *Holder) ForgeMerged(body json.RawMessage) error { - f, err := forgemsg.DecodeForge(body) - if err != nil { - h.logf("[mesh-delivery] a merged message of the forge bridge is not readable, the source does not follow it: %v", err) - return nil - } - if f.Kind != forgemsg.ForgeMerged { - return nil - } - if f.Base == "" || f.Merge == "" { - h.logf("[mesh-delivery] the merged message of %s names no branch or no merge, the source does not follow it", f.Repository) - return nil - } - moved, err := h.moveHead(f.Base, f.Repository, f.Merge, f.Group) - if err != nil { - return err - } - if moved { - if f.Group == "" { // A-464b: a merge whose message names no delivery group is one the gate did not make - h.logf("[mesh-delivery] source.%s follows the merge %.12s of %s: not made by a delivery group of the gate", f.Base, f.Merge, f.Repository) - } else { - h.logf("[mesh-delivery] source.%s follows the merge %.12s of %s, made by the delivery group %s", f.Base, f.Merge, f.Repository, f.Group) - } - } - return nil -} - -// SourceUncompared is the finding of a start comparison that left a head uncompared (A-464e). -const SourceUncompared = "source-uncompared" - -// FollowAtStart compares each head of every source key with the forge's head of that branch and moves every one behind it, at -// each start. It ends only when every head was compared (A-464e): a head the forge could not be asked for (the seat git not -// answering yet, as when its bundle starts in the same tool runner) is compared again after a growing pause of at most a -// minute, and the finding source-uncompared names the repositories and the last error while any stands. It answers the heads -// moved as "@". -func (h *Holder) FollowAtStart() ([]string, error) { - if h.Source == nil || h.Forge == nil { - return nil, errors.New("this gate keeps no source or reads no forge") - } - var moved []string - var only map[string]bool - for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { - got, left := h.followPass(only) - moved = append(moved, got...) - if len(left) == 0 { - h.clearUncompared() - h.logf("[mesh-delivery] the sources compared with the forge's heads at the start: moved %v", moved) - return moved, nil - } - only = map[string]bool{} - var names []string - var last error - for n, err := range left { - only[n] = true - names = append(names, n) - last = err - } - sort.Strings(names) - h.sayUncompared(names, last) - h.logf("[mesh-delivery] %d heads are not compared with the forge's yet (%s; last: %v); asking again in %s", len(names), strings.Join(names, ", "), last, wait) - startSleep(wait) - } -} - -// followPass compares the heads named in only (every head when nil) once; it answers the heads moved and, by "@", -// each head it could not compare with why. A source it cannot list or read is one entry named for itself. -func (h *Holder) followPass(only map[string]bool) (moved []string, left map[string]error) { - left = map[string]error{} - branches, err := h.Source.Branches() - if err != nil { - left["the branches of the source"] = err - return nil, left - } - for _, branch := range branches { - held, _, err := h.Source.Read(branch) - if err != nil { - left["source."+branch] = err - continue - } - if held == nil { - continue - } - for repository, head := range held.Heads { - name := repository + "@" + branch - if only != nil && !only[name] { - continue - } - ok, err := h.followForge(branch, repository, head) - if err != nil { - left[name] = err - continue - } - if ok { - moved = append(moved, name) - } - } - } - return moved, left -} - -func (h *Holder) sayUncompared(names []string, last error) { - if h.Findings == nil { - return - } - at := h.Now().UTC() - err := h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: SourceUncompared, Kind: SourceUncompared, - Subject: meshconditions.Subject{Scope: FindingScope, ID: SourceUncompared}, - Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", - Summary: fmt.Sprintf("the gate's source is not compared with the forge's head for %s; the last error: %v", strings.Join(names, ", "), last), - Headline: "The gate's source is not compared with the forge", - Explanation: "At its start the gate compares each head of its source with the forge's head of the branch. A head it could not compare is asked again after a growing pause, and this clears once every head is compared.", - Needs: "the seat git answering; gate_source_follow moves one repository's head by hand.", - Source: SourceUncompared, Observer: Module, At: at, Since: at}) - if err != nil { - h.logf("[mesh-delivery] the finding %s is not written: %v", SourceUncompared, err) - } -} - -func (h *Holder) clearUncompared() { - if h.Findings == nil { - return - } - for _, f := range h.Findings.Held() { - if f.Scope == FindingScope && f.ID == SourceUncompared && f.Kind == SourceUncompared { - if err := h.Findings.Clear(context.Background(), FindingScope, SourceUncompared, SourceUncompared, "every head is compared with the forge's"); err != nil { - h.logf("[mesh-delivery] the finding %s is not cleared: %v", SourceUncompared, err) - } - } - } -} - -// followForge moves one repository's head in a branch's source to the forge's head of the branch when they differ. -func (h *Holder) followForge(branch, repository, held string) (bool, error) { - a, err := h.Forge.Branch(repository, branch) - if err == nil && a.Error != "" { - err = errors.New(a.Error) - } - if err == nil && a.Head == "" { - err = errors.New("the forge named no head") - } - if err != nil { - return false, err - } - if sameCommit(held, a.Head) && len(held) == len(a.Head) { - return false, nil - } - moved, err := h.moveHead(branch, repository, a.Head, "") - if moved { - h.logf("[mesh-delivery] source.%s follows the forge: %s from %.12s to %.12s", branch, repository, held, a.Head) - } - return moved, err -} - -// SourceFollow moves one repository's head to the forge's head of the branch by hand, after the hand-act log took it. -func (h *Holder) SourceFollow(branch, repository, why, by string, acts handActs) (map[string]any, error) { - if strings.TrimSpace(branch) == "" || strings.TrimSpace(repository) == "" || strings.TrimSpace(why) == "" { - return nil, errors.New("say the branch, the repository and why its head follows the forge") - } - if h.Source == nil || h.Forge == nil { - return nil, errors.New("this gate keeps no source or reads no forge") - } - if acts == nil { - return nil, errors.New("the hand-act log cannot be reached here, so nothing was moved") - } - held, _, err := h.Source.Read(branch) - if err != nil { - return nil, err - } - if held == nil { - return nil, fmt.Errorf("the gate keeps no source of the branch %s", branch) - } - name := "" - for r := range held.Heads { - if trunk.SameRepository(r, repository) { - name = r - } - } - if name == "" { - return nil, fmt.Errorf("the source of %s names no head of %s", branch, repository) - } - if _, err := acts.Record(meshhandactsclient.Request{What: "moved the head of " + repository + " in the source of the branch " + branch + " to the forge's head", - Why: why, Cause: "gate_source_follow", Verb: "source-follow"}); err != nil { - return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was moved: %w", err) - } - moved, err := h.followForge(branch, name, held.Heads[name]) - return map[string]any{"branch": branch, "repository": name, "moved": moved, "by": by}, err -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow_test.go deleted file mode 100644 index 214564098..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcefollow_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "errors" - "strings" - "testing" - "time" - - "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" - meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" - stdio "git.novox.be/novox/mesh-sdk/go" -) - -// Design 47 G A-464, A-464b: the forge bridge's merged message moves the head of its repository in the source of the branch it -// landed on and says source-moved; a merge naming no delivery group is said not made by one; a branch no source key holds, a -// repository the key does not name, and a head the key holds already move nothing. -func TestAMergedMessageMovesTheSourceOfItsBranchWhoeverMadeTheMerge(t *testing.T) { - old, merge := strings.Repeat("a", 40), strings.Repeat("b", 40) - body := func(repository, base, group string) []byte { - f := forgemsg.Forge{V: 1, Kind: forgemsg.ForgeMerged, Repository: repository, Base: base, Merge: merge, Head: merge, Number: 14, Root: strings.Repeat("d", 40)} - data, err := forgemsg.EncodeForge(f) - if err != nil { - t.Fatal(err) - } - return data - } - for _, c := range []struct { - name, repository, base string - moved bool - }{ - {"watched branch, named repository", "novox/mesh-contracts", "main", true}, - {"a branch no source key holds", "novox/mesh-contracts", "other", false}, - {"a repository the key does not name", "novox/other", "main", false}, - } { - t.Run(c.name, func(t *testing.T) { - src := &memSource{vals: map[string]Source{"main": {Group: "g", Heads: map[string]string{"novox/mesh-contracts": old}}}} - var said []string - var logged []string - h := &Holder{Now: time.Now, Source: src, Forge: &fakeForge{}, - Logf: func(f string, a ...any) { logged = append(logged, f) }, - SaySeat: func(subject string, _ any, id string) error { said = append(said, id); return nil }} - if err := h.ForgeMerged(body(c.repository, c.base, "")); err != nil { - t.Fatal(err) - } - got := src.vals["main"] - if c.moved != (got.Heads["novox/mesh-contracts"] == merge) || c.moved != (len(said) == 1) || (c.moved && got.Group != "") { - t.Fatalf("source %+v said %v: moved wanted %v", got, said, c.moved) - } - if c.moved && !strings.Contains(strings.Join(logged, "\n"), "not made by a delivery group of the gate") { - t.Errorf("a merge no group made is not said so: %v", logged) - } - // Heard again, the key names the head already: nothing is moved or said twice. - if err := h.ForgeMerged(body(c.repository, c.base, "")); err != nil || len(said) > 1 { - t.Errorf("heard twice: %v, said %v", err, said) - } - }) - } -} - -// Design 47 G A-464: at its start the gate compares each head with the forge's branch head and moves every one behind it; a head -// the forge cannot read is said and left; gate_source_follow does it for one repository after the hand-act log took it. -func TestTheStartAndTheToolMoveAHeadBehindTheForge(t *testing.T) { - old, now := strings.Repeat("a", 40), strings.Repeat("c", 40) - mk := func() (*Holder, *branchSource, *[]string) { - src := &branchSource{memSource{vals: map[string]Source{"main": {Heads: map[string]string{"o/f1": old, "o/f2": old, "o/f3": now}}}}} - var said []string - return &Holder{Now: time.Now, Source: src, Logf: func(string, ...any) {}, - Forge: &fakeForge{heads: map[string]string{"o/f1@main": now, "o/f3@main": now}}, // o/f2 cannot be read - SaySeat: func(_ string, _ any, id string) error { said = append(said, id); return nil }}, src, &said - } - h, src, said := mk() - fw := &fakeFindings{} - h.Findings = fw - forge := h.Forge.(*fakeForge) - var pauses []time.Duration - var heldWhileWaiting int - prevSleep := startSleep - startSleep = func(d time.Duration) { - pauses = append(pauses, d) - heldWhileWaiting = len(fw.held) // the finding stands while a head is uncompared - forge.heads["o/f2@main"] = now // the seat git answers by the second pass - } - defer func() { startSleep = prevSleep }() - moved, err := h.FollowAtStart() - if err != nil || len(moved) != 2 || src.vals["main"].Heads["o/f1"] != now || src.vals["main"].Heads["o/f2"] != now || len(*said) != 2 { - t.Fatalf("start: moved %v err %v heads %v said %v: want o/f1 and, after the second pass, o/f2 moved", moved, err, src.vals["main"].Heads, *said) - } - if len(pauses) != 1 || heldWhileWaiting != 1 || len(fw.held) != 0 { - t.Fatalf("pauses %v, finding held while waiting %d and after %d: want one pause, the finding raised while a head stood uncompared and cleared after", pauses, heldWhileWaiting, len(fw.held)) - } - h, src, said = mk() - acts := &handActsFake{refuse: errors.New("log down")} - if _, err := h.SourceFollow("main", "o/f1", "missed a merge", "me", acts); err == nil || src.vals["main"].Heads["o/f1"] != old { - t.Fatalf("moved without the log: %v", err) - } - acts.refuse = nil - if _, err := h.SourceFollow("main", "o/f1", "", "me", acts); err == nil { - t.Fatal("moved with no reason") - } - out, err := h.SourceFollow("main", "o/f1", "missed a merge", "me", acts) - if err != nil || out["moved"] != true || len(acts.took) != 1 || acts.took[0].Cause != "gate_source_follow" || src.vals["main"].Heads["o/f1"] != now { - t.Fatalf("tool: %v %v log %+v heads %v", out, err, acts.took, src.vals["main"].Heads) - } -} - -// Design 47 G A-464: the gate takes the forge bridge's merged event of any repository, by the manifest's own pattern. -func TestTheGateTakesTheForgeBridgesMergedEventOfAnyRepository(t *testing.T) { - merge := strings.Repeat("b", 40) - data, err := forgemsg.EncodeForge(forgemsg.Forge{V: 1, Kind: forgemsg.ForgeMerged, Repository: "novox/mesh-contracts", Base: "main", Merge: merge, Head: merge, Number: 14, Root: strings.Repeat("d", 40)}) - if err != nil { - t.Fatal(err) - } - src := &memSource{vals: map[string]Source{"main": {Heads: map[string]string{"novox/mesh-contracts": strings.Repeat("a", 40)}}}} - h := &Holder{Now: time.Now, Source: src, Forge: &fakeForge{}, Logf: func(string, ...any) {}} - key := strings.Replace(strings.Replace(forgeMergedEvent, "*", "novox", 1), "*", "mesh-contracts", 1) - if err := take(h, stdio.Envelope{Key: key, Body: data}); err != nil || src.vals["main"].Heads["novox/mesh-contracts"] != merge { - t.Fatalf("event %q: %v, source %+v", key, err, src.vals["main"]) - } -} - -// Design 47 G A-464c: a head moves only forward and only when it changes. A merged message for a commit that does not contain -// the held head (replayed, late, out of order) moves nothing and is said; a second message for the same head writes no -// revision; and a take-in.taken for a head a merged already moved writes none and says no source-moved. -func TestAHeadMovesOnlyForwardAndOnlyWhenItChanges(t *testing.T) { - oldC, newC := strings.Repeat("a", 40), strings.Repeat("b", 40) - msg := func(merge string) []byte { - data, err := forgemsg.EncodeForge(forgemsg.Forge{V: 1, Kind: forgemsg.ForgeMerged, Repository: "novox/app", Base: "main", Merge: merge, Head: merge, Number: 3, Root: strings.Repeat("d", 40)}) - if err != nil { - t.Fatal(err) - } - return data - } - src := &memSource{vals: map[string]Source{"main": {Heads: map[string]string{"novox/app": newC}}}} - var said, logged []string - // newC contains oldC, not the other way round. - forge := &fakeForge{contains: func(commit, in string) bool { return commit == in || (commit == oldC && in == newC) }} - h := &Holder{Now: time.Now, Source: src, Forge: forge, Logf: func(f string, a ...any) { logged = append(logged, f) }, - SaySeat: func(_ string, _ any, id string) error { said = append(said, id); return nil }} - if err := h.ForgeMerged(msg(oldC)); err != nil || src.vals["main"].Heads["novox/app"] != newC || src.rev != 0 || len(said) != 0 || len(logged) == 0 { - t.Fatalf("a replayed old merge: %v, source %+v, revisions %d, said %v, logged %v: want nothing moved and a log line", err, src.vals["main"], src.rev, said, logged) - } - if err := h.ForgeMerged(msg(newC)); err != nil || src.rev != 0 || len(said) != 0 { - t.Fatalf("a second message for the same head wrote revision %d, said %v", src.rev, said) - } - // A take-in.taken naming the head a merged moved already writes no revision and says nothing. - body := []byte(`{"v":1,"kind":"taken","key":"g.feat","what":"group","group":"feat","branch":"main","source":7,` + - `"merges":[{"repository":"novox/app","number":3,"merge":"` + newC + `"}],"entries":[]}`) - if err := h.moveSource(mustTaken(t, body)); err != nil || src.rev != 0 || len(said) != 0 { - t.Fatalf("take-in for a head already moved: %v, revision %d, said %v", err, src.rev, said) - } - // A real forward move still writes one revision. - src.vals["main"] = Source{Heads: map[string]string{"novox/app": oldC}} - if err := h.ForgeMerged(msg(newC)); err != nil || src.rev != 1 || len(said) != 1 { - t.Fatalf("a forward move: %v, revision %d, said %v", err, src.rev, said) - } -} - -func mustTaken(t *testing.T, body []byte) meshcatalog.TakeInTaken { - t.Helper() - var v meshcatalog.TakeInTaken - if err := json.Unmarshal(body, &v); err != nil { - t.Fatal(err) - } - return v -} - -// Design 47 G A-464d: a take-in.taken arriving after a later merge moved the head leaves the head where it is. -func TestATakeInTakenAfterALaterMergeLeavesTheHead(t *testing.T) { - oldC, newC := strings.Repeat("a", 40), strings.Repeat("b", 40) - src := &memSource{vals: map[string]Source{"main": {Heads: map[string]string{"novox/app": newC}}}} - var said []string - h := &Holder{Now: time.Now, Source: src, Logf: func(string, ...any) {}, - Forge: &fakeForge{contains: func(commit, in string) bool { return commit == in || (commit == oldC && in == newC) }}, - SaySeat: func(_ string, _ any, id string) error { said = append(said, id); return nil }} - body := []byte(`{"v":1,"kind":"taken","key":"g.feat","what":"group","group":"feat","branch":"main","source":7,` + - `"merges":[{"repository":"novox/app","number":3,"merge":"` + oldC + `"}],"entries":[]}`) - if err := h.moveSource(mustTaken(t, body)); err != nil || src.vals["main"].Heads["novox/app"] != newC || src.rev != 0 || len(said) != 0 { - t.Fatalf("take-in of an older merge: %v, source %+v, revision %d, said %v: want the head left at the later merge", err, src.vals["main"], src.rev, said) - } -} - -// fakeFindings is the gate's finding writer in memory. -type fakeFindings struct{ held []meshconditions.Finding } - -func (f *fakeFindings) Write(_ context.Context, x meshconditions.Finding) error { - f.held = append(f.held, x) - return nil -} -func (f *fakeFindings) Clear(_ context.Context, _, _, _, _ string) error { f.held = nil; return nil } -func (f *fakeFindings) Held() []meshconditions.Finding { return f.held } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcestart.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcestart.go index 20341b06c..a2d44dcc9 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcestart.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcestart.go @@ -11,15 +11,12 @@ import ( "errors" "fmt" "sort" - "strconv" "strings" "time" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - "git.novox.be/novox/mesh-sdk/go/keys" ) // registrationChangedEvent is the seat mesh-catalog's event, as the gate's manifest consumes it. @@ -33,40 +30,90 @@ type Registered interface { // seatCatalog reads the seat mesh-catalog through the tool runner. type seatCatalog struct{ ask asking } -func (s seatCatalog) Registrations() (meshcatalog.RegistrationsAnswer, error) { - var a meshcatalog.RegistrationsAnswer - raw, err := s.ask("seat:"+meshcatalog.Seat+"."+meshcatalog.VerbRegistrations, meshcatalog.RegistrationsInput{}) +// Class is the class of the module at fingerprint, as its catalog entry's manifest says it (design 47 H2 §810; +// H-A-394 (2)): the seat mesh-catalog's entry; a manifest with no class is a leaf. +func (s seatCatalog) Class(fingerprint string) (string, error) { + raw, err := s.ask("seat:"+meshcatalog.Seat+"."+meshcatalog.VerbEntry, meshcatalog.EntryInput{Fingerprint: fingerprint}) if err != nil { - return a, err + return "", err } answer, said, ok := answerOf(raw) if !ok { - return a, fmt.Errorf("registrations refused: %s", lastLine(said)) + return "", fmt.Errorf("entry refused: %s", lastLine(said)) + } + var a struct { + Entry struct { + Manifest struct { + Class string `json:"class"` + } `json:"manifest"` + } `json:"entry"` } if err := json.Unmarshal(answer, &a); err != nil { - return a, fmt.Errorf("the answer of registrations is not readable: %w", err) + return "", fmt.Errorf("the answer of entry is not readable: %w", err) + } + return a.Entry.Manifest.Class, nil +} + +// Registrations reads every registration, a module's and a source-only one alike (design 47 H2 §815), page by page from +// the cursor each page answers (§779, §806), so a registration past the first 768 KB is watched too. +func (s seatCatalog) Registrations() (meshcatalog.RegistrationsAnswer, error) { + var all meshcatalog.RegistrationsAnswer + seen := map[string]bool{} + for next := ""; ; { + var a meshcatalog.RegistrationsAnswer + raw, err := s.ask("seat:"+meshcatalog.Seat+"."+meshcatalog.VerbRegistrations, meshcatalog.RegistrationsInput{Next: next}) + if err != nil { + return all, err + } + answer, said, ok := answerOf(raw) + if !ok { + return all, fmt.Errorf("registrations refused: %s", lastLine(said)) + } + if err := json.Unmarshal(answer, &a); err != nil { + return all, fmt.Errorf("the answer of registrations is not readable: %w", err) + } + all.Registrations = append(all.Registrations, a.Registrations...) + if a.Next == "" { + return all, nil + } + if seen[a.Next] { + return all, fmt.Errorf("registrations answered the cursor %q twice: its pages do not end", a.Next) + } + seen[a.Next], next = true, a.Next } - return a, nil } // Branch is the seat git's verb branch: a repository's branch head. +// ForgeReads is what the gate reads of the seat git. +type ForgeReads interface { + // Branch is a repository branch's head (the seat git's verb branch). + Branch(repository, branch string) (gitseat.BranchAnswer, error) +} + +// seatGit reads the seat git through the tool runner. +type seatGit struct{ ask asking } + +func (s seatGit) call(verb string, in any, out any) error { + raw, err := s.ask("seat:"+gitseat.Seat+"."+verb, in) + if err != nil { + return err + } + answer, said, ok := answerOf(raw) + if !ok { + return fmt.Errorf("%s refused: %s", verb, lastLine(said)) + } + if err := json.Unmarshal(answer, out); err != nil { + return fmt.Errorf("the answer of %s is not readable: %w", verb, err) + } + return nil +} + func (s seatGit) Branch(repository, branch string) (gitseat.BranchAnswer, error) { var a gitseat.BranchAnswer return a, s.call(gitseat.VerbBranch, gitseat.BranchInput{Repository: repository, Branch: branch}, &a) } // Contains is whether commit is the commit in or an ancestor of it. -func (s seatGit) Contains(repository, commit, in string) (bool, error) { - var a gitseat.ContainsAnswer - if err := s.call(gitseat.VerbContains, gitseat.ContainsInput{Repository: repository, Commit: commit, In: in}, &a); err != nil { - return false, err - } - if a.Error != "" { - return false, errors.New(a.Error) - } - return a.Contains, nil -} - // watchedRepositories are the repositories each watched branch is registered for, each once, sorted. func watchedRepositories(regs []meshcatalog.Registration) map[string][]string { seen := map[string]map[string]bool{} @@ -159,7 +206,7 @@ func (h *Holder) startSources(only string) (started, leftOut []string, err error for _, repository := range watched[branch] { if held != nil { if _, has := held.Heads[repository]; has { - continue // a head a key holds moves by a take-in alone (A-34) + continue // a head a key holds moves by a merge call alone (§737) } } a, err := h.Forge.Branch(repository, branch) @@ -179,24 +226,18 @@ func (h *Holder) startSources(only string) (started, leftOut []string, err error if len(heads) == 0 { continue } - wrote := false - rev, err := h.Source.Set(branch, func(prev *Source) (Source, bool) { - next := Source{Heads: map[string]string{}} - if prev != nil { - next.Group = prev.Group - for r, c := range prev.Heads { - next.Heads[r] = c - } + var moved []revisionHead + for _, repository := range watched[branch] { + if c, ok := heads[repository]; ok { + moved = append(moved, revisionHead{Repository: repository, Commit: c}) } - wrote = false - for r, c := range heads { - if _, has := next.Heads[r]; !has { // a held head is never changed - next.Heads[r] = c - wrote = true - } - } - return next, wrote - }) + } + call, err := newCall() + if err != nil { + errs = append(errs, err) + continue + } + named, wrote, err := h.nameRevision(branch, call, moved) if err != nil { errs = append(errs, fmt.Errorf("source.%s cannot be started: %w", branch, err)) continue @@ -205,13 +246,8 @@ func (h *Holder) startSources(only string) (started, leftOut []string, err error continue } started = append(started, branch) - if h.SaySeat == nil { - continue - } - at := h.Now().UTC() - if err := h.SaySeat(seat.SubjectSourceMoved(keys.EscapeName(branch)), - seat.SourceMovedEvent{Branch: branch, Revision: int64(rev), At: &at}, - "source-moved."+keys.EscapeName(branch)+"."+strconv.FormatUint(rev, 10)); err != nil { + // start is true only for a branch's first revision (§737, §768). + if err := h.saySourceMoved(branch, named, held == nil, moved); err != nil { errs = append(errs, err) } } @@ -242,7 +278,7 @@ func (h *Holder) SourceStart(branch, why, by string, acts handActs) (map[string] started, leftOut, err := h.startSources(branch) out := map[string]any{"branch": branch, "started": started, "left-out": leftOut, "by": by} if err == nil && len(started) == 0 && len(leftOut) == 0 { - out["note"] = "the key names every registered repository already: only a take-in moves a head" + out["note"] = "the key names every registered repository already: only a merge call moves a head" } return out, err } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools.go index b756d4271..726b3e416 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools.go @@ -7,6 +7,7 @@ package main import ( "errors" "fmt" + "sort" "strconv" "strings" @@ -39,7 +40,7 @@ func (h *Holder) SourceAgain(branch, why, by string, acts handActs) (map[string] if h.Source == nil || h.SaySeat == nil { return nil, errors.New("this gate keeps no source or says no events") } - held, rev, err := h.Source.Read(branch) + held, _, err := h.Source.Read(branch) if err != nil { return nil, err } @@ -54,13 +55,16 @@ func (h *Holder) SourceAgain(branch, why, by string, acts handActs) (map[string] return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was said: %w", err) } at := h.Now().UTC() - escaped := keys.EscapeName(branch) - id := "source-moved." + escaped + "." + strconv.FormatUint(rev, 10) + ".again." + strconv.FormatInt(at.UnixNano(), 10) - if err := h.SaySeat(seat.SubjectSourceMoved(escaped), - seat.SourceMovedEvent{Branch: branch, Group: held.Group, Revision: int64(rev), At: &at}, id); err != nil { + escaped, number := keys.EscapeName(branch), strconv.FormatInt(held.Source, 10) + id := "source-moved." + escaped + "." + number + ".again." + strconv.FormatInt(at.UnixNano(), 10) + e := seat.SourceMovedEvent{V: 1, Branch: branch, Source: held.Source, Call: held.Call, Heads: []seat.SourceMovedEventHeadsItem{}} + for _, r := range sortedKeys(held.Heads) { + e.Heads = append(e.Heads, seat.SourceMovedEventHeadsItem{Repository: r, Commit: held.Heads[r]}) + } + if err := h.SaySeat(seat.SubjectSourceMoved(escaped, number), e, id); err != nil { return nil, err } - return map[string]any{"said": "source-moved", "branch": branch, "revision": rev, "by": by}, nil + return map[string]any{"said": "source-moved", "branch": branch, "source": held.Source, "call": held.Call, "by": by}, nil } // sourceTools are the source's tools; acts is the hand-act log. @@ -68,7 +72,7 @@ func sourceTools(h *Holder, acts handActs) []stdio.Tool { return []stdio.Tool{ {Name: "gate_source", Description: "Every branch's source revision the gate keeps, each whole: its repositories with their trunk branch and head, " + - "the group that moved it last and the key's revision. Read, never written.", + "the merge call that moved it last and its source revision. Read, never written.", Run: func(map[string]any) (any, error) { return h.SourceAll(), nil }}, {Name: "gate_source_again", Description: "Say source-moved again for one branch, with the revision its source key holds now, for a part that missed it; " + @@ -79,9 +83,17 @@ func sourceTools(h *Holder, acts handActs) []stdio.Tool { Run: func(a map[string]any) (any, error) { return h.SourceAgain(strArg(a, "branch"), strArg(a, "why"), stdio.CallerOf(a), acts) }}, + {Name: "gate_source_seed", + Description: "Seed every watched branch's first source revision at the clean state (design 47 H §768): for every watched " + + "branch the registrations name, one source revision at each registered repository's current head read from the forge, " + + "start true, then source-moved; no record. Recorded in the hand-act log of the seat mesh-hand-acts first. It refuses " + + "to run while a source key of the earlier form is held, naming it. Answers the branches and repositories written, counted.", + Input: map[string]any{"type": "object", "properties": map[string]any{"why": str("why the sources are seeded, in plain words")}, + "required": []string{"why"}}, + Run: func(a map[string]any) (any, error) { return h.SourceSeed(strArg(a, "why"), stdio.CallerOf(a), acts) }}, {Name: "gate_source_start", Description: "Start the source of one watched branch the registrations name and no source key holds yet, from the forge: each " + - "registered repository at the branch's head, the group empty, then source-moved; recorded in the hand-act log of the seat " + + "registered repository at the branch's head, one source revision with a call of its own, then source-moved; recorded in the hand-act log of the seat " + "mesh-hand-acts first. A key the gate holds is never rewritten.", Input: map[string]any{"type": "object", "properties": map[string]any{ "branch": str("the watched branch"), "why": str("why it is started by hand, in plain words")}, @@ -89,16 +101,15 @@ func sourceTools(h *Holder, acts handActs) []stdio.Tool { Run: func(a map[string]any) (any, error) { return h.SourceStart(strArg(a, "branch"), strArg(a, "why"), stdio.CallerOf(a), acts) }}, - {Name: "gate_source_follow", - Description: "Move the head one watched branch's source names for one repository to the forge's head of that branch now, as " + - "the gate does when it hears a merge and at its start (design 47 G A-464); recorded in the hand-act log of the seat " + - "mesh-hand-acts first. Nothing is moved when the source already names the forge's head.", - Input: map[string]any{"type": "object", "properties": map[string]any{ - "branch": str("the watched branch"), "repository": str("the repository, owner/name"), - "why": str("why its head follows the forge by hand, in plain words")}, - "required": []string{"branch", "repository", "why"}}, - Run: func(a map[string]any) (any, error) { - return h.SourceFollow(strArg(a, "branch"), strArg(a, "repository"), strArg(a, "why"), stdio.CallerOf(a), acts) - }}, } } + +// sortedKeys are a map's keys, sorted. +func sortedKeys(m map[string]string) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools_test.go index aa0b7063c..5c0ba7fb7 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcetools_test.go @@ -4,13 +4,16 @@ import ( "encoding/json" "errors" "fmt" - meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - stdio "git.novox.be/novox/mesh-sdk/go" "reflect" + "slices" "strings" "testing" "time" + + gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" + meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + stdio "git.novox.be/novox/mesh-sdk/go" ) type branchSource struct{ memSource } @@ -29,7 +32,7 @@ func TestTheSourceToolsReadEveryBranchAndSayItAgainAfterTheLog(t *testing.T) { src := &branchSource{} for _, b := range []string{"main", "feat"} { _, _ = src.Set(b, func(*Source) (Source, bool) { - return Source{Group: "g-" + b, Heads: map[string]string{"novox/app": "c1"}}, true + return Source{Source: 3, Call: "00000000000000c1", Heads: map[string]string{"novox/app": "c1"}}, true }) } type said struct{ subject, id string } @@ -59,44 +62,18 @@ func TestTheSourceToolsReadEveryBranchAndSayItAgainAfterTheLog(t *testing.T) { t.Fatal(err) } if len(acts.took) != 1 || acts.took[0].Cause != "gate_source_again" || len(events) != 1 || - !strings.HasSuffix(events[0].subject, ".event.source-moved.main") || !strings.Contains(events[0].id, ".again.") { + !strings.HasSuffix(events[0].subject, ".event.source-moved.main.3") || !strings.Contains(events[0].id, ".again.") { t.Fatalf("log %+v events %+v", acts.took, events) } } -// Design 47 G §579: at its start the gate says `pinned` again for every revision each record pins, each under an id of its own, -// then `pins-stated` once. -func TestTheGateStatesItsPinsThenSaysPinsStated(t *testing.T) { - at := time.Date(2026, 11, 12, 4, 0, 0, 0, time.UTC) - type said struct{ subject, id string } - var events []said - rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }, - Say: func(subject string, body any, id string) error { - events = append(events, said{subject, id}) - return nil - }} - r, _, err := rs.Open("47/G", map[string]string{"novox/app@1": "c1"}, false) - if err != nil { - t.Fatal(err) - } - if err := rs.Pin(r, HalfCatalog, "main", 3); err != nil { - t.Fatal(err) - } - events = nil - n, err := rs.StatePins() - if err != nil || n != 1 || len(events) != 2 || !strings.HasSuffix(events[0].subject, ".event.pinned") || - !strings.Contains(events[0].id, ".stated.") || !strings.HasSuffix(events[1].subject, ".event.pins-stated") { - t.Fatalf("%d %v %+v", n, err, events) - } -} - // Design 47 G §428, §507: no part's code holds a branch's name; the trunk of each repository a source revision names is the // branch whose key was read, and delivery_status says every branch's source, not one fixed branch's. func TestTheSourceAnswerNamesTheBranchItWasAskedAndStatusSaysEveryBranch(t *testing.T) { src := &branchSource{} for _, b := range []string{"release", "feat"} { _, _ = src.Set(b, func(*Source) (Source, bool) { - return Source{Group: "g-" + b, Heads: map[string]string{"novox/app": "c1"}}, true + return Source{Source: 3, Call: "00000000000000c1", Heads: map[string]string{"novox/app": "c1"}}, true }) } h := &Holder{Now: time.Now, Source: src} @@ -121,6 +98,31 @@ func (f fakeCatalog) Registrations() (meshcatalog.RegistrationsAnswer, error) { // Design 47 G A-401: a watched branch starts from the forge as a clone does: each registered repository at the branch's head, // the group empty, source-moved said; a repository whose head cannot be read is left out; a key held is never rewritten. func TestAWatchedBranchStartsFromTheForge(t *testing.T) { + // A source-only registration (no module, design 47 H2 §815) is watched as any branch, its registrations read page by + // page from the cursor (§779, §806). + t.Run("a source-only registration past the first page is watched", func(t *testing.T) { + pages := map[string]meshcatalog.RegistrationsAnswer{ + "": {Registrations: []meshcatalog.Registration{{Module: "mesh-a", Origin: "o/mesh", Branches: []string{"main"}}}, Next: "p2", Capped: true}, + "p2": {Registrations: []meshcatalog.Registration{{Origin: "o/hq", Branches: []string{"main"}, Check: &meshcatalog.SourceCheck{Seat: "node-build-go", Step: "unit"}}}}, + } + var asked []string + c := seatCatalog{ask: func(key string, body any) (json.RawMessage, error) { + in := body.(meshcatalog.RegistrationsInput) + asked = append(asked, in.Next) + return json.Marshal(pages[in.Next]) + }} + a, err := c.Registrations() + if err != nil || !slices.Equal(asked, []string{"", "p2"}) { + t.Fatalf("asked %v: %v", asked, err) + } + if w := watchedRepositories(a.Registrations); !slices.Equal(w["main"], []string{"o/hq", "o/mesh"}) { + t.Errorf("main watches %v", w["main"]) + } + pages["p2"] = meshcatalog.RegistrationsAnswer{Next: "p2"} + if _, err := c.Registrations(); err == nil { + t.Error("pages that never end were read on") + } + }) regs := []meshcatalog.Registration{ {Module: "car-hunter", Origin: "o/car-hunter", Branches: []string{"main"}}, {Module: "mesh-a", Origin: "o/mesh", Branches: []string{"main"}}, @@ -148,15 +150,15 @@ func TestAWatchedBranchStartsFromTheForge(t *testing.T) { heads: map[string]map[string]string{"main": {"o/car-hunter": "c1", "o/mesh": "c2", "o/photos": "c6"}, "master": {"o/f1-circuits": "c3"}, "nox-mesh": {"o/link2pay": "c4"}}}, {name: "a held key lacking repositories gets them, its heads unchanged", catalog: fakeCatalog{regs: regs}, - held: map[string]Source{"main": {Group: "g", Heads: map[string]string{"o/mesh": "old"}}}, + held: map[string]Source{"main": {Source: 4, Call: "00000000000000aa", Heads: map[string]string{"o/mesh": "old"}}}, started: []string{"main", "master", "nox-mesh"}, events: 3, heads: map[string]map[string]string{"main": {"o/mesh": "old", "o/car-hunter": "c1", "o/photos": "c6"}, "master": {"o/f1-circuits": "c3"}, "nox-mesh": {"o/link2pay": "c4"}}}, {name: "a held key lacking one repository", catalog: fakeCatalog{regs: regs[:2]}, - held: map[string]Source{"main": {Group: "g", Heads: map[string]string{"o/mesh": "old"}}}, + held: map[string]Source{"main": {Source: 4, Call: "00000000000000aa", Heads: map[string]string{"o/mesh": "old"}}}, started: []string{"main"}, events: 1, heads: map[string]map[string]string{"main": {"o/mesh": "old", "o/car-hunter": "c1"}}}, {name: "a held key naming all: nothing written or said", catalog: fakeCatalog{regs: regs[:2]}, - held: map[string]Source{"main": {Group: "g", Heads: map[string]string{"o/mesh": "old", "o/car-hunter": "older"}}}, + held: map[string]Source{"main": {Source: 4, Call: "00000000000000aa", Heads: map[string]string{"o/mesh": "old", "o/car-hunter": "older"}}}, events: 0, heads: map[string]map[string]string{"main": {"o/mesh": "old", "o/car-hunter": "older"}}}, {name: "by hand, one branch", catalog: fakeCatalog{regs: regs}, only: "master", @@ -175,8 +177,9 @@ func TestAWatchedBranchStartsFromTheForge(t *testing.T) { Logf: func(f string, a ...any) { logged = append(logged, fmt.Sprintf(f, a...)) }, SaySeat: func(subject string, body any, id string) error { events++ - if ev := body.(seat.SourceMovedEvent); ev.Group != "" { - t.Errorf("a source-moved for started heads names no group (A-404), got %q", ev.Group) + ev := body.(seat.SourceMovedEvent) + if held, had := c.held[ev.Branch]; ev.Start == had || ev.Source != held.Source+1 || len(ev.Call) != 16 || len(ev.Heads) == 0 { + t.Errorf("a start's source-moved: %+v (start only for a branch's first revision, numbered above its newest)", ev) } return nil }} @@ -196,8 +199,8 @@ func TestAWatchedBranchStartsFromTheForge(t *testing.T) { } } for b, h := range c.held { - if src.vals[b].Group != h.Group { - t.Errorf("source.%s keeps the group %q a take-in wrote, got %q", b, h.Group, src.vals[b].Group) + if c.events == 0 && !reflect.DeepEqual(src.vals[b], h) { + t.Errorf("source.%s naming every repository is rewritten: %+v", b, src.vals[b]) } } if c.only == "" && c.held == nil && !strings.Contains(strings.Join(logged, "\n"), "o/photos") { @@ -253,7 +256,7 @@ func TestRegistrationChangedAndTheStartPassStartABranch(t *testing.T) { if err := c.run(h); err != nil { t.Fatal(err) } - if src.vals["master"].Heads["o/f1"] != "c3" || len(subjects) != 1 || !strings.HasSuffix(subjects[0], ".event.source-moved.master") { + if src.vals["master"].Heads["o/f1"] != "c3" || len(subjects) != 1 || !strings.HasSuffix(subjects[0], ".event.source-moved.master.1") { t.Fatalf("source %+v events %v", src.vals, subjects) } }) @@ -309,3 +312,72 @@ func (f *flakyCatalog) Registrations() (meshcatalog.RegistrationsAnswer, error) } return f.fakeCatalog.Registrations() } + +// fakeForge is the seat git's reads: a branch's head and whether one commit is in another. +type fakeForge struct { + heads map[string]string // "@" -> head + // contains says whether commit is in `in`; nil means every commit is in every other (a straight line forward) + contains func(commit, in string) bool + fail bool +} + +func (f *fakeForge) Branch(repository, branch string) (gitseat.BranchAnswer, error) { + if f.fail { + return gitseat.BranchAnswer{}, errors.New("the forge is away") + } + head, ok := f.heads[repository+"@"+branch] + if !ok { + return gitseat.BranchAnswer{Error: "no such branch"}, nil + } + return gitseat.BranchAnswer{Branch: branch, Repository: repository, Head: head}, nil +} +func (f *fakeForge) Contains(repository, commit, in string) (bool, error) { + if f.fail { + return false, errors.New("the forge is away") + } + if f.contains == nil { + return true, nil + } + return f.contains(commit, in), nil +} + +// GATE-8/AC14 (design 47 H §768; H-A-47, H-A-76): gate_source_seed writes one revision per watched branch at each registered +// repository's head, numbered from 1, start true, a call of its own, says source-moved, opens no record, answers the counts, +// and is recorded in the hand-act log first; it refuses to run while a key of the earlier form is held, naming it. +func TestTheSeedWritesEveryWatchedBranchsFirstRevision(t *testing.T) { + regs := []meshcatalog.Registration{{Module: "a", Origin: "o/a", Branches: []string{"main"}}, {Module: "b", Origin: "o/b", Branches: []string{"main"}}, + {Module: "c", Origin: "o/c", Branches: []string{"master"}}} + forge := &fakeForge{heads: map[string]string{"o/a@main": "ca", "o/b@main": "cb", "o/c@master": "cc"}} + setup := func() (*Holder, *branchSource, *[]seat.SourceMovedEvent) { + src := &branchSource{memSource{vals: map[string]Source{}}} + var moved []seat.SourceMovedEvent + h := &Holder{Now: time.Now, Source: src, Forge: forge, Catalog: fakeCatalog{regs: regs}, Logf: func(string, ...any) {}, + SaySeat: func(subject string, body any, id string) error { + moved = append(moved, body.(seat.SourceMovedEvent)) + return nil + }} + return h, src, &moved + } + h, src, moved := setup() + acts := &handActsFake{refuse: errors.New("log down")} + if _, err := h.SourceSeed("clean state", "lead@shanks", acts); err == nil || len(src.vals) != 0 { + t.Fatalf("seeded without the log: %v %+v", err, src.vals) + } + acts.refuse = nil + out, err := h.SourceSeed("clean state", "lead@shanks", acts) + if err != nil || out["branches"] != 2 || out["repositories"] != 3 || len(acts.took) != 1 || acts.took[0].Cause != "gate_source_seed" { + t.Fatalf("seed %+v %v, log %+v", out, err, acts.took) + } + if got := src.vals["main"]; got.Source != 1 || len(got.Call) != 16 || got.Heads["o/a"] != "ca" || got.Heads["o/b"] != "cb" { + t.Fatalf("source.main %+v", got) + } + if len(*moved) != 2 || !(*moved)[0].Start || !(*moved)[1].Start || (*moved)[0].Source != 1 || len((*moved)[0].Heads) != 2 { + t.Fatalf("source-moved %+v", *moved) + } + h, src, moved = setup() + src.unreadable = map[string]bool{"master": true} + if _, err := h.SourceSeed("clean state", "lead@shanks", &handActsFake{}); err == nil || !strings.Contains(err.Error(), "source.master") || + len(src.vals) != 0 || len(*moved) != 0 { + t.Fatalf("seeded over a key of the earlier form: %v %+v", err, src.vals) + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/switch.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/switch.go deleted file mode 100644 index 730eaea4e..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/switch.go +++ /dev/null @@ -1,296 +0,0 @@ -package main - -// The switch to the delivery record (design 47 *The delivery record*: "The switch carries today's state in, once"): at -// the new gate's start, every group in flight and its merge as the old sections hold them become records, keyed by the -// milestone and the heads. It is safe to run twice: a group in flight whose record is there already leaves it as it is -// (Records.Open), and a group state the record holds already is not written again (Records.SetGroup), so delivering milestone -// G again after a revert makes no second record and asks nothing again. The old sections are read, never written (§613). - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "sort" - "strings" - - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - "git.novox.be/novox/mesh-sdk/go/keys" - "git.novox.be/novox/mesh-sdk/go/process" -) - -// oldDelivery is a delivery as the old section `deliveries` kept it, as far as the switch reads it. -type oldDelivery struct { - ID string `json:"id"` - Repository string `json:"repository"` - Commit string `json:"commit"` - Number int `json:"number"` - Branch string `json:"branch"` - Group string `json:"group"` - State string `json:"state"` - InSource bool `json:"in_source"` - NewerHead string `json:"newer_head"` - ClosedUnmerged bool `json:"closed_unmerged"` -} - -// milestone is the name a delivery's record is kept under: its group's, a lone pull request's branch, its id. -func (d oldDelivery) milestone() string { - switch { - case d.Group != "": - return d.Group - case d.Branch != "": - return d.Branch - } - return d.ID -} - -// recordGroupOf is a merge, as the old section merges holds it, as the record's group state. -func recordGroupOf(m Merge, members []string) RecordGroup { - g := RecordGroup{Group: m.Group, Members: members, Ask: m.Ask, Approved: m.Approved} - for _, p := range m.Pulls { - g.Pulls = append(g.Pulls, RecordPull{Repository: p.Repository, Number: p.Number, Head: p.Head.Head, State: string(p.State), - Commit: p.Commit, Words: p.Words}) - } - return g -} - -// switchGroup is one group in flight as the switch finds it: its milestone, its heads and its members. -type switchGroup struct { - milestone string - heads map[string]string - members []string -} - -// inFlight are the groups in flight in the old section deliveries: every milestone with a delivery not final, its live -// members' heads as `@` to the full commit. -func (h *Holder) inFlight() ([]switchGroup, error) { - if h.Old == nil { - return nil, nil - } - keys, err := h.Old.Keys("deliveries") - if err != nil { - return nil, fmt.Errorf("the old section deliveries cannot be read for the switch: %w", err) - } - by := map[string]*switchGroup{} - for _, key := range keys { - raw, _, err := h.Old.Get("deliveries", key) - if err != nil { - return nil, fmt.Errorf("the old delivery %s cannot be read for the switch: %w", key, err) - } - var d oldDelivery - if raw == nil || json.Unmarshal(raw, &d) != nil || d.ID == "" { - continue // a mark an earlier owner kept, or no delivery - } - final := d.State == "merged" || d.State == "held" || d.State == "closed" - if final && !(d.State == "merged" && !d.InSource) || d.Number == 0 || d.NewerHead != "" || d.ClosedUnmerged { - continue - } - name := d.milestone() - g := by[name] - if g == nil { - g = &switchGroup{milestone: name, heads: map[string]string{}} - by[name] = g - } - g.heads[mdc.ApprovedKey(d.Repository, d.Number)] = d.Commit - g.members = append(g.members, d.ID) - } - out := make([]switchGroup, 0, len(by)) - for _, g := range by { - sort.Strings(g.members) - out = append(out, *g) - } - sort.Slice(out, func(i, j int) bool { return out[i].milestone < out[j].milestone }) - return out, nil -} - -// Switch carries today's state into the records, once and safe to run again: each group in flight becomes a record at -// its heads, or at the heads its merge was approved at when `merges` holds one, with that merge as its group state. -// It answers how many records it opened and how many it found there. It runs once (A-281): when it has carried today's state in -// it writes the key `switch.done`, and a start that finds the key runs no switch, so the deliveries the gate writes from the -// seat git's events (§716) never become records at a start. A revert's restore brings back the state without the key, so -// delivering G again switches again. -func (h *Holder) Switch() (opened, found int, err error) { - if h.Records == nil { - return 0, 0, nil - } - if done, err := h.Records.SwitchDone(); err != nil || done { - return 0, 0, err - } - defer func() { - if err == nil { - err = h.Records.MarkSwitched(process.ReadOwnBuild(os.Getenv).String()) - } - }() - groups, err := h.inFlight() - if err != nil { - return 0, 0, err - } - for _, g := range groups { - var merge *Merge - if h.Merges != nil { - if merge, err = h.Merges.Get(g.milestone); err != nil { - return opened, found, fmt.Errorf("the merge of %s cannot be read for the switch: %w", g.milestone, err) - } - } - heads := g.heads - if merge != nil && len(merge.Approved) > 0 { - heads = merge.Approved - } - r, made, err := h.Records.Open(g.milestone, heads, false) - if err != nil { - return opened, found, fmt.Errorf("the switch cannot open the record of %s: %w", g.milestone, err) - } - if made { - opened++ - } else { - found++ - } - if merge != nil { - if err := h.Records.SetGroup(r, recordGroupOf(*merge, g.members)); err != nil { - return opened, found, fmt.Errorf("the switch cannot carry the merge of %s: %w", g.milestone, err) - } - } - } - if err := h.carryOwed(); err != nil { - return opened, found, err - } - err = h.carryApprovals() - return opened, found, err -} - -// oldMerge is a group's merge as the old state merges holds it, with its key and revision; nil when it holds none. -func (h *Holder) oldMerge(group string) (*Merge, uint64, error) { - if h.Old == nil { - return nil, 0, nil - } - key, err := mdc.MergesKey(group) - if err != nil { - return nil, 0, err - } - raw, rev, err := h.Old.Get(mdc.SwitchedMerges, key) - if err != nil || raw == nil { - return nil, 0, err - } - m, err := DecodeMerge(raw) - if err != nil { - return nil, 0, err - } - return &m, rev, nil -} - -// carryOwed says every act the old state owed holds as owed, under its switched id (the state, the key and its revision: -// meshdeliveryclient.SwitchedActID), so the forge bridge performs what the old bridge did not and counts as performed what -// it did (design 47 G §169). No merge act is made from the old state merges (G §167, §542). Said at every switch, it is the same act each time. A key that cannot be read as an act is said -// as refused and skipped. -func (h *Holder) carryOwed() error { - if h.Old == nil || h.Owed == nil { - return nil - } - now := h.Now().UTC() - keys, err := h.Old.Keys(mdc.SwitchedOwed) - if err != nil { - return fmt.Errorf("the state owed cannot be read for the switch: %w", err) - } - for _, key := range keys { - raw, rev, err := h.Old.Get(mdc.SwitchedOwed, key) - if err != nil { - return fmt.Errorf("the owed act %s cannot be read for the switch: %w", key, err) - } - if raw == nil { - continue - } - repository, number, head, _, kerr := mdc.ParseOwedKey(key) - var o Owed - id, ierr := mdc.SwitchedActID(mdc.SwitchedOwed, key, rev) - if derr := json.Unmarshal(raw, &o); kerr != nil || derr != nil || ierr != nil { - h.Refuse(fmt.Errorf("the owed act %s is not carried by the switch: %v", key, errors.Join(kerr, derr, ierr))) - continue - } - said := seatOwedOf(o, id, repository, number, head, &now) - if r := h.recordHolding(repository, head); r != nil { - err = h.owe(r, said) - } else { - err = h.Owed.Say(said) - } - if err != nil { - return fmt.Errorf("the owed act %s cannot be said for the switch: %w", key, err) - } - } - return nil -} - -// recordHolding is the open record that holds a pull request of the repository at the head, nil when none does. -func (h *Holder) recordHolding(repository, head string) *Record { - if h.Records == nil { - return nil - } - current, err := h.Records.Current() - if err != nil { - return nil - } - for _, r := range current { - for _, m := range membersOf(r) { - if strings.EqualFold(m.Repository, repository) && sameCommit(m.Head, head) { - return r - } - } - } - return nil -} - -// approver is who an Approve carried across the switch was given by (design 47 §542). -const approver = "the operator" - -// carryApprovals says, for each key of the old section merges the old bridge had not performed, `approval-carried` of each -// pull request it had not merged, once (design 47 §542, §592): the runner takes it as that pull request's `approval` step. -// The keys stay, read no more. Said at every switch, it is the same event under the same id each time, which the bus keeps once. -func (h *Holder) carryApprovals() error { - if h.Old == nil || h.SaySeat == nil { - return nil - } - names, err := h.Old.Keys(mdc.SwitchedMerges) - if err != nil { - return fmt.Errorf("the old section merges cannot be read for the switch: %w", err) - } - now := h.Now().UTC() - for _, key := range names { - raw, _, err := h.Old.Get(mdc.SwitchedMerges, key) - if err != nil { - return fmt.Errorf("the old merge %s cannot be read for the switch: %w", key, err) - } - if raw == nil { - continue - } - m, err := DecodeMerge(raw) - if err != nil { - h.Refuse(fmt.Errorf("the old merge %s is not carried by the switch: %v", key, err)) - continue - } - for approved, head := range m.Approved { - repository, number, ok := parseApprovedKey(approved) - if !ok || mergedIn(m, repository, number) { - continue - } - body := seat.ApprovalCarriedEvent{Approver: approver, At: now, Commit: head, Pull: int64(number), Repository: repository} - subject := seat.SubjectApprovalCarried(keys.EscapeName(repository), fmt.Sprint(number)) - if err := h.SaySeat(subject, body, fmt.Sprintf("approval-carried.%s.%d", repository, number)); err != nil { - return fmt.Errorf("the approval of %s#%d cannot be said carried: %w", repository, number, err) - } - if err := h.approvalOpen(repository, number, head); err != nil { - return fmt.Errorf("the finding of the approval of %s#%d cannot be written: %w", repository, number, err) - } - } - } - return nil -} - -// mergedIn is whether a merge's pull request of that repository and number was merged. -func mergedIn(m Merge, repository string, number int) bool { - for _, p := range m.Pulls { - if strings.EqualFold(p.Repository, repository) && p.Number == number && p.State == mdc.MergeMerged { - return true - } - } - return false -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin.go index 11fd7131a..b6060d9c6 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin.go @@ -3,166 +3,61 @@ package main import ( "encoding/json" "fmt" - "sort" "strconv" - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk" "git.novox.be/novox/mesh-sdk/go/keys" ) -// What a take-in.taken does at the gate (design 47 G A-33, A-34; §151, §291, §592): it opens one delivery record, keyed by the -// taken body's branch and source revision, and moves that branch's source revision, saying source-moved. Nothing else opens a -// record or moves a source key. +// What a take-in.taken does at the gate (design 47 H §738, H-A-29): the record of its source revision, opened by the merge +// call (§737) and read by its key `.`, never by reading every record, gains the take-in's movers as its +// entries, each taken in; a take-in with no mover ends its record at once as nothing to deliver. It moves no source key: +// only a merge call does (§737, §764). -// recordMilestone is the key of a taken revision's record: `.`, each escaped as a name (A-33). +// recordMilestone is the key of a source revision's record: `.`, each escaped as a name (A-33). func recordMilestone(branch string, source int64) string { return keys.EscapeName(branch) + "." + keys.EscapeName(strconv.FormatInt(source, 10)) } -// TakenIn takes one take-in.taken body: the record of its source revision is opened (safe to repeat: a record there already -// is left as it is), its members are the entries' pull requests, its heads the merge commits the take-in names; then the -// branch's source key is written and source-moved said. A hand drop took nothing in, so it opens nothing. +// WhyNothingToDeliver is why a record whose take-in named no mover ends (§738). +const WhyNothingToDeliver = "nothing to deliver" + +// TakenIn takes one take-in.taken body. A revision with no record (a seed's or a start's, which open none, H-A-47) is +// taken with nothing written; safe to repeat: an entry or outcome the record holds is not written again. func (h *Holder) TakenIn(body json.RawMessage) error { var t meshcatalog.TakeInTaken if err := json.Unmarshal(body, &t); err != nil { return fmt.Errorf("a take-in.taken is not readable: %w", err) } - if t.Dropped || len(t.Merges) == 0 || t.Branch == "" { + if h.Records == nil || t.Branch == "" || t.Source < 1 { return nil } - if h.Records != nil { - heads := map[string]string{} - for _, m := range t.Merges { - heads[mdc.ApprovedKey(m.Repository, int(m.Number))] = m.Merge - } - milestone := recordMilestone(t.Branch, t.Source) - r, _, err := h.Records.Open(milestone, heads, false) - if err != nil { - return fmt.Errorf("the record of %s cannot be opened: %w", milestone, err) - } - g := RecordGroup{Group: t.Group} - seen := map[string]bool{} - for _, e := range t.Entries { - // A-188: the take-in's entries, each with its module, are written into the record. - if e.Module != "" { - if err := h.Records.AddEntry(r, RecordEntry{Module: e.Module, Fingerprint: e.Fingerprint}); err != nil { - return err - } - } - if e.Repository == "" || seen[mdc.ApprovedKey(e.Repository, int(e.Pull))] { - continue - } - seen[mdc.ApprovedKey(e.Repository, int(e.Pull))] = true - g.Members = append(g.Members, mdc.ApprovedKey(e.Repository, int(e.Pull))) - } - sort.Strings(g.Members) - // §716: each member's base is copied from its delivery onto the record's member; a record that holds the member already - // (a take-in heard again, its delivery deleted) keeps the base it holds. - var kept map[string]Delivery - if h.Kept != nil { - h.dmu.Lock() - kept, err = h.deliveries() - h.dmu.Unlock() - if err != nil { - return err - } - } - for _, m := range t.Merges { - p := RecordPull{Repository: m.Repository, Number: int(m.Number), Head: heads[mdc.ApprovedKey(m.Repository, int(m.Number))], - State: string(mdc.MergeMerged), Commit: m.Merge} - if base, ok := baseOf(kept, m.Repository, int(m.Number)); ok { - p.Base = base - } else if r.Group != nil { - for _, o := range r.Group.Pulls { - if samePull(Delivery{Repository: o.Repository, Number: o.Number}, m.Repository, int(m.Number)) { - p.Base = o.Base - } - } - } - if p.Base == "" && h.Kept != nil && h.Logf != nil { - h.Logf("[mesh-delivery] the take-in of %s names no delivery of %s#%d: its base is not known, the take-in's branch is %s", t.Group, m.Repository, m.Number, t.Branch) - } - g.Pulls = append(g.Pulls, p) - } - if err := h.Records.SetGroup(r, g); err != nil { - return err - } - // The record that carries the members now holds their bases: their deliveries, and a group no member of which remains outside a record, go. - if err := h.carried(g.Pulls); err != nil { - return err - } - } - return h.moveSource(t) -} - -// moveSource writes the taken source revision of a branch: the merge commit of each repository it took in, the group that -// moved it, and says source-moved with the key's revision. -func (h *Holder) moveSource(t meshcatalog.TakeInTaken) error { - if h.Source == nil { - return nil - } - heads := map[string]string{} - for _, m := range t.Merges { - heads[m.Repository] = m.Merge - } - // A head moves only forward (A-464d): a repository whose held head is not contained in the merge is left where it is. - if held, _, err := h.Source.Read(t.Branch); err != nil { - return err - } else if held != nil && h.Forge != nil { - for r, c := range heads { - for name, was := range held.Heads { - if !trunk.SameRepository(name, r) || was == c { - continue - } - ahead, err := h.Forge.Contains(name, was, c) - if err != nil { - return fmt.Errorf("whether %.12s is in %.12s of %s cannot be read, so the head stays: %w", was, c, name, err) - } - if !ahead { - h.logf("[mesh-delivery] source.%s keeps %s at %.12s: the take-in's merge %.12s does not contain it, left without effect", t.Branch, name, was, c) - delete(heads, r) - } - } - } - if len(heads) == 0 { - return nil - } - } - wrote := false - rev, err := h.Source.Set(t.Branch, func(prev *Source) (Source, bool) { - wrote = false - next := Source{Group: t.Group, Heads: heads} - if prev != nil { - same := true - for r, c := range heads { - if prev.Heads[r] != c { - same = false - } - } - if same { - return Source{}, false // a merged message moved these heads already: no revision (A-464c) - } - next.Heads = map[string]string{} - for r, c := range prev.Heads { - next.Heads[r] = c - } - for r, c := range heads { - next.Heads[r] = c - } - } - wrote = true - return next, true - }) + r, err := h.Records.ByKey(t.Branch, t.Source) if err != nil { - return fmt.Errorf("source.%s cannot be moved: %w", t.Branch, err) + return fmt.Errorf("the record of %s at %d cannot be read: %w", t.Branch, t.Source, err) } - if h.SaySeat == nil || !wrote { + if r == nil || r.Ended != nil { return nil } at := h.Now().UTC() - return h.SaySeat(seat.SubjectSourceMoved(keys.EscapeName(t.Branch)), - seat.SourceMovedEvent{Branch: t.Branch, Group: t.Group, Revision: int64(rev), At: &at}, "source-moved."+keys.EscapeName(t.Branch)+"."+strconv.FormatUint(rev, 10)) + for _, e := range t.Entries { + if e.Module == "" { + continue + } + if err := h.Records.AddEntry(r, RecordEntry{Module: e.Module, Fingerprint: e.Fingerprint}); err != nil { + return err + } + if _, err := h.Records.Outcome(r, RecordOutcome{Module: e.Module, Fingerprint: e.Fingerprint, Step: "take-in", + Outcome: OutcomeTakenIn, Why: t.Why, At: at}); err != nil { + return err + } + } + if len(t.Entries) == 0 { + why := WhyNothingToDeliver + if t.Skipped { + why += ": its take-in was skipped by hand: " + t.Why + } + return h.Records.End(r, why, t.By) + } + return nil } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_bus_test.go deleted file mode 100644 index a34bf2ef8..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_bus_test.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build integration - -package main - -import ( - "context" - "strings" - "testing" - "time" - - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" -) - -// The gate whole, over a real bus (design 47 G A-33, A-34): a take-in.taken the indexer says opens a delivery record in the -// gate's ledger with the take-in as its outcome, writes the branch's source key and says source-moved; the gate asks the -// controller nothing, and no state it no longer declares is needed (the template states are buckets under their local names). -const eventWithin = 20 * time.Second - -func TestAGateWholeTakesAnIndexersTakeInIntoARecordAndASourceKeyOverARealBus(t *testing.T) { - b := newTestBus(t) - ctx := context.Background() - rt := b.start(t) - evctx, cancel := context.WithCancel(ctx) - defer cancel() - rt.deliverEvents(evctx) - rt.untilListening() - merge := strings.Repeat("c", 40) - b.publish(t, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", map[string]any{"v": 1, "kind": "taken", "key": "m.00000000000000000001", - "what": "revision", "branch": "main", "source": 3, "since": "2026-11-11T19:00:00Z", - "merges": []any{map[string]any{"repository": "novox/app", "number": 5, "merge": merge}}, - "entries": []any{map[string]any{"module": "app", "commit": merge, "fingerprint": "f", "repository": "novox/app", "pull": 5}}}) - rt.until("the source key of main", eventWithin, func() bool { - e, err := b.kvs["source"].Get(ctx, mdc.SourceKey("main")) - if err != nil { - return false - } - s, err := mdc.DecodeSource(e.Value()) - return err == nil && s.Heads["novox/app"] == merge - }) - rt.until("the record of the take-in", eventWithin, func() bool { - b.mu.Lock() - defer b.mu.Unlock() - if b.ledger == nil { - return false - } - for instance := range b.ledger.states { - if strings.Contains(instance, "main") { - return true - } - } - return false - }) - rt.noControllerAsk() -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_test.go index a4c50ec07..7a32bd3db 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/takenin_test.go @@ -2,18 +2,20 @@ package main import ( "encoding/json" + "errors" "strings" "testing" "time" stdio "git.novox.be/novox/mesh-sdk/go" - "git.novox.be/novox/mesh-sdk/go/keys" ) // memSource is the gate's source bucket in memory: one value and revision per branch key. type memSource struct { vals map[string]Source rev uint64 + // unreadable are the branches whose key holds a value the gate cannot read (the earlier form). + unreadable map[string]bool } func (m *memSource) Set(branch string, update func(prev *Source) (Source, bool)) (uint64, error) { @@ -33,6 +35,9 @@ func (m *memSource) Set(branch string, update func(prev *Source) (Source, bool)) return m.rev, nil } func (m *memSource) Read(branch string) (*Source, uint64, error) { + if m.unreadable[branch] { + return nil, 0, errors.New("a source does not fit its shape") + } v, ok := m.vals[branch] if !ok { return nil, 0, nil @@ -41,10 +46,9 @@ func (m *memSource) Read(branch string) (*Source, uint64, error) { } func (m *memSource) Branches() ([]string, error) { return nil, nil } -// Design 47 G A-33, A-34: a take-in.taken opens one record keyed `.`, whose members are the entries' pull -// requests and whose heads are the merge commits it names, moves that branch's source key and says source-moved; heard twice -// it opens no second record; a hand drop opens nothing and moves nothing. -func TestATakeInTakenOpensOneRecordAndMovesItsBranchsSource(t *testing.T) { +// GATE-3/AC3 (design 47 H §737, §764): neither a take-in.taken nor the forge bridge's merged message moves a source key, +// says source-moved or opens a record: only a merge call does (mergecalled_test.go). +func TestATakeInTakenOpensNoRecordAndMovesNoSource(t *testing.T) { now := time.Date(2026, 11, 11, 20, 0, 0, 0, time.UTC) type said struct{ subject, id string } var events []said @@ -56,43 +60,21 @@ func TestATakeInTakenOpensOneRecordAndMovesItsBranchsSource(t *testing.T) { }} h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now} merge := strings.Repeat("a", 40) - body := json.RawMessage(`{"v":1,"kind":"taken","key":"g.feat","what":"group","group":"feat","branch":"main","source":7,` + - `"merges":[{"repository":"novox/app","number":3,"merge":"` + merge + `"}],` + - `"entries":[{"module":"app","commit":"` + merge + `","fingerprint":"f","repository":"novox/app","pull":3}],"since":"2026-11-11T19:00:00Z"}`) + body := json.RawMessage(`{"branch":"main","source":7,"revision":7,"call":"0000000000000007",` + + `"entries":[{"module":"app","commit":"` + merge + `","fingerprint":"f","repository":"novox/app"}]}`) c := &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn} - for i := 0; i < 2; i++ { - if err := c.Hear(stdio.Envelope{Key: "mesh-delivery-indexer.take-in.taken", Body: body}); err != nil { - t.Fatal(err) - } - } - kept, err := h.Records.Kept() - if err != nil || len(kept) != 1 { - t.Fatalf("records %v %v: one per take-in", kept, err) - } - r := kept[0] - if r.Milestone != keys.EscapeName("main")+".7" || r.Heads["novox/app@3"] != merge || r.Group == nil || - len(r.Group.Members) != 1 || r.Group.Members[0] != "novox/app@3" || r.Group.Group != "feat" { - t.Fatalf("the record %+v group %+v", r, r.Group) - } - // A-188: the take-in's entries are in the record, each with its module. - if e, ok := r.Entries[EntryKey("app", "f", "")]; !ok || e.Module != "app" { - t.Fatalf("the take-in's entries are not in the record: %+v", r.Entries) - } - if got := r.Outcomes[OutcomeKey("", "", "", "take-in")]; got.Outcome != OutcomeTakenIn { - t.Fatalf("the take-in is not the record's outcome: %+v", r.Outcomes) - } - if s := src.vals["main"]; s.Group != "feat" || s.Heads["novox/app"] != merge { - t.Fatalf("source.main %+v", s) - } - if len(events) != 1 || !strings.HasSuffix(events[0].subject, ".event.source-moved.main") { - t.Fatalf("said %+v", events) - } - drop := json.RawMessage(`{"v":1,"kind":"taken","key":"m.00000000000000000002","what":"revision","dropped":true,"branch":"main","source":8,` + - `"merges":[{"repository":"novox/lib","number":4,"merge":"` + merge + `"}],"since":"2026-11-11T19:00:00Z"}`) - if err := c.Hear(stdio.Envelope{Key: "mesh-delivery-indexer.take-in.taken", Body: drop}); err != nil { + if err := c.Hear(stdio.Envelope{Key: "mesh-delivery-indexer.take-in.taken", Body: body}); err != nil { t.Fatal(err) } - if kept, _ := h.Records.Kept(); len(kept) != 1 || len(events) != 1 { - t.Fatalf("a hand drop opened %d records and said %d events", len(kept), len(events)) + if kept, err := h.Records.Kept(); err != nil || len(kept) != 0 { + t.Fatalf("records %v %v: a take-in opens none", kept, err) + } + if len(src.vals) != 0 || len(events) != 0 { + t.Fatalf("a take-in.taken moved source %+v and said %+v", src.vals, events) + } + merged := stdio.Envelope{Key: "mesh-delivery-forge-bridge.forge.novox.app.merged", + Body: json.RawMessage(`{"v":1,"kind":"merged","repository":"novox/app","base":"main","head":"` + merge + `"}`)} + if err := take(h, merged); err != nil || len(src.vals) != 0 || len(events) != 0 { + t.Fatalf("a merged message moved source %+v and said %+v (%v)", src.vals, events, err) } } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/times.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/times.go new file mode 100644 index 000000000..da3762abf --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/times.go @@ -0,0 +1,203 @@ +package main + +// A delivery record keeps its delivery time (design 47 H2 §810; ADR 0282 §1, §6, §7; ADR 0304; H-A-394): the head entry +// keeps `merge-called` from its opening, the pipeline's `phases` (§785) from its end, and at its end the record's +// `delivery-time`, from `merge-called` to the last `running` of its movers, and its `class`: core when it moves a module +// whose manifest's class (the catalog entry the gate read at the mover's opening) says core, else leaf. gate_times +// answers each class's budget, the last seven days' median and worst, and every delivery over its budget with its +// longest phase; the self-check's probe judges them, the gate raises nothing. + +import ( + "fmt" + "sort" + "time" + + stdio "git.novox.be/novox/mesh-sdk/go" + catalogue "git.novox.be/novox/mesh-sdk/go/catalogue" + + runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" +) + +// OpPhases writes the pipeline's phases on the head entry (set-fields phases). +const OpPhases = "phases" + +// The budgets' settings and their defaults (ADR 0282, ADR 0304). +const ( + BudgetCoreSetting = "budget-core" + BudgetLeafSetting = "budget-leaf" + DefaultBudgetCore = 10 * time.Minute + DefaultBudgetLeaf = 3 * time.Minute +) + +// timesWindow is how far back gate_times reads (§810: the last seven days). +const timesWindow = 7 * 24 * time.Hour + +// Budgets are the two classes' budgets, read with the one settings reader; a value that is no duration is said and the +// default kept. +func (h *Holder) Budgets() map[string]time.Duration { + out := map[string]time.Duration{} + for class, s := range map[string]struct { + key string + def time.Duration + }{catalogue.ClassCore: {BudgetCoreSetting, DefaultBudgetCore}, catalogue.ClassLeaf: {BudgetLeafSetting, DefaultBudgetLeaf}} { + d, err := stdio.SettingDuration(s.key, s.def) + if err != nil { + h.logf("[mesh-delivery] the setting %s: %v; %s is kept", s.key, err, s.def) + d = s.def + } + out[class] = d + } + return out +} + +// SetPhases writes the pipeline's phases on the record's head entry, unless it holds them already. +func (rs *Records) SetPhases(r *Record, p *runner.PipelineEndedPhases) error { + if p == nil { + return nil + } + next := *r + next.Phases = p + seq, err := rs.write(r, r.Instance, OpPhases, map[string]any{"phases": p}, next.head()) + if err != nil { + return err + } + r.Phases, r.Sequence = p, seq + return nil +} + +// timesAtEnd are the delivery time and the class of a record whose every mover runs: from merge-called to the last running +// of its movers; core when one of its movers is core. No delivery time without merge-called or a running. +func timesAtEnd(r *Record) (time.Duration, string) { + class := catalogue.ClassLeaf + var last time.Time + for _, m := range r.movers { + if m.Class == catalogue.ClassCore { + class = catalogue.ClassCore + } + for _, at := range m.Running() { + if at.After(last) { + last = at + } + } + } + if r.MergeCalled.IsZero() || last.IsZero() || last.Before(r.MergeCalled) { + return 0, class + } + return last.Sub(r.MergeCalled), class +} + +// longestPhase is the record's longest phase of §785 and its length: the take-in, the placing, each step kind's span. +func longestPhase(p *runner.PipelineEndedPhases, mergeCalled time.Time) (string, time.Duration) { + if p == nil { + return "", 0 + } + type span struct { + name string + start, end *time.Time + } + mc := mergeCalled + spans := []span{{"take-in", &mc, p.Taken}, {"placing", p.Taken, p.Placed}} + add := func(name string, start, end *time.Time) { spans = append(spans, span{name, start, end}) } + if b := p.Build; b != nil { + add("build", b.Start, b.End) + } + if b := p.Lint; b != nil { + add("lint", b.Start, b.End) + } + if b := p.Unit; b != nil { + add("unit", b.Start, b.End) + } + if b := p.Integration; b != nil { + add("integration", b.Start, b.End) + } + if b := p.Validate; b != nil { + add("validate", b.Start, b.End) + } + if b := p.Composition; b != nil { + add("composition", b.Start, b.End) + } + name, longest := "", time.Duration(0) + for _, s := range spans { + if s.start == nil || s.end == nil || s.start.IsZero() { + continue + } + if d := s.end.Sub(*s.start); d > longest { + name, longest = s.name, d + } + } + return name, longest +} + +// TimesOver is one delivery over its class's budget, with its longest phase. +type TimesOver struct { + Record string `json:"record"` + Milestone string `json:"milestone"` + Ended string `json:"ended"` + DeliveryTime string `json:"delivery-time"` + Longest string `json:"longest-phase,omitempty"` + LongestTime string `json:"longest-phase-time,omitempty"` +} + +// TimesLast is a class's newest ended delivery: whether it was over its budget, which the self-check's probe judges +// (design 47 H2 §810; H-A-396). +type TimesLast struct { + TimesOver + Over bool `json:"over"` +} + +// ClassTimes are one class's times over the last seven days. +type ClassTimes struct { + Budget string `json:"budget"` + Deliveries int `json:"deliveries"` + Median string `json:"median,omitempty"` + Worst string `json:"worst,omitempty"` + Over []TimesOver `json:"over"` + Last *TimesLast `json:"last,omitempty"` +} + +// Times is gate_times: each class's budget, the last seven days' median and worst, and every delivery over its budget, +// newest first, with its longest phase (§810; ADR 0282 §6). +func (h *Holder) Times() (map[string]ClassTimes, error) { + kept, err := h.keptRecords() + if err != nil { + return nil, err + } + budgets, now := h.Budgets(), h.Now().UTC() + by := map[string][]*Record{} + for _, r := range kept { + if r.Ended == nil || r.DeliveryTime == "" || now.Sub(r.Ended.At) > timesWindow { + continue + } + by[firstOf(r.Class, catalogue.ClassLeaf)] = append(by[firstOf(r.Class, catalogue.ClassLeaf)], r) + } + out := map[string]ClassTimes{} + for class, budget := range budgets { + rs := by[class] + ct := ClassTimes{Budget: budget.String(), Deliveries: len(rs), Over: []TimesOver{}} + var ds []time.Duration + sort.Slice(rs, func(i, j int) bool { return rs[i].Ended.At.After(rs[j].Ended.At) }) + for _, r := range rs { + d, err := time.ParseDuration(r.DeliveryTime) + if err != nil { + return nil, fmt.Errorf("the record %s keeps a delivery time %q that is no duration", r.Instance, r.DeliveryTime) + } + ds = append(ds, d) + o := TimesOver{Record: r.Instance, Milestone: r.Milestone, Ended: r.Ended.At.Format(time.RFC3339), DeliveryTime: d.String()} + if name, l := longestPhase(r.Phases, r.MergeCalled); name != "" { + o.Longest, o.LongestTime = name, l.String() + } + if ct.Last == nil { + ct.Last = &TimesLast{TimesOver: o, Over: d > budget} + } + if d > budget { + ct.Over = append(ct.Over, o) + } + } + if len(ds) > 0 { + sort.Slice(ds, func(i, j int) bool { return ds[i] < ds[j] }) + ct.Median, ct.Worst = ds[len(ds)/2].String(), ds[len(ds)-1].String() + } + out[class] = ct + } + return out, nil +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values.go deleted file mode 100644 index b1de5f8ce..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values.go +++ /dev/null @@ -1,130 +0,0 @@ -package main - -import ( - "encoding/json" - "reflect" - - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" -) - -// The values the gate keeps in the seat mesh-delivery's states. The seat's types are the layout and meshdeliveryclient -// holds their rules and codecs; Source, Owed and Answer are used as they are, and the three whose seat form differs from the -// form the gate works in (a pull request that holds its head, the router's ask as bytes, a turn's times as plain times) -// are converted at the edge, so a stored value decodes unchanged (novox/hq ADR 0634 §2). -type ( - // Source is the state source's value. - Source = seat.SourceByBranchValue - // Owed is the state owed's value: what the forge bridge performs. - Owed = seat.OwedByRepositoryNumberHeadActValue - // Answer is the operator's answer as the gate acts on it. - Answer = mdc.Answer -) - -// Merge is the state merges' value: a group's merge. -type Merge struct { - V int - Group string - Ask string - Approved map[string]string - Pulls []MergePull -} - -// MergePull is one pull request of a merge: its expected head, its state, the merge commit once merged, the forge's words -// when refused. -type MergePull struct { - mdc.Head - State mdc.MergeState - Commit string - Words string -} - -func (m Merge) stored() seat.MergesByGroupValue { - out := seat.MergesByGroupValue{Approved: m.Approved, Ask: m.Ask, Group: m.Group, V: int64(m.V)} - if m.Pulls != nil { - out.Pulls = make([]seat.MergesByGroupValuePullsItem, len(m.Pulls)) - } - for i, p := range m.Pulls { - out.Pulls[i] = seat.MergesByGroupValuePullsItem{Commit: p.Commit, Head: p.Head.Head, Number: int64(p.Number), - Repository: p.Repository, State: string(p.State), Words: p.Words} - } - return out -} - -func mergeFromSeat(s seat.MergesByGroupValue) Merge { - out := Merge{V: int(s.V), Group: s.Group, Ask: s.Ask, Approved: s.Approved} - for _, p := range s.Pulls { - out.Pulls = append(out.Pulls, MergePull{Head: mdc.Head{Repository: p.Repository, Number: int(p.Number), Head: p.Head}, - State: mdc.MergeState(p.State), Commit: p.Commit, Words: p.Words}) - } - return out -} - -// EncodeMerge is m as the value of a merges key. -func EncodeMerge(m Merge) ([]byte, error) { return mdc.EncodeMerge(m.stored()) } - -// DecodeMerge reads the value of a merges key. -func DecodeMerge(data []byte) (Merge, error) { - s, err := mdc.DecodeMerge(data) - if err != nil { - return Merge{}, err - } - return mergeFromSeat(s), nil -} - -// SameMerge says whether two merges are the same value. -func SameMerge(a, b Merge) bool { return mdc.SameMerge(a.stored(), b.stored()) } - -// Ask is the state asks' value: the router's ask for a group's merge at its heads. -type Ask struct { - V int - Group string - Heads []mdc.Head - Ask json.RawMessage - // Asking counts the times the gate wrote this group's ask at these heads (0 or 1 for the first). - Asking int -} - -func (a Ask) stored() seat.AsksByMergeGroupHeadsValue { - out := seat.AsksByMergeGroupHeadsValue{Asking: int64(a.Asking), Group: a.Group, V: int64(a.V)} - if len(a.Ask) > 0 { - out.Ask = a.Ask - } - if a.Heads != nil { - out.Heads = make([]seat.AsksByMergeGroupHeadsValueHeadsItem, len(a.Heads)) - } - for i, h := range a.Heads { - out.Heads[i] = seat.AsksByMergeGroupHeadsValueHeadsItem{Head: h.Head, Number: int64(h.Number), Repository: h.Repository} - } - return out -} - -func askFromSeat(s seat.AsksByMergeGroupHeadsValue) (Ask, error) { - raw, err := json.Marshal(s.Ask) - if err != nil { - return Ask{}, err - } - return Ask{V: int(s.V), Group: s.Group, Heads: mdc.HeadsOf(s.Heads), Ask: raw, Asking: int(s.Asking)}, nil -} - -// EncodeAsk is a as the value of an asks key. -func EncodeAsk(a Ask) ([]byte, error) { return mdc.EncodeAsk(a.stored()) } - -// DecodeAsk reads the value of an asks key. -func DecodeAsk(data []byte) (Ask, error) { - s, err := mdc.DecodeAsk(data) - if err != nil { - return Ask{}, err - } - return askFromSeat(s) -} - -// SameAsk says whether two asks are the same value, the router's ask by its content. -func SameAsk(a, b Ask) bool { - var x, y any - if json.Unmarshal(a.Ask, &x) != nil || json.Unmarshal(b.Ask, &y) != nil { - return false - } - a.Ask, b.Ask = nil, nil - return reflect.DeepEqual(a, b) && reflect.DeepEqual(x, y) -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values_test.go deleted file mode 100644 index d1b22ce26..000000000 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/values_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "encoding/json" - "reflect" - "testing" - - mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient" -) - -// What go/delivery wrote into the seat's states, key order and all, must decode as it did and encode to the same -// content (ADR 0634 §2): the gate's working values are converted to the seat's types at the edge. -func TestStoredValuesOfTheEarlierLayoutDecodeUnchanged(t *testing.T) { - head := mdc.Head{Repository: "novox/app", Number: 7, Head: "0123456789abcdef0123456789abcdef01234567"} - rows := []struct { - name string - stored string - decode func(string) (any, error) - encode func(any) ([]byte, error) - want any - }{ - {"merge with a merged and a refused pull", `{"v":1,"group":"feat/x","ask":"merge.feat_x.0123456789ab","approved":{"novox/app@7":"` + head.Head + `","novox/web@8":"abc"},` + - `"pulls":[{"repository":"novox/app","number":7,"head":"` + head.Head + `","state":"merged","commit":"c0ffee"},` + - `{"repository":"novox/web","number":8,"head":"abc","state":"refused","words":"mesh/check (missing)"}]}`, - func(s string) (any, error) { return DecodeMerge([]byte(s)) }, func(v any) ([]byte, error) { return EncodeMerge(v.(Merge)) }, - Merge{V: 1, Group: "feat/x", Ask: "merge.feat_x.0123456789ab", Approved: map[string]string{"novox/app@7": head.Head, "novox/web@8": "abc"}, Pulls: []MergePull{ - {Head: head, State: mdc.MergeMerged, Commit: "c0ffee"}, - {Head: mdc.Head{Repository: "novox/web", Number: 8, Head: "abc"}, State: mdc.MergeRefused, Words: "mesh/check (missing)"}}}}, - {"ask keeps the router's ask as bytes", `{"v":1,"group":"feat/x","heads":[{"repository":"novox/app","number":7,"head":"` + head.Head + `"}],"ask":{"id":"a","options":["Approve"]},"asking":2}`, - func(s string) (any, error) { return DecodeAsk([]byte(s)) }, func(v any) ([]byte, error) { return EncodeAsk(v.(Ask)) }, - Ask{V: 1, Group: "feat/x", Heads: []mdc.Head{head}, Ask: json.RawMessage(`{"id":"a","options":["Approve"]}`), Asking: 2}}, - {"source", `{"v":1,"group":"feat/x","heads":{"novox/app":"c0ffee"}}`, - func(s string) (any, error) { return mdc.DecodeSource([]byte(s)) }, func(v any) ([]byte, error) { return mdc.EncodeSource(v.(Source)) }, - Source{V: 1, Group: "feat/x", Heads: map[string]string{"novox/app": "c0ffee"}}}, - {"owed status", `{"v":1,"act":"status","context":"mesh/delivery","target":"https://x/y","state":"pending"}`, - func(s string) (any, error) { return mdc.DecodeOwed([]byte(s)) }, func(v any) ([]byte, error) { return mdc.EncodeOwed(v.(Owed)) }, - Owed{V: 1, Act: "status", Context: "mesh/delivery", Target: "https://x/y", State: "pending"}}, - {"answer", `{"v":1,"option":"Approve","warrant":"w@2026-11-05T10:00:00Z","words":"chose Approve"}`, - func(s string) (any, error) { return mdc.DecodeAnswer([]byte(s)) }, func(v any) ([]byte, error) { return mdc.EncodeAnswer(v.(Answer)) }, - Answer{V: 1, Option: "Approve", Warrant: "w@2026-11-05T10:00:00Z", Words: "chose Approve"}}, - } - for _, r := range rows { - t.Run(r.name, func(t *testing.T) { - got, err := r.decode(r.stored) - if err != nil { - t.Fatalf("the earlier layout does not decode: %v", err) - } - if !sameValue(got, r.want) { - t.Fatalf("decoded %+v, want %+v", got, r.want) - } - raw, err := r.encode(got) - if err != nil { - t.Fatalf("encode: %v", err) - } - var a, b any - if json.Unmarshal(raw, &a) != nil || json.Unmarshal([]byte(r.stored), &b) != nil || !reflect.DeepEqual(a, b) { - t.Fatalf("encoded %s, the earlier layout was %s", raw, r.stored) - } - }) - } -} - -func sameValue(a, b any) bool { - if x, ok := a.(Ask); ok { - return SameAsk(x, b.(Ask)) - } - return reflect.DeepEqual(a, b) -} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/verbs.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/verbs.go index 52e21c370..78a9be406 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/verbs.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/verbs.go @@ -1,12 +1,14 @@ package main import ( + "encoding/base64" + "encoding/json" "fmt" "sort" "strings" "time" - seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" + "git.novox.be/novox/mesh-sdk/go/views" ) // The seat's verbs that read (novox/hq ADR 0239; design 47 G §431, §172, A-24): from G's delivery the gate keeps no merge @@ -52,14 +54,27 @@ func holdsRepository(r *Record, repository string) bool { return false } +// Member is one pull request of a record as the verbs deliveries and show answer it: its id, repository, number, head, +// state, whether it is open and its base (the seat's type goes with the verb groups, design 47 H §764; the verbs answer +// from the records, A-24). +type Member struct { + ID string `json:"id"` + Repository string `json:"repository"` + Number int64 `json:"number"` + Head string `json:"head"` + State string `json:"state"` + Open bool `json:"open,omitempty"` + Base string `json:"base,omitempty"` +} + // membersOf are a record's pull requests: the group's pulls as kept, or else the members its heads name (`@` // to the commit, as an Approve names them). -func membersOf(r *Record) []seat.Member { +func membersOf(r *Record) []Member { open := r.Ended == nil - var out []seat.Member + var out []Member if r.Group != nil && len(r.Group.Pulls) > 0 { for _, p := range r.Group.Pulls { - out = append(out, seat.Member{ID: IDOf(p.Repository, firstOf(p.Commit, p.Head)), Repository: p.Repository, State: p.State, + out = append(out, Member{ID: IDOf(p.Repository, firstOf(p.Commit, p.Head)), Repository: p.Repository, State: p.State, Number: int64(p.Number), Head: p.Head, Open: open && p.State != "merged", Base: p.Base}) } return out @@ -74,7 +89,7 @@ func membersOf(r *Record) []seat.Member { if !ok { repository = id } - out = append(out, seat.Member{ID: IDOf(repository, r.Heads[id]), Repository: repository, Number: int64(number), Head: r.Heads[id], + out = append(out, Member{ID: IDOf(repository, r.Heads[id]), Repository: repository, Number: int64(number), Head: r.Heads[id], State: stateOf(r), Open: open}) } return out @@ -100,9 +115,66 @@ func firstOf(a, b string) string { return b } +// DeliveriesFilter narrows `deliveries` (design 47 H2 §811): state (open or ended), repository, group, the module a record +// moves, the outcome it ended with and the time it opened at or after; All lists the ended ones of every day kept; Next is +// the cursor the previous page answered. +type DeliveriesFilter struct { + State, Repository, Group, Module, Outcome string + Since time.Time + All bool + Next string +} + +// movesModule is whether one of the record's entries is the module's. +func movesModule(r *Record, module string) bool { + for _, e := range r.Entries { + if e.Module == module { + return true + } + } + return false +} + +// endedWith is whether the record ended with the outcome: its why, or the why's first word before a colon ("failed" for +// "failed: "). +func endedWith(r *Record, outcome string) bool { + if r.Ended == nil { + return false + } + return r.Ended.Why == outcome || strings.HasPrefix(r.Ended.Why, outcome+":") +} + +// deliveriesCursor is the opaque cursor of a page of `deliveries` (§779): the place of the last record it answered in the +// order open first, then the newest. +func deliveriesCursor(v recordView) string { + return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%t|%d|%s", v.Record.Ended == nil, v.Record.Opened.UnixNano(), v.Instance))) +} + +// beforeOrAt is whether v comes at or before the place cursor names, in the order of `deliveries`. +func beforeOrAt(v recordView, cursor string) (bool, error) { + raw, err := base64.RawURLEncoding.DecodeString(cursor) + parts := strings.SplitN(string(raw), "|", 3) + if err != nil || len(parts) != 3 { + return false, fmt.Errorf("deliveries: %q is no cursor this verb answered", cursor) + } + var opened int64 + if _, err := fmt.Sscanf(parts[1], "%d", &opened); err != nil { + return false, fmt.Errorf("deliveries: %q is no cursor this verb answered", cursor) + } + open := v.Record.Ended == nil + switch cOpen := parts[0] == "true"; { + case open != cOpen: + return open, nil + case v.Record.Opened.UnixNano() != opened: + return v.Record.Opened.UnixNano() > opened, nil + } + return v.Instance >= parts[2], nil +} + // Deliveries is the `deliveries` verb: every record kept as it is kept, the open ones first, then the newest; the ended ones -// of the last thirty days (all: every one kept), narrowed by state (open or ended), repository or group. -func (h *Holder) Deliveries(state, repository, group string, all bool) (map[string]any, error) { +// of the last thirty days (all: every one kept), narrowed by the filter while it reads, at most views.PageBytes a page +// with capped, total and the next page's cursor (design 47 H2 §811, §779), never refused as too big. +func (h *Holder) Deliveries(f DeliveriesFilter) (map[string]any, error) { kept, err := h.keptRecords() if err != nil { return nil, err @@ -110,10 +182,11 @@ func (h *Holder) Deliveries(state, repository, group string, all bool) (map[stri now := h.Now() var out []recordView for _, r := range kept { - if state != "" && state != stateOf(r) || repository != "" && !holdsRepository(r, repository) || group != "" && groupOf(r) != group { - continue - } - if r.Ended != nil && !all && now.Sub(r.Ended.At) > listedFor { + switch { + case f.State != "" && f.State != stateOf(r), f.Repository != "" && !holdsRepository(r, f.Repository), + f.Group != "" && groupOf(r) != f.Group, f.Module != "" && !movesModule(r, f.Module), + f.Outcome != "" && !endedWith(r, f.Outcome), !f.Since.IsZero() && r.Opened.Before(f.Since), + r.Ended != nil && !f.All && now.Sub(r.Ended.At) > listedFor: continue } out = append(out, viewOf(r)) @@ -122,12 +195,30 @@ func (h *Holder) Deliveries(state, repository, group string, all bool) (map[stri if (out[i].Record.Ended == nil) != (out[j].Record.Ended == nil) { return out[i].Record.Ended == nil } - return out[i].Record.Opened.After(out[j].Record.Opened) + if !out[i].Record.Opened.Equal(out[j].Record.Opened) { + return out[i].Record.Opened.After(out[j].Record.Opened) + } + return out[i].Instance > out[j].Instance }) - if out == nil { - out = []recordView{} + page, size, capped, next := []recordView{}, 0, false, "" + for _, v := range out { + if f.Next != "" { + at, err := beforeOrAt(v, f.Next) + if err != nil { + return nil, err + } + if at { + continue + } + } + raw, _ := json.Marshal(v) + if size+len(raw) > views.PageBytes && len(page) > 0 { + capped, next = true, deliveriesCursor(page[len(page)-1]) + break + } + page, size = append(page, v), size+len(raw) } - return map[string]any{"deliveries": out}, nil + return map[string]any{"deliveries": page, "capped": capped, "total": len(out), "next": next}, nil } func (h *Holder) keptRecords() ([]*Record, error) { @@ -164,114 +255,6 @@ func (h *Holder) Show(id string) (any, error) { return map[string]any{"records": out}, nil } -// Groups is the seat's verb groups: every record's group not ended (all: those that ended too), or with only that group -// alone, ended or not, and none for a group it does not know. Each with its members, its state, why, and the acts the gate said -// for it with the outcome recorded in the record (owedended.go). -func (h *Holder) Groups(all bool, only string) seat.GroupsAnswer { - kept, err := h.keptRecords() - if err != nil { - return seat.GroupsAnswer{Error: err.Error()} - } - out := seat.GroupsAnswer{Groups: []seat.Group{}} - for _, r := range kept { - if only != "" && groupOf(r) != only || only == "" && !all && r.Ended != nil { - continue - } - g := seat.Group{ID: groupOf(r), State: stateOf(r), Members: membersOf(r), Acts: recordedActs(r)} - if r.Ended != nil { - g.Why = r.Ended.Why - } else { - g.Why = allRun(r) - } - out.Groups = append(out.Groups, g) - } - if err := h.addKeptMembers(&out, kept, all, only); err != nil { - return seat.GroupsAnswer{Error: err.Error()} - } - sort.SliceStable(out.Groups, func(i, j int) bool { return out.Groups[i].ID < out.Groups[j].ID }) - return out -} - -// memberOf is a pull request as one key: the repository in lower case and the number. -func memberOf(repository string, number int64) string { - return fmt.Sprintf("%s#%d", strings.ToLower(repository), number) -} - -// addKeptMembers answers a group from its records and its key in the state `groups` together, each member once, a record's first -// (§716, A-279): the members of a group the gate keeps and no record carries, with their delivery's base, head, state and open -// while not merged, so before any take-in the verb names every member and its base. A group only its key holds is open. -func (h *Holder) addKeptMembers(out *seat.GroupsAnswer, kept []*Record, all bool, only string) error { - if h.Kept == nil { - return nil - } - groups, err := h.keptGroups() - if err != nil { - return err - } - deliveries, err := h.deliveries() - if err != nil { - return err - } - carried := map[string]map[string]bool{} - for _, r := range kept { - id := groupOf(r) - if carried[id] == nil { - carried[id] = map[string]bool{} - } - for _, m := range membersOf(r) { - carried[id][memberOf(m.Repository, m.Number)] = true - } - } - for _, kg := range groups { - if only != "" && kg.Group != only { - continue - } - var add []seat.Member - for _, d := range deliveries { - if d.Branch != kg.Group || carried[kg.Group][memberOf(d.Repository, int64(d.Number))] { - continue - } - add = append(add, seat.Member{ID: d.ID, Repository: d.Repository, State: d.openOrMerged(), Number: int64(d.Number), Head: d.Commit, - Open: d.openOrMerged() != deliveryMerged, Base: d.Base}) - } - if len(add) == 0 { - continue - } - sort.Slice(add, func(i, j int) bool { return add[i].ID < add[j].ID }) - placed := false - for i := range out.Groups { - if out.Groups[i].ID == kg.Group { - out.Groups[i].Members = append(out.Groups[i].Members, add...) - placed = true - } - } - if !placed { - out.Groups = append(out.Groups, seat.Group{ID: kg.Group, State: stateOpen, Members: add, Acts: []seat.Act{}, - Why: "its pull requests are not taken in yet"}) - } - } - return nil -} - -// recordedActs are the acts a record holds, each with its outcome when the forge bridge said one, ordered by id. -func recordedActs(r *Record) []seat.Act { - out := []seat.Act{} - for _, a := range r.Acts { - o := a.Owed - if o.ID == "" { - o = seat.Owed{ID: a.ID, Act: a.Act, Repository: a.Repository, Number: int64(a.Number), Head: a.Head} - } - act := seat.Act{Outcome: a.Outcome, Words: a.Words, Owed: o} - if a.Outcome != "" { - at := a.At - act.At = &at - } - out = append(out, act) - } - sort.Slice(out, func(i, j int) bool { return out[i].Owed.ID < out[j].Owed.ID }) - return out -} - // StalledLine is one record stalled: its open wait past its bound, or an act owed the forge unanswered past its. type StalledLine struct { // ID is the record's instance. diff --git a/modules/mesh-delivery-gate/files/settings.json b/modules/mesh-delivery-gate/files/settings.json index bff20f51c..63414735c 100644 --- a/modules/mesh-delivery-gate/files/settings.json +++ b/modules/mesh-delivery-gate/files/settings.json @@ -1,3 +1,4 @@ { - "record-retention": 90 + "record-retention": 90, + "untaken-bound": 10 } diff --git a/modules/mesh-delivery-gate/go.mod b/modules/mesh-delivery-gate/go.mod index 3bf41633a..1cfa2af70 100644 --- a/modules/mesh-delivery-gate/go.mod +++ b/modules/mesh-delivery-gate/go.mod @@ -3,14 +3,16 @@ module mesh-delivery-gate go 1.26.0 require ( + git.novox.be/novox/mesh-contracts/go/seats/nodeengine v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel v0.0.0-00010101000000-000000000000 - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view/viewstate v0.0.0-00010101000000-000000000000 @@ -38,12 +40,10 @@ require ( git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner v0.0.0-00010101000000-000000000000 // indirect - git.novox.be/novox/mesh-contracts/go/seats/nodeengine v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect - git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks v0.0.0-00010101000000-000000000000 // indirect git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds v0.0.0-00010101000000-000000000000 // indirect diff --git a/modules/mesh-delivery-gate/module.json b/modules/mesh-delivery-gate/module.json index ebddcb329..a6cb5797e 100644 --- a/modules/mesh-delivery-gate/module.json +++ b/modules/mesh-delivery-gate/module.json @@ -1,6 +1,7 @@ { "module": "mesh-delivery-gate", "version": "0.1", + "class": "core", "slug": "gate", "claims": [ { @@ -9,7 +10,6 @@ "serves": [ "deliveries", "show", - "groups", "source", "recovery", "stalled" @@ -18,27 +18,26 @@ ], "consumes": [ "mesh-delivery-forge-bridge.owed.ended", + "git.merge-called.*", + "mesh-delivery-forge-bridge.forge.*.*.*.head-moved", "mesh-delivery-indexer.take-in.taken", - "git.pull-updated", - "git.pull-merged", - "git.pull-closed", + "mesh-pipeline-runner.pipeline-started.*.*", + "mesh-pipeline-runner.pipeline-ended.*.*", + "mesh-pipeline-runner.wait-held.*.*", + "mesh-pipeline-runner.wait-ended.*.*", + "mesh-wants.wanted.*.*", + "mesh-wants.pipeline-wanted.*.*", + "node-engine.running.*.*", "mesh-catalog.registration-changed", - "mesh-delivery-forge-bridge.forge.*.*.merged", "mesh-conditions.findings-asked" ], - "emits": [ - "transition" - ], - "uses": [ - "operator-channel" - ], "requires": [ { "name": "records", "storage": "ledger", "template": "ledger", "options": { - "max-mib": 768 + "max-mib": 1024 }, "types": [ { @@ -47,15 +46,18 @@ "milestone": { "type": "string" }, + "source": { + "type": "integer" + }, + "call": { + "type": "string" + }, "heads": { "type": "object" }, "opened": { "type": "string" }, - "forge-made": { - "type": "boolean" - }, "form": { "type": "integer" }, @@ -95,40 +97,28 @@ "since": { "type": "string" }, - "revision": { - "type": "string" - }, - "half": { - "type": "string" - }, "branch": { "type": "string" }, "ended": { "type": "object" }, - "id": { - "type": "string" - }, - "act": { - "type": "string" - }, - "repository": { - "type": "string" - }, - "number": { - "type": "integer" - }, - "head": { - "type": "string" - }, - "words": { - "type": "string" - }, "recovery": { "type": "object" }, - "owed": { + "movers": { + "type": "integer" + }, + "merge-called": { + "type": "string" + }, + "delivery-time": { + "type": "string" + }, + "class": { + "type": "string" + }, + "phases": { "type": "object" } }, @@ -138,10 +128,13 @@ "effect": "set-fields", "fields": [ "milestone", + "branch", + "source", + "call", "heads", "opened", - "forge-made", - "form" + "form", + "merge-called" ], "sequence": true }, @@ -162,6 +155,106 @@ ], "sequence": true }, + { + "name": "movers", + "effect": "set-fields", + "fields": [ + "movers" + ], + "sequence": true + }, + { + "name": "phases", + "effect": "set-fields", + "fields": [ + "phases" + ], + "sequence": true + }, + { + "name": "away", + "effect": "set-entry", + "fields": [ + "node", + "since" + ], + "into": "away", + "key": "node" + }, + { + "name": "back", + "effect": "remove", + "into": "away", + "key": "node" + }, + { + "name": "end", + "effect": "set-fields", + "fields": [ + "ended", + "delivery-time", + "class" + ], + "sequence": true + } + ] + }, + { + "name": "mover", + "schema": { + "record": { + "type": "string" + }, + "module": { + "type": "string" + }, + "pipeline": { + "type": "string" + }, + "version": { + "type": "string" + }, + "key": { + "type": "string" + }, + "fingerprint": { + "type": "string" + }, + "node": { + "type": "string" + }, + "step": { + "type": "string" + }, + "outcome": { + "type": "string" + }, + "why": { + "type": "string" + }, + "at": { + "type": "string" + }, + "event": { + "type": "string" + }, + "class": { + "type": "string" + } + }, + "operations": [ + { + "name": "mover", + "effect": "set-fields", + "fields": [ + "record", + "module", + "class", + "pipeline", + "version" + ], + "sequence": true + }, { "name": "entry", "effect": "set-entry", @@ -192,44 +285,57 @@ "into": "outcomes", "key": "key", "sequence": true - }, + } + ], + "indexes": [ { - "name": "away", - "effect": "set-entry", - "fields": [ - "node", - "since" - ], - "into": "away", - "key": "node" + "name": "movers", + "on": [ + "record" + ] + } + ] + }, + { + "name": "act", + "schema": { + "record": { + "type": "string" }, - { - "name": "back", - "effect": "remove", - "into": "away", - "key": "node" + "id": { + "type": "string" }, - { - "name": "pin", - "effect": "set-entry", - "fields": [ - "revision", - "half", - "branch" - ], - "into": "pinned", - "key": "revision" + "act": { + "type": "string" }, - { - "name": "free", - "effect": "remove", - "into": "pinned", - "key": "revision" + "repository": { + "type": "string" }, + "number": { + "type": "integer" + }, + "head": { + "type": "string" + }, + "outcome": { + "type": "string" + }, + "words": { + "type": "string" + }, + "at": { + "type": "string" + }, + "owed": { + "type": "object" + } + }, + "operations": [ { "name": "act", - "effect": "set-entry", + "effect": "set-fields", "fields": [ + "record", "id", "act", "repository", @@ -240,17 +346,15 @@ "at", "owed" ], - "into": "acts", - "key": "id", "sequence": true - }, + } + ], + "indexes": [ { - "name": "end", - "effect": "set-fields", - "fields": [ - "ended" - ], - "sequence": true + "name": "acts", + "on": [ + "record" + ] } ] }, @@ -282,57 +386,24 @@ "key": "instance" } ] - }, - { - "name": "switch", - "schema": { - "fingerprint": { - "type": "string" - }, - "at": { - "type": "string" - } - }, - "operations": [ - { - "name": "done", - "effect": "set-fields", - "fields": [ - "fingerprint", - "at" - ] - } - ] } ] }, { - "name": "deliveries", - "storage": "key-value", - "template": "state" - }, - { - "name": "groups", - "storage": "key-value", - "template": "state" - }, - { - "name": "owed", + "name": "heads", "storage": "key-value", "template": "state", "options": { - "history": 5 + "max-mib": 8 } }, - { - "name": "conditions", - "storage": "key-value", - "template": "state" - }, { "name": "findings", "storage": "key-value", - "template": "state" + "template": "state", + "options": { + "max-mib": 8 + } }, { "name": "finding-events", @@ -345,30 +416,27 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ], "packages": { + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks": "0.3", "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg": "0.1" }, "invokes": [ "seat:git.branch", - "seat:git.open-pulls", - "seat:git.pull", + "seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", "seat:mesh-wants.entry", "seat:node-engine.composition" ], "state": [ - { - "name": "merges", - "history": 10 - }, { "name": "source", - "history": 64 + "history": 64, + "max-mib": 8 } ], "capabilities": [ @@ -378,14 +446,19 @@ "tools": [ "delivery_status", "gate_consumer", + "gate_head_take", + "gate_heads", "gate_record", "gate_record_end", "gate_record_repair", "gate_records", "gate_source", "gate_source_again", - "gate_source_follow", - "gate_source_start" + "gate_source_seed", + "gate_source_start", + "gate_times", + "mesh-delivery-gate_state_keep", + "mesh-delivery-gate_state_prune_now" ], "config": { "record-retention": { @@ -395,6 +468,45 @@ "maximum": 3650, "trusted": false, "default": 90 + }, + "untaken-bound": { + "type": "number", + "description": "minutes a watched branch's head may stand that no merge call delivered before the gate raises head-untaken (design 47 H §740); the gate keeps one deadline timer for the earliest.", + "minimum": 1, + "trusted": false, + "default": 10 + }, + "budget-core": { + "type": "string", + "description": "The budget of a delivery that moves a core module, from merge-called to the last running of its movers, as a duration such as 10m (ADR 0282; design 47 H2 §810): gate_times names every delivery over it, and the self-check raises over-budget for it.", + "trusted": false, + "runtime": true, + "default": "10m" + }, + "budget-leaf": { + "type": "string", + "description": "The budget of a delivery that moves only leaf modules, as a duration such as 3m (ADR 0304; design 47 H2 §810).", + "trusted": false, + "runtime": true, + "default": "3m" + }, + "prune-mark": { + "type": "number", + "description": "The fill of the gate's state heads, in percent of its cap, past which the gate prunes it at its own write, oldest first (design 47 H2 §812): below the bus module's raise mark of 75 %.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 70 + }, + "prune-target": { + "type": "number", + "description": "The fill, in percent of the cap, a prune of the gate's state heads takes it down to (design 47 H2 §812); below prune-mark.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 50 } }, "resources": [ @@ -411,7 +523,8 @@ "path": "${dir:state}/settings.json", "mode": "0600", "takes-config": [ - "record-retention" + "record-retention", + "untaken-bound" ], "merge": "json", "template": "files/settings.json" diff --git a/modules/mesh-files/module.json b/modules/mesh-files/module.json index c43c13d49..4b75b5f33 100644 --- a/modules/mesh-files/module.json +++ b/modules/mesh-files/module.json @@ -1,6 +1,7 @@ { "module": "mesh-files", "version": "0.1", + "class": "core", "claims": [ { "name": "node-files", diff --git a/modules/mesh-hand-acts/module.json b/modules/mesh-hand-acts/module.json index ef8bb16a9..6131b4e2e 100644 --- a/modules/mesh-hand-acts/module.json +++ b/modules/mesh-hand-acts/module.json @@ -1,6 +1,7 @@ { "module": "mesh-hand-acts", "version": "0.1", + "class": "core", "runs-as": "mesh-hand-acts", "claims": [ { diff --git a/modules/mesh-healers/cmd/mesh-healers/manifest_test.go b/modules/mesh-healers/cmd/mesh-healers/manifest_test.go index e1c1989cf..efb620b7a 100644 --- a/modules/mesh-healers/cmd/mesh-healers/manifest_test.go +++ b/modules/mesh-healers/cmd/mesh-healers/manifest_test.go @@ -84,8 +84,8 @@ func TestTheManifestSaysWhatTheCodeDoes(t *testing.T) { got := map[string]string{} for _, r := range m.Requires { got[r.Name] = r.Template - if r.Name == "finding-events" && (len(r.Options["events"].([]any)) != 3 || r.Options["max-age-days"] != 7.0 || r.Options["max-mib"] != 16.0) { - t.Errorf("the finding stream's options are %v, want the three finding events, 7 days and 16 MiB", r.Options) + if r.Name == "finding-events" && (len(r.Options["events"].([]any)) != 3 || r.Options["max-age-days"] != 7.0 || r.Options["max-mib"] != 8.0) { // H-A-411 (1): 8 MiB on every module that binds it + t.Errorf("the finding stream's options are %v, want the three finding events, 7 days and 8 MiB", r.Options) } } if got[FindingsState] != "state" || got["finding-events"] != "events" || len(m.Streams) != 0 { diff --git a/modules/mesh-healers/module.json b/modules/mesh-healers/module.json index ccfb3216d..930c16ec9 100644 --- a/modules/mesh-healers/module.json +++ b/modules/mesh-healers/module.json @@ -1,6 +1,7 @@ { "module": "mesh-healers", "version": "0.1", + "class": "core", "runs-as": "mesh-healers", "claims": [ { @@ -93,7 +94,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/mesh-issues/cmd/mesh-issues/core_test.go b/modules/mesh-issues/cmd/mesh-issues/core_test.go index 237801475..49b3527ea 100644 --- a/modules/mesh-issues/cmd/mesh-issues/core_test.go +++ b/modules/mesh-issues/cmd/mesh-issues/core_test.go @@ -13,7 +13,7 @@ func TestIsCoreNamesTheBuildModulesAndTheDeliveryParts(t *testing.T) { for _, e := range []string{ "mesh-catalog modules/mesh-build-go", "mesh-catalog modules/mesh-build-node", "mesh-catalog modules/mesh-build-image", "mesh-catalog modules/mesh-build-go/cmd/mesh-build-go", - "mesh-delivery", "mesh-delivery modules/mesh-delivery-checker", "mesh-catalog modules/mesh-delivery-gate", + "mesh-delivery", "mesh-catalog modules/mesh-delivery-gate", "mesh-catalog modules/nats", "mesh-catalog modules/gitea", "mesh-sdk", } { if !IsCore([]string{e}) { @@ -43,5 +43,16 @@ func TestNoOwnerNamesBuildAgent(t *testing.T) { if strings.Contains(o, "build-agent") { t.Errorf("the owner %q is registered: build-agent is gone (ADR 0524 §5)", o) } + if strings.Contains(o, "mesh-delivery-checker") { + t.Errorf("the owner %q is registered: the checker is gone whole (design 47 H §764)", o) + } + } + // The manifest's default owners name it no more either. + raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "mesh-delivery-checker") { + t.Error("the manifest names mesh-delivery-checker: the checker is gone whole (design 47 H §764)") } } diff --git a/modules/mesh-issues/cmd/mesh-issues/manifest_test.go b/modules/mesh-issues/cmd/mesh-issues/manifest_test.go index 9cd24d027..9588b3ed6 100644 --- a/modules/mesh-issues/cmd/mesh-issues/manifest_test.go +++ b/modules/mesh-issues/cmd/mesh-issues/manifest_test.go @@ -264,7 +264,7 @@ func TestEveryCodeModuleOfTheCatalogueIsAnOwner(t *testing.T) { } // 1815/AC2: the delivery repository's modules cannot ride on its repository entry (owns refuses a folder // of a repository that is registered only as a whole), so each is named. - for _, m := range []string{"builder", "checker", "indexer"} { + for _, m := range []string{"builder", "indexer"} { // the checker went whole (design 47 H §764) if Owners(s.Owners).owns("mesh-delivery modules/mesh-delivery-"+m) == "" { t.Errorf("mesh-delivery-%s is not an owner", m) } diff --git a/modules/mesh-issues/files/settings.json b/modules/mesh-issues/files/settings.json index b833058f6..8c2f04378 100644 --- a/modules/mesh-issues/files/settings.json +++ b/modules/mesh-issues/files/settings.json @@ -147,7 +147,6 @@ "mesh-catalog modules/zsh-syntax-highlighting", "mesh-delivery", "mesh-delivery modules/mesh-delivery-builder", - "mesh-delivery modules/mesh-delivery-checker", "mesh-delivery modules/mesh-delivery-forge-bridge", "mesh-delivery modules/mesh-delivery-indexer", "mesh-delivery modules/mesh-delivery-teller", diff --git a/modules/mesh-issues/module.json b/modules/mesh-issues/module.json index ebf31730c..ec6bdc8f8 100644 --- a/modules/mesh-issues/module.json +++ b/modules/mesh-issues/module.json @@ -1,6 +1,7 @@ { "module": "mesh-issues", "version": "0.1", + "class": "core", "slug": "issues", "seats": [ { @@ -259,7 +260,6 @@ "mesh-catalog modules/zsh-syntax-highlighting", "mesh-delivery", "mesh-delivery modules/mesh-delivery-builder", - "mesh-delivery modules/mesh-delivery-checker", "mesh-delivery modules/mesh-delivery-forge-bridge", "mesh-delivery modules/mesh-delivery-indexer", "mesh-delivery modules/mesh-delivery-teller", diff --git a/modules/mesh-knowledge/cmd/mesh-knowledge/manifest_test.go b/modules/mesh-knowledge/cmd/mesh-knowledge/manifest_test.go index ac295944b..3a7852b72 100644 --- a/modules/mesh-knowledge/cmd/mesh-knowledge/manifest_test.go +++ b/modules/mesh-knowledge/cmd/mesh-knowledge/manifest_test.go @@ -84,9 +84,15 @@ func TestItDeclaresAndHoldsTheKnowledgeBaseSeatOnceForTheMesh(t *testing.T) { } if !reflect.DeepEqual(m.Invokes, []string{"seat:issue-tracker.reserve", "claude-code.claude_code_judge", "records.records_status", "records.records_list", "records.records_read", "seat:operator-channel.notify", "seat:issue-tracker.list", "seat:issue-tracker.get", - "seat:issue-tracker.milestones", "seat:issue-tracker.changes", "seat:mesh-delivery.deliveries", "seat:mesh-delivery.show", "seat:mesh-delivery.groups", "seat:operator-channel.asks", "seat:mesh-hand-acts.hand-act"}) { + "seat:issue-tracker.milestones", "seat:issue-tracker.changes", "seat:mesh-delivery.deliveries", "seat:mesh-delivery.show", "seat:operator-channel.asks", "seat:mesh-hand-acts.hand-act"}) { t.Fatalf("invokes %v", m.Invokes) } + // The overview keeps no delivery block (design 47 H, H-A-125): it hears no merge, transition or pipeline's end. + for _, e := range m.Consumes { + if strings.HasPrefix(e, "git.") || strings.HasPrefix(e, "mesh-delivery") || strings.HasPrefix(e, "mesh-pipeline-runner.") { + t.Errorf("it consumes %s, and the overview shows no deliveries", e) + } + } src := "" for _, f := range []string{"main.go", "hq.go", "progress.go", "progress_since.go", "milestones.go", "overview.go", "tools.go"} { src += readFile(t, f) @@ -282,7 +288,7 @@ func TestItAsksForItsBusStateInTheTypedForm(t *testing.T) { // overviewConsumes are the events the overview page hears, in the order the manifest lists them. func overviewConsumes() []string { var out []string - for _, s := range []string{SourceTracker, SourceDelivery, SourceAsks} { + for _, s := range []string{SourceTracker, SourceAsks} { out = append(out, OverviewEvents[s]...) } return out diff --git a/modules/mesh-knowledge/cmd/mesh-knowledge/overview.go b/modules/mesh-knowledge/cmd/mesh-knowledge/overview.go index 88bbf9a39..0a8985729 100644 --- a/modules/mesh-knowledge/cmd/mesh-knowledge/overview.go +++ b/modules/mesh-knowledge/cmd/mesh-knowledge/overview.go @@ -2,9 +2,9 @@ package main // The overview page (novox/hq to-be 55 §11, ADR 0616): one read-only page for the operator with three blocks: every design in // progress with its milestones and their issues; the decisions and research efforts accepted in the last seven days and those -// waiting; and what waits on the operator (records waiting for an Approve, the operator channel's open asks, the delivery -// groups waiting). Built from mesh paths alone: the module's own ledger, and three other modules' verbs for the first view and -// their events after it. It never polls: a source is asked again only when it is marked unanswered, on a bounded backoff. +// waiting; and what waits on the operator (records waiting for an Approve, the operator channel's open asks). No delivery +// block: the deliveries are another module's state, read through the status view (design 47 H, H-A-125). Built from mesh +// paths alone: the module's own ledger, and two other modules' verbs for the first view and their events after it. It never polls: a source is asked again only when it is marked unanswered, on a bounded backoff. import ( "encoding/json" @@ -19,24 +19,21 @@ import ( // The sources of the page, besides the module's own ledger. const ( - SourceTracker = "issue-tracker" - SourceDelivery = "mesh-delivery" - SourceAsks = "operator-channel" + SourceTracker = "issue-tracker" + SourceAsks = "operator-channel" ) // The verbs of the first view, and the events that keep each source current. const ( TrackerMilestonesVerb = "seat:issue-tracker.milestones" TrackerListVerb = "seat:issue-tracker.list" - DeliveryGroupsVerb = "seat:mesh-delivery.groups" AsksVerb = "seat:operator-channel.asks" ) // OverviewEvents are the events the page consumes, by source, as the manifest declares them. var OverviewEvents = map[string][]string{ - SourceTracker: {"mesh-issues.opened", "mesh-issues.moved", "mesh-issues.milestone-set", "mesh-issues.milestone-moved"}, - SourceDelivery: {"git.pull-merged", "mesh-delivery-gate.transition", "mesh-pipeline-runner.group-ended"}, - SourceAsks: {"messenger.offered", "messenger.closed"}, + SourceTracker: {"mesh-issues.opened", "mesh-issues.moved", "mesh-issues.milestone-set", "mesh-issues.milestone-moved"}, + SourceAsks: {"messenger.offered", "messenger.closed"}, } // The unanswered marks: a verb that did not answer, or a subscription that missed its heartbeat. @@ -123,7 +120,6 @@ type OverviewModel struct { type OperatorBlock struct { Records []RecordRow `json:"records"` Asks []askRow `json:"asks"` - Groups []groupRow `json:"delivery-groups"` } // Overview is the page's model in memory, kept by events. @@ -136,7 +132,6 @@ type Overview struct { mu sync.Mutex milestones map[string]trackerMilestone issues map[int]trackerRow - groups map[string]groupRow asks map[string]askRow state map[string]*SourceState rebuilt time.Time @@ -147,8 +142,8 @@ type Overview struct { // NewOverview is a model with no source answered: Start asks each source's verb once. func NewOverview(ask SeatAsk, records func() ([]*Entry, error), now func() time.Time) *Overview { o := &Overview{Ask: ask, Records: records, Now: now, milestones: map[string]trackerMilestone{}, issues: map[int]trackerRow{}, - groups: map[string]groupRow{}, asks: map[string]askRow{}, state: map[string]*SourceState{}, verbCalls: map[string]int{}} - for _, s := range []string{SourceTracker, SourceDelivery, SourceAsks} { + asks: map[string]askRow{}, state: map[string]*SourceState{}, verbCalls: map[string]int{}} + for _, s := range []string{SourceTracker, SourceAsks} { o.state[s] = &SourceState{Name: s} } return o @@ -234,19 +229,6 @@ func (o *Overview) rebuildLocked(source string) error { for _, r := range rows { o.issues[r.Number] = r } - case SourceDelivery: - raw, err := call(DeliveryGroupsVerb, map[string]any{}) - if err != nil { - return fail(err.Error()) - } - var gs []groupRow - if err := rowsOf(raw, &gs, "groups"); err != nil { - return fail("groups answered something else: " + err.Error()) - } - o.groups = map[string]groupRow{} - for _, g := range gs { - o.groups[g.ID] = g - } case SourceAsks: raw, err := call(AsksVerb, map[string]any{}) if err != nil { @@ -279,7 +261,7 @@ func (o *Overview) sourceNames() []string { // Start is the first view: every source's verb asked once. A verb that does not answer marks its source. func (o *Overview) Start() { - for _, s := range []string{SourceTracker, SourceDelivery, SourceAsks} { + for _, s := range []string{SourceTracker, SourceAsks} { _ = o.Rebuild(s) } } @@ -339,16 +321,11 @@ func (o *Overview) Heard(source, event string, body json.RawMessage) { Number int `json:"number"` Status string `json:"status"` To string `json:"to"` - State string `json:"state"` Title string `json:"title"` Design int `json:"design"` ID string `json:"id"` - Group string `json:"group"` - Branch string `json:"branch"` Outcome string `json:"outcome"` Issues []int `json:"issues"` - Members []string `json:"members"` - Why string `json:"why"` Key string `json:"key"` Asker string `json:"asker"` Headline string `json:"headline"` @@ -381,22 +358,6 @@ func (o *Overview) Heard(source, event string, body json.RawMessage) { m.Status = firstNonEmpty(f.To, f.Status, m.Status) o.milestones[k] = m } - case SourceDelivery: - id := firstNonEmpty(f.Group, f.ID) - switch name { - case "pull-merged": - // A merged pull request leaves the group named by its head branch (a group's id is its branch name): it waits for - // the operator no longer (design 47 G §431). - delete(o.groups, f.Branch) - case "transition": - if g, ok := o.groups[id]; ok { - g.State = firstNonEmpty(f.To, f.State, g.State) - g.Why = firstNonEmpty(f.Why, g.Why) - o.groups[id] = g - } - case "group-ended": - delete(o.groups, id) - } case SourceAsks: switch name { case "offered": @@ -481,12 +442,6 @@ func (o *Overview) Model() (*OverviewModel, error) { m.Operator.Asks = append(m.Operator.Asks, a) } sort.Slice(m.Operator.Asks, func(i, j int) bool { return m.Operator.Asks[i].Key < m.Operator.Asks[j].Key }) - for _, g := range o.groups { - if g.State != "merged" { - m.Operator.Groups = append(m.Operator.Groups, g) - } - } - sort.Slice(m.Operator.Groups, func(i, j int) bool { return m.Operator.Groups[i].ID < m.Operator.Groups[j].ID }) for _, n := range o.sourceNames() { m.Sources = append(m.Sources, *o.state[n]) } diff --git a/modules/mesh-knowledge/cmd/mesh-knowledge/overview_test.go b/modules/mesh-knowledge/cmd/mesh-knowledge/overview_test.go index 646ac6f92..37023e142 100644 --- a/modules/mesh-knowledge/cmd/mesh-knowledge/overview_test.go +++ b/modules/mesh-knowledge/cmd/mesh-knowledge/overview_test.go @@ -25,7 +25,6 @@ func newOverviewWorld(t *testing.T) *overviewWorld { w := &overviewWorld{now: time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC), fail: map[string]bool{}, answers: map[string]string{ TrackerMilestonesVerb: `{"milestones":[{"design":47,"id":"1","outcome":"A merge is never dropped","status":"open","issues":[973,525]},{"design":47,"id":"2","outcome":"Done thing","status":"done","issues":[1]}]}`, TrackerListVerb: `[{"number":973,"title":"The window","status":"fixing"},{"number":525,"title":"The queue","status":"open"}]`, - DeliveryGroupsVerb: `[{"id":"fix/a","state":"held","why":"a member is held","members":["x@1"]},{"id":"fix/b","state":"checking","members":["y@2"]}]`, AsksVerb: `{"asks":[{"key":"mesh-knowledge.1","asker":"mesh-knowledge","headline":"Approve ADR 0301","state":"open","offered_on":["telegram"]},{"key":"ask-0","asker":"x","headline":"old","state":"answered"}]}`, }} w.o = NewOverview(func(key string, body any) (json.RawMessage, error) { @@ -45,8 +44,8 @@ func recordEntry(n int, status, date string, accepted time.Time, mut func(*Recor return &Entry{Current: r, CurrentVersion: 1, Versions: 1} } -// The page's model (ADR 0616 §1-3, AC P1): three blocks built from the ledger, the tracker's milestones and issues, the delivery -// groups and the operator channel's asks; events change the blocks and ask no verb; a record accepted eight days before the +// The page's model (ADR 0616 §1-3, AC P1): three blocks built from the ledger, the tracker's milestones and issues and the +// operator channel's asks, and no delivery block (design 47 H, H-A-125); events change the blocks and ask no verb; a record accepted eight days before the // answer is not in the seven-day block, with no event between. func TestThePageModelHasThreeBlocksKeptByEventsAndAsksNoVerbAgain(t *testing.T) { w := newOverviewWorld(t) @@ -68,28 +67,25 @@ func TestThePageModelHasThreeBlocksKeptByEventsAndAsksNoVerbAgain(t *testing.T) t.Fatalf("the design block: %+v", m.Designs) } if len(m.Accepted) != 2 || len(m.Waiting) != 2 || len(m.Operator.Records) != 1 || m.Operator.Records[0].Record != "ADR 0303" || - len(m.Operator.Asks) != 1 || m.Operator.Asks[0].Key != "mesh-knowledge.1" || len(m.Operator.Groups) != 2 { + len(m.Operator.Asks) != 1 || m.Operator.Asks[0].Key != "mesh-knowledge.1" || len(m.Sources) != 2 { t.Fatalf("%+v", m) } asked := map[string]int{} - for _, v := range []string{TrackerMilestonesVerb, TrackerListVerb, DeliveryGroupsVerb, AsksVerb} { + for _, v := range []string{TrackerMilestonesVerb, TrackerListVerb, AsksVerb} { asked[v] = w.o.Calls(v) } // Events change the blocks. - w.o.Heard(SourceDelivery, "git.pull-merged", json.RawMessage(`{"repository":"novox/y","number":2,"branch":"fix/b"}`)) - w.o.Heard(SourceDelivery, "mesh-delivery-gate.transition", json.RawMessage(`{"group":"fix/a","to":"approved"}`)) w.o.Heard(SourceAsks, "messenger.offered", json.RawMessage(`{"id":"2","asker":"mesh-delivery","headline":"Approve the group","channels":["telegram"]}`)) w.o.Heard(SourceTracker, "mesh-issues.opened", json.RawMessage(`{"number":1999,"title":"New","status":"open"}`)) w.o.Heard(SourceTracker, "mesh-issues.milestone-moved", json.RawMessage(`{"design":47,"id":"1","to":"done","issues":[973,525,1999]}`)) m, _ = w.o.Model() - if len(m.Operator.Groups) != 1 || m.Operator.Groups[0].State != "approved" || len(m.Operator.Asks) != 2 || len(m.Designs) != 0 { + if len(m.Operator.Asks) != 2 || len(m.Designs) != 0 { t.Fatalf("after the events: %+v", m) } - w.o.Heard(SourceDelivery, "mesh-pipeline-runner.group-ended", json.RawMessage(`{"group":"fix/a","branch":"main","outcome":"passed"}`)) w.o.Heard(SourceAsks, "messenger.closed", json.RawMessage(`{"id":"1","asker":"mesh-knowledge","how":"answered"}`)) m, _ = w.o.Model() - if len(m.Operator.Groups) != 0 || len(m.Operator.Asks) != 1 || m.Operator.Asks[0].Key != "mesh-delivery.2" { - t.Fatalf("after the group ended and the ask closed: %+v", m.Operator) + if len(m.Operator.Asks) != 1 || m.Operator.Asks[0].Key != "mesh-delivery.2" { + t.Fatalf("after the ask closed: %+v", m.Operator) } for v, n := range asked { if w.o.Calls(v) != n { @@ -109,56 +105,56 @@ func TestThePageModelHasThreeBlocksKeptByEventsAndAsksNoVerbAgain(t *testing.T) // next event; the model as a tool equals the page's model; the re-read tool asks one source and records the hand act. func TestASourceThatDoesNotAnswerIsSaidAndAskedAgainOnABackoff(t *testing.T) { w := newOverviewWorld(t) - w.fail[DeliveryGroupsVerb] = true + w.fail[AsksVerb] = true w.o.Start() m, _ := w.o.Model() - var delivery SourceState + var asks SourceState for _, s := range m.Sources { - if s.Name == SourceDelivery { - delivery = s + if s.Name == SourceAsks { + asks = s } } - if delivery.Answered || delivery.Mark == nil || delivery.Mark.Cause != MarkVerb || len(m.Operator.Groups) != 0 || !strings.Contains(delivery.Mark.Why, "no answer in time") { - t.Fatalf("%+v", delivery) + if asks.Answered || asks.Mark == nil || asks.Mark.Cause != MarkVerb || len(m.Operator.Asks) != 0 || !strings.Contains(asks.Mark.Why, "no answer in time") { + t.Fatalf("%+v", asks) } if len(m.Designs) != 1 { t.Fatalf("another source's block was lost: %+v", m.Designs) } // Asked again on the backoff alone: 10 s, then doubling, at most 5 minutes; no other source is asked. - calls := w.o.Calls(DeliveryGroupsVerb) + calls := w.o.Calls(AsksVerb) if got := w.o.Due(); len(got) != 0 { t.Fatalf("asked before the backoff ran out: %v", got) } var waits []time.Duration for i := 0; i < 8; i++ { before := w.now - w.now = w.o.state[SourceDelivery].Mark.Next + w.now = w.o.state[SourceAsks].Mark.Next waits = append(waits, w.now.Sub(before)) - if got := w.o.Due(); len(got) != 1 || got[0] != SourceDelivery { + if got := w.o.Due(); len(got) != 1 || got[0] != SourceAsks { t.Fatalf("%v", got) } } - if waits[0] != BackoffFrom || waits[1] != 2*BackoffFrom || waits[7] != BackoffMost || w.o.Calls(DeliveryGroupsVerb) != calls+8 || w.o.Calls(AsksVerb) != 1 { - t.Fatalf("waits %v, delivery asked %d, asks asked %d", waits, w.o.Calls(DeliveryGroupsVerb), w.o.Calls(AsksVerb)) + if waits[0] != BackoffFrom || waits[1] != 2*BackoffFrom || waits[7] != BackoffMost || w.o.Calls(AsksVerb) != calls+8 || w.o.Calls(TrackerListVerb) != 1 { + t.Fatalf("waits %v, asks asked %d, tracker asked %d", waits, w.o.Calls(AsksVerb), w.o.Calls(TrackerListVerb)) } // Its first answer rebuilds the block and clears the mark. - w.fail[DeliveryGroupsVerb] = false - w.now = w.o.state[SourceDelivery].Mark.Next + w.fail[AsksVerb] = false + w.now = w.o.state[SourceAsks].Mark.Next w.o.Due() m, _ = w.o.Model() - if len(w.o.Unanswered()) != 0 || len(m.Operator.Groups) != 2 { + if len(w.o.Unanswered()) != 0 || len(m.Operator.Asks) != 1 { t.Fatalf("%+v", m) } // A subscription that goes silent marks the source from the subscription and asks nothing while it is silent. asked := w.o.Calls(AsksVerb) w.now = w.now.Add(HeartbeatWithin + time.Second) - if got := w.o.Silent(); len(got) != 3 { + if got := w.o.Silent(); len(got) != 2 { t.Fatalf("%v", got) } if got := w.o.Due(); len(got) != 0 || w.o.Calls(AsksVerb) != asked { t.Fatalf("a silent subscription was asked: %v", got) } - if u := w.o.Unanswered(); len(u) != 3 || u[0].Mark.Cause != MarkSubscription { + if u := w.o.Unanswered(); len(u) != 2 || u[0].Mark.Cause != MarkSubscription { t.Fatalf("%+v", u) } // Its next event (or heartbeat) makes the module ask the verb once, and that answer clears the mark. @@ -167,19 +163,19 @@ func TestASourceThatDoesNotAnswerIsSaidAndAskedAgainOnABackoff(t *testing.T) { t.Fatalf("asked %d, mark %+v", w.o.Calls(AsksVerb), w.o.state[SourceAsks].Mark) } // An unanswered verb then turns the mark into one from the verb. - w.fail[DeliveryGroupsVerb] = true - w.o.Heard(SourceDelivery, "", nil) - if mk := w.o.state[SourceDelivery].Mark; mk == nil || mk.Cause != MarkVerb { + w.fail[TrackerMilestonesVerb] = true + w.o.Heard(SourceTracker, "", nil) + if mk := w.o.state[SourceTracker].Mark; mk == nil || mk.Cause != MarkVerb { t.Fatalf("%+v", mk) } // The runtime's word on the module's consumer (stdio.OnHeartbeat): a missed heartbeat marks every subscribed source // at once, before the bound passes, with the runtime's why; the next beat asks each verb once and clears the marks. - w.fail[DeliveryGroupsVerb] = false - w.now = w.o.state[SourceDelivery].Mark.Next + w.fail[TrackerMilestonesVerb] = false + w.now = w.o.state[SourceTracker].Mark.Next w.o.Due() asked = w.o.Calls(AsksVerb) w.o.Beat(stdio.Heartbeat{At: w.now, Missed: true, Why: "the bus's heartbeat stopped arriving"}) - if u := w.o.Unanswered(); len(u) != 3 || u[0].Mark.Cause != MarkSubscription || !strings.Contains(u[0].Mark.Why, "stopped arriving") { + if u := w.o.Unanswered(); len(u) != 2 || u[0].Mark.Cause != MarkSubscription || !strings.Contains(u[0].Mark.Why, "stopped arriving") { t.Fatalf("a missed heartbeat marked %+v", u) } w.o.Beat(stdio.Heartbeat{At: w.now}) @@ -218,12 +214,12 @@ func TestThePagesModelIsAToolAndItsRereadIsAHandAct(t *testing.T) { } // The re-read asks the one source and no other, and records itself. before := map[string]int{} - for _, v := range []string{TrackerListVerb, DeliveryGroupsVerb, AsksVerb} { + for _, v := range []string{TrackerListVerb, AsksVerb} { before[v] = w.o.Calls(v) } w.fail[AsksVerb] = true res, err := callTool(t, tools, RereadTool, map[string]any{"source": SourceAsks, "why": "the page showed it stale"}) - if err != nil || res["answered"] != false || w.o.Calls(AsksVerb) != before[AsksVerb]+1 || w.o.Calls(DeliveryGroupsVerb) != before[DeliveryGroupsVerb] || w.o.Calls(TrackerListVerb) != before[TrackerListVerb] { + if err != nil || res["answered"] != false || w.o.Calls(AsksVerb) != before[AsksVerb]+1 || w.o.Calls(TrackerListVerb) != before[TrackerListVerb] { t.Fatalf("%v %v", err, res) } if len(acts) != 1 || acts[0] != "seat:mesh-hand-acts.hand-act" { diff --git a/modules/mesh-knowledge/cmd/mesh-knowledge/page.go b/modules/mesh-knowledge/cmd/mesh-knowledge/page.go index 2279a37ae..bd73ff881 100644 --- a/modules/mesh-knowledge/cmd/mesh-knowledge/page.go +++ b/modules/mesh-knowledge/cmd/mesh-knowledge/page.go @@ -88,13 +88,11 @@ code{font-size:.9em}.src{display:inline-block;margin-right:1rem} {{if .Waiting}}
    {{range .Waiting}}
  • {{.Record}}: {{.Title}} waits for {{.Waits}}
  • {{end}}
{{else}}

None.

{{end}}

Waiting on you

-{{range .Sources}}{{if and (eq .Name "operator-channel") (not .Answered)}}

The operator channel does not answer: the asks below are not complete (last answer {{clock .Last}}).

{{end}}{{if and (eq .Name "mesh-delivery") (not .Answered)}}

Delivery does not answer: the groups below are not complete (last answer {{clock .Last}}).

{{end}}{{end}} +{{range .Sources}}{{if and (eq .Name "operator-channel") (not .Answered)}}

The operator channel does not answer: the asks below are not complete (last answer {{clock .Last}}).

{{end}}{{end}}

Records waiting for your Approve

{{if .Operator.Records}}
    {{range .Operator.Records}}
  • {{.Record}}: {{.Title}}
  • {{end}}
{{else}}

None.

{{end}}

Open asks

{{if .Operator.Asks}}
    {{range .Operator.Asks}}
  • {{.Headline}} from {{.Asker}}{{if .Offered}}, offered on {{join .Offered ", "}}{{end}}
  • {{end}}
{{else}}

None.

{{end}} -

Delivery groups waiting

-{{if .Operator.Groups}}
    {{range .Operator.Groups}}
  • {{.ID}} {{.State}}{{if .Why}}: {{.Why}}{{end}}
  • {{end}}
{{else}}

None.

{{end}} `)) // ServePage starts the overview: the model's first view, the events kept, the unanswered sources asked again on their backoff, diff --git a/modules/mesh-knowledge/cmd/mesh-knowledge/page_test.go b/modules/mesh-knowledge/cmd/mesh-knowledge/page_test.go index 1cb57e8ef..0532cc2f1 100644 --- a/modules/mesh-knowledge/cmd/mesh-knowledge/page_test.go +++ b/modules/mesh-knowledge/cmd/mesh-knowledge/page_test.go @@ -22,7 +22,7 @@ func TestThePageAnswersGetOnlyAndTheManifestKeepsItToThisMachine(t *testing.T) { h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) body := rec.Body.String() if rec.Code != 200 || !strings.Contains(body, "Design 47, milestone 1") || !strings.Contains(body, "ADR 0301") || !strings.Contains(body, "Approve ADR 0301") || - !strings.Contains(body, "fix/a") { + strings.Contains(body, "Delivery") { // no delivery block (design 47 H, H-A-125) t.Fatalf("%d\n%.600s", rec.Code, body) } if strings.Contains(body, "., or exactly person. — the same shapes mesh-mail's own trusted setting -// `grants` matches (modules/mesh-mail/cmd/mesh-mail/config.go, Grants.Allows), copied here in miniature (one -// flat list, not one per account) so mesh-mail-reader never imports mesh-mail. Nobody beyond the list is -// granted, a wildcard in the list is no entry, and an unproven caller never matches. The setting's default is -// ["mesh-mail-web"]. - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "strings" -) - -// Unproven is the caller the runtime proved nobody to be (stdio.Unproven; copied so this file reads alone). -const Unproven = "unproven" - -// Callers is the setting's shape once read: a flat list of entries. -type Callers []string - -// callersFile is the shape of the setting as the mesh writes it. -type callersFile struct { - Callers Callers `json:"callers"` -} - -// ReadCallers reads the callers setting. A setting that cannot be read allows nobody, and says why: a caller -// refused for a reason it can read is better than one let through because the setting was unreadable. -func ReadCallers(path string) (Callers, error) { - if path == "" { - return nil, errors.New("the module was started without its callers setting (MESH_MAIL_READER_CALLERS)") - } - raw, err := os.ReadFile(path) - if err != nil { - return nil, fmt.Errorf("the callers setting cannot be read: %w", err) - } - return ParseCallers(raw) -} - -// ParseCallers reads the callers setting's content. -func ParseCallers(raw []byte) (Callers, error) { - var f callersFile - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - if err := dec.Decode(&f); err != nil { - return nil, fmt.Errorf("the callers setting is not the module's: %v", err) - } - return f.Callers, nil -} - -// Allows says whether the caller may call a mail-reading verb: a bare module name (on any machine, as long as -// the caller is not person.), exactly ., or exactly person.. Nobody is granted by -// default, an unproven caller never, and a wildcard entry is no entry (mesh-mail's own Grants.Allows mirrored). -func (c Callers) Allows(caller string) bool { - if caller == "" || caller == Unproven { - return false - } - for _, entry := range c { - if entry == "" || strings.ContainsAny(entry, "*>") { - continue - } - if entry == caller { - return true - } - if !strings.Contains(entry, ".") { - if _, module, ok := strings.Cut(caller, "."); ok && module == entry && !strings.HasPrefix(caller, "person.") { - return true - } - } - } - return false -} - -// refuseCaller says why the caller is refused a mail-reading verb: the setting unread, or simply not named in it. -func refuseCaller(readErr error, caller string) error { - if readErr != nil { - return fmt.Errorf("refused: the setting callers cannot be read, so it allows nobody: %w", readErr) - } - return fmt.Errorf("refused: %s is not named in the setting callers; the operator grants it there", caller) -} diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/callers_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/callers_test.go deleted file mode 100644 index 19349c7f1..000000000 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/callers_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package main - -// 1426/AC4: the trusted setting callers, per shape, and an unproven caller. - -import "testing" - -func TestCallersAllowsEachShape(t *testing.T) { - c := Callers{"mesh-mail-web", "novox.mesh-knowledge", "person.jochen"} - cases := []struct { - caller string - want bool - }{ - {"mesh-mail-web", true}, // a bare module name - {"shanks.mesh-mail-web", true}, // ... on any machine - {"novox.mesh-knowledge", true}, // exactly . - {"shanks.mesh-knowledge", false}, // ... but not on another machine - {"person.jochen", true}, // exactly person. - {"person.someoneelse", false}, // ... but not another person - {"mesh-mail-notifier", false}, // not named at all - {"", false}, - {Unproven, false}, // 1426/AC4: unproven never - } - for _, c2 := range cases { - if got := c.Allows(c2.caller); got != c2.want { - t.Errorf("Allows(%q) = %v, want %v", c2.caller, got, c2.want) - } - } -} - -// 1426/AC4: a wildcard entry is no entry (mirrors mesh-mail's own Grants.Allows). -func TestCallersWildcardEntryIsNoEntry(t *testing.T) { - c := Callers{"*", "mesh-mail.>"} - if c.Allows("anything") { - t.Fatal("a wildcard entry granted a caller") - } -} - -func TestParseCallersDefault(t *testing.T) { - c, err := ParseCallers([]byte(`{"callers": ["mesh-mail-web"]}`)) - if err != nil { - t.Fatal(err) - } - if len(c) != 1 || c[0] != "mesh-mail-web" { - t.Fatalf("callers = %v", c) - } -} - -func TestReadCallersEmptyPath(t *testing.T) { - if _, err := ReadCallers(""); err == nil { - t.Fatal("no error reading callers with no path") - } -} diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/correct_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/correct_test.go index 7aed3a06b..4d55e48d0 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/correct_test.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/correct_test.go @@ -9,9 +9,7 @@ import ( func testBundle(store Store, caller string) *Bundle { return &Bundle{ - Caller: func(map[string]any) string { return caller }, - callersOverride: func() (Callers, error) { return Callers{"mesh-mail-web"}, nil }, - Store: func(context.Context) (Store, error) { return store, nil }, + Store: func(context.Context) (Store, error) { return store, nil }, } } diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/entries_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/entries_test.go index 00b6c071e..3270111a2 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/entries_test.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/entries_test.go @@ -115,9 +115,7 @@ func TestEntriesToolAnswersFilteredAndSorted(t *testing.T) { store.AddEntry(ctx, Entry{Account: "bob", Subject: "b", Mark: MarkMatters, DueDate: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), Date: time.Date(2026, 10, 2, 0, 0, 0, 0, time.UTC)}) b := &Bundle{ - Caller: func(map[string]any) string { return "mesh-mail-web" }, - callersOverride: func() (Callers, error) { return Callers{"mesh-mail-web"}, nil }, - Store: func(context.Context) (Store, error) { return store, nil }, + Store: func(context.Context) (Store, error) { return store, nil }, } out, err := b.entriesTool(map[string]any{"group": "newsletters"}) if err != nil { @@ -150,9 +148,7 @@ func TestGroupsToolAnswersLargestFirst(t *testing.T) { store.AddEntry(ctx, Entry{Group: big.ID}) b := &Bundle{ - Caller: func(map[string]any) string { return "mesh-mail-web" }, - callersOverride: func() (Callers, error) { return Callers{"mesh-mail-web"}, nil }, - Store: func(context.Context) (Store, error) { return store, nil }, + Store: func(context.Context) (Store, error) { return store, nil }, } out, err := b.groupsTool(map[string]any{}) if err != nil { @@ -172,9 +168,7 @@ func TestStatusToolAnswersHealthAndWeeklyMeasure(t *testing.T) { store.SetReaderHealth(ctx, ReaderHealth{Healthy: false, Cause: OutcomeRefused, Why: "holds no licence", Since: since}) b := &Bundle{ - Caller: func(map[string]any) string { return "mesh-mail-web" }, - callersOverride: func() (Callers, error) { return Callers{"mesh-mail-web"}, nil }, - Store: func(context.Context) (Store, error) { return store, nil }, + Store: func(context.Context) (Store, error) { return store, nil }, } out, err := b.statusTool(map[string]any{}) if err != nil { diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/health_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/health_test.go index bc0a71e1c..143fda8ac 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/health_test.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/health_test.go @@ -82,9 +82,7 @@ func TestHealthToolReadsTheKeptState(t *testing.T) { // A fresh Bundle, as a restarted process would build one, reading the same store. b := &Bundle{ - Caller: func(map[string]any) string { return "mesh-mail-web" }, - callersOverride: func() (Callers, error) { return Callers{"mesh-mail-web"}, nil }, - Store: func(context.Context) (Store, error) { return store, nil }, + Store: func(context.Context) (Store, error) { return store, nil }, } got, err := b.healthTool(map[string]any{}) if err != nil { diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/main.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/main.go index e85b95a2d..8c53a4482 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/main.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/main.go @@ -30,10 +30,6 @@ const Module = "mesh-mail-reader" func logf(format string, a ...any) { fmt.Fprintf(os.Stderr, format+"\n", a...) } -func envFromOS() Env { - return Env{Callers: os.Getenv("MESH_MAIL_READER_CALLERS")} -} - // cachedStore opens the index once, lazily, and hands every later caller that SAME store (review round 1 // finding 2, issue 1517/1518): the Bundle's own tool calls (one per mesh/ask, tools.go), hearLoop's handler // (one per event heard) and batchLoop. Before this, each of those called storeFor itself, which opened a @@ -71,7 +67,7 @@ func main() { os.Exit(prepare()) } store := newCachedStore(func(ctx context.Context) (Store, error) { return PgStoreFromEnv(ctx) }) - b := &Bundle{Env: envFromOS(), Store: store.get} + b := &Bundle{Store: store.get} go hearLoop(store.get, stdio.Subscribe, time.Sleep) go batchLoop(store.get) if err := stdio.ServeOn("", b.Tools(), os.Stdin, os.Stdout); err != nil { diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/runtime_player_integration_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/runtime_player_integration_test.go index f75322f5c..f6f429894 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/runtime_player_integration_test.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/runtime_player_integration_test.go @@ -518,18 +518,12 @@ func startReader(t *testing.T) *startedReader { if err := os.WriteFile(dbPath, []byte(dbURL), 0o600); err != nil { t.Fatal(err) } - callersPath := filepath.Join(dir, "callers.json") - callersJSON, _ := json.Marshal(map[string]any{"callers": []string{"mesh-mail-web"}}) - if err := os.WriteFile(callersPath, callersJSON, 0o600); err != nil { - t.Fatal(err) - } stand := &standIns{} env := append(os.Environ(), "MESH_NODE="+testNode, "MESH_SERVED_MODULE=mesh-mail-reader", "DATABASE_URL_FILE="+dbPath, - "MESH_MAIL_READER_CALLERS="+callersPath, ) player := startReaderPlayer(t, binary, env, stand, nc, nil) return &startedReader{player: player, stand: stand, nc: nc, dbURL: dbURL} diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools.go index 3137b7ae6..4100581d4 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools.go @@ -1,10 +1,9 @@ package main // The module's tools (novox/hq ADR 0459 §2, issue 1426): the six mail-reading seat verbs — entries, groups, -// correct, lessons, undo, status — and the module's own health tool, mail_reader_health (1519). Who calls is -// the runtime's word (stdio.CallerOf), never an argument; a mail-reading verb answers only a caller the -// trusted setting `callers` names (callers.go), and refuses any other, naming why. mail_reader_health is -// asked by the node-engine itself and carries no caller check. +// correct, lessons, undo, status — and the module's own health tool, mail_reader_health (1519). Every verb +// answers every caller: the module keeps no callers list (design 47 H, H-A-122; every account may call every +// verb); what protects the mail is what the verbs answer, never a body (ADR 0459 §2). // // The six verbs' own behaviour — reading and writing mail entries, mail groups and reading lessons — is // 1521 (entries, groups, status) and 1428 (correct, lessons, undo): all six now answer for real. @@ -31,46 +30,9 @@ const ( StatusTool = "mail-reading.status" ) -// Bundle is what the tools reach: the trusted setting `callers`, the runtime's own caller, and the index -// (store.go), which mail_reader_health reads (1519). Caller is nil outside a test (CallerOf is read from the -// runtime). +// Bundle is what the tools reach: the index (store.go), which mail_reader_health reads too (1519). type Bundle struct { - Env Env - Caller func(args map[string]any) string - Store func(ctx context.Context) (Store, error) - - // callersOverride, when set, is used instead of reading Env.Callers — the tests' own seam. - callersOverride func() (Callers, error) -} - -// Env is where the bundle reads its settings from. -type Env struct { - Callers string // the path MESH_MAIL_READER_CALLERS names. -} - -func (b *Bundle) caller(args map[string]any) string { - if b.Caller != nil { - return b.Caller(args) - } - return stdio.CallerOf(args) -} - -func (b *Bundle) callers() (Callers, error) { - if b.callersOverride != nil { - return b.callersOverride() - } - return ReadCallers(b.Env.Callers) -} - -// checkCaller refuses args' caller unless the trusted setting `callers` names it (1426/AC4). It is the first -// thing every mail-reading verb does: a caller learns it is refused before it learns anything about the verb. -func (b *Bundle) checkCaller(args map[string]any) (string, error) { - caller := b.caller(args) - callers, err := b.callers() - if err != nil || !callers.Allows(caller) { - return caller, refuseCaller(err, caller) - } - return caller, nil + Store func(ctx context.Context) (Store, error) } // schema, text, integer and boolean mirror mesh-mail's own tools.go helpers (modules/mesh-mail/cmd/mesh-mail, @@ -125,7 +87,7 @@ func (b *Bundle) Tools() []stdio.Tool { Description: "Every mail entry (novox/hq ADR 0459 §4): the mail's own headers, its mail group, a " + "one-line summary, its mark and why, its due date — never a mail body. Newest first, except a " + "mail that matters comes first, nearest due date first among those (none last). Filtered by mail " + - "group (its label) or by mark when asked. Answered only to a caller the setting callers names. " + + "group (its label) or by mark when asked. " + "Read-only.", Input: schema(nil, map[string]any{ "limit": integer("how many to answer; a default bounds it when left out"), @@ -135,7 +97,7 @@ func (b *Bundle) Tools() []stdio.Tool { Run: b.entriesTool}, {Name: GroupsTool, Description: "Every mail group a batch has made (novox/hq ADR 0459 §4, §5), with how many mails it " + - "holds, largest first. Answered only to a caller the setting callers names. Read-only.", + "holds, largest first. Read-only.", Input: schema(nil, map[string]any{ "limit": integer("how many to answer; a default bounds it when left out"), }), @@ -144,7 +106,7 @@ func (b *Bundle) Tools() []stdio.Tool { Description: "Correct one mail entry's mark, mail group, why or due date (novox/hq ADR 0459 §8): " + "kept at once as a reading lesson (the mail's own headers, the change made, when), no operator " + "Approve needed, and outranking that mail's own words in any later batch. Refused for an unknown " + - "mail id or mark. Answered only to a caller the setting callers names.", + "mail id or mark.", Input: schema([]string{"id"}, map[string]any{ "id": integer("the mail entry's id, as entries answered it"), "mark": text("the corrected mark: matters, scam warning or neither"), @@ -156,8 +118,7 @@ func (b *Bundle) Tools() []stdio.Tool { {Name: LessonsTool, Description: "The reading lessons kept (novox/hq ADR 0459 §9): newest first, at most 40 (fewer when " + "asked); undone ones left out unless include-undone asks for them, each then marked undone. A " + - "lesson outranks a mail it would otherwise contradict. Answered only to a caller the setting " + - "callers names. Read-only.", + "lesson outranks a mail it would otherwise contradict. Read-only.", Input: schema(nil, map[string]any{ "limit": integer("how many to answer, at most 40; a default bounds it when left out"), "include-undone": boolean("also answer undone lessons, each marked undone; left out by default"), @@ -165,7 +126,7 @@ func (b *Bundle) Tools() []stdio.Tool { Run: b.lessonsTool}, {Name: UndoTool, Description: "Undo one reading lesson (novox/hq ADR 0459 §9, issue 1523): it no longer outranks a " + - "mail. Answered only to a caller the setting callers names.", + "mail.", Input: schema([]string{"id"}, map[string]any{ "id": integer("the reading lesson's id, as lessons answered it"), }), @@ -173,7 +134,7 @@ func (b *Bundle) Tools() []stdio.Tool { {Name: StatusTool, Description: "How mail reading stands for the page (novox/hq ADR 0459 §10): healthy or not, the cause " + "and since when, and reading lessons per 100 read mails for each of the last 8 weeks (a week with " + - "no mail read says so). Answered only to a caller the setting callers names. Read-only.", + "no mail read says so). Read-only.", Input: schema(nil, map[string]any{}), Run: b.statusTool}, {Name: HealthTool, @@ -200,9 +161,6 @@ func entryOut(e Entry, labels map[int64]string) map[string]any { } func (b *Bundle) entriesTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args, "limit", "group", "mark"); err != nil { return nil, err } @@ -254,9 +212,6 @@ func (b *Bundle) entriesTool(args map[string]any) (any, error) { } func (b *Bundle) groupsTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args, "limit"); err != nil { return nil, err } @@ -294,9 +249,6 @@ func validMark(s string) (Mark, error) { } func (b *Bundle) correctTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args, "id", "mark", "group", "why", "due-date"); err != nil { return nil, err } @@ -397,9 +349,6 @@ func groupLabels(ctx context.Context, store Store) (map[int64]string, error) { } func (b *Bundle) lessonsTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args, "limit", "include-undone"); err != nil { return nil, err } @@ -443,9 +392,6 @@ func (b *Bundle) lessonsTool(args map[string]any) (any, error) { } func (b *Bundle) undoTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args, "id"); err != nil { return nil, err } @@ -473,9 +419,6 @@ func (b *Bundle) undoTool(args map[string]any) (any, error) { } func (b *Bundle) statusTool(args map[string]any) (any, error) { - if _, err := b.checkCaller(args); err != nil { - return nil, err - } if err := only(args); err != nil { return nil, err } diff --git a/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools_test.go b/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools_test.go index fc794f23d..68269244a 100644 --- a/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools_test.go +++ b/modules/mesh-mail-reader/cmd/mesh-mail-reader/tools_test.go @@ -2,7 +2,6 @@ package main import ( "context" - "strings" "testing" ) @@ -34,76 +33,21 @@ func TestToolsListsTheSixVerbsAndHealth(t *testing.T) { } } -// 1426/AC4, 1428/AC5: a mail-reading verb answers a caller the setting callers names, and refuses any other, -// naming why — before anything else about the verb (business errors such as an unknown id are not caller -// refusals, and are exercised by correct_test.go and 1521's own tests, not here). -func TestAMailReadingVerbChecksItsCaller(t *testing.T) { - granted := func(map[string]any) string { return "mesh-mail-web" } - refused := func(map[string]any) string { return "person.someoneelse" } - unproven := func(map[string]any) string { return Unproven } - storeOf := func(context.Context) (Store, error) { return newMemStore(), nil } - +// Design 47 H, H-A-122: a mail-reading verb answers every caller, even one the runtime proved nobody to be (the +// caller of arguments no call was handed): the module keeps no callers list. +func TestAMailReadingVerbAnswersEveryCaller(t *testing.T) { + b := &Bundle{Store: func(context.Context) (Store, error) { return newMemStore(), nil }} for _, tool := range []struct { name string - run func(*Bundle) (any, error) + run func() (any, error) }{ - {EntriesTool, func(b *Bundle) (any, error) { return b.entriesTool(map[string]any{}) }}, - {GroupsTool, func(b *Bundle) (any, error) { return b.groupsTool(map[string]any{}) }}, - {CorrectTool, func(b *Bundle) (any, error) { - return b.correctTool(map[string]any{"id": float64(1), "mark": "matters"}) - }}, - {LessonsTool, func(b *Bundle) (any, error) { return b.lessonsTool(map[string]any{}) }}, - {UndoTool, func(b *Bundle) (any, error) { return b.undoTool(map[string]any{"id": float64(1)}) }}, - {StatusTool, func(b *Bundle) (any, error) { return b.statusTool(map[string]any{}) }}, + {EntriesTool, func() (any, error) { return b.entriesTool(map[string]any{}) }}, + {GroupsTool, func() (any, error) { return b.groupsTool(map[string]any{}) }}, + {LessonsTool, func() (any, error) { return b.lessonsTool(map[string]any{}) }}, + {StatusTool, func() (any, error) { return b.statusTool(map[string]any{}) }}, } { - callers := func() (Callers, error) { return Callers{"mesh-mail-web"}, nil } - - b := &Bundle{Caller: granted, callersOverride: callers, Store: storeOf} - _, err := tool.run(b) - if err != nil && strings.Contains(err.Error(), "is not named in the setting callers") { - t.Errorf("%s granted: %v, want it to pass the caller check (any other error is its own business, not a caller refusal)", tool.name, err) - } - - b = &Bundle{Caller: refused, callersOverride: callers, Store: storeOf} - _, err = tool.run(b) - if err == nil || !strings.Contains(err.Error(), "refused") || !strings.Contains(err.Error(), "person.someoneelse") { - t.Errorf("%s refused caller: %v, want a refusal naming person.someoneelse", tool.name, err) - } - - b = &Bundle{Caller: unproven, callersOverride: callers, Store: storeOf} - _, err = tool.run(b) - if err == nil || !strings.Contains(err.Error(), "refused") { - t.Errorf("%s unproven caller: %v, want a refusal", tool.name, err) + if _, err := tool.run(); err != nil { + t.Errorf("%s: %v, want an answer to any caller", tool.name, err) } } } - -// 1426/AC4: a setting that cannot be read allows nobody, and says why — before the store is ever reached. -func TestAMailReadingVerbRefusesWhenCallersCannotBeRead(t *testing.T) { - b := &Bundle{ - Caller: func(map[string]any) string { return "mesh-mail-web" }, - callersOverride: func() (Callers, error) { return nil, errFake }, - } - _, err := b.entriesTool(map[string]any{}) - if err == nil || !strings.Contains(err.Error(), "cannot be read") { - t.Fatalf("entriesTool with an unreadable setting: %v", err) - } -} - -// mail_reader_health carries no caller check (1426: "mail_reader_health is asked by the node-engine itself"). -func TestHealthToolHasNoCallerCheck(t *testing.T) { - b := &Bundle{ - callersOverride: func() (Callers, error) { return nil, errFake }, - Store: func(context.Context) (Store, error) { return newMemStore(), nil }, - } - _, err := b.healthTool(map[string]any{}) - if err != nil { - t.Fatalf("mail_reader_health: %v, want it to skip the caller check entirely and answer", err) - } -} - -type fakeErr struct{} - -func (fakeErr) Error() string { return "the setting cannot be read (fake)" } - -var errFake = fakeErr{} diff --git a/modules/mesh-mail-reader/files/callers.json b/modules/mesh-mail-reader/files/callers.json deleted file mode 100644 index 84dd80034..000000000 --- a/modules/mesh-mail-reader/files/callers.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "callers": ["mesh-mail-web"] -} diff --git a/modules/mesh-mail-reader/module.json b/modules/mesh-mail-reader/module.json index 5829145a1..211b6dbe5 100644 --- a/modules/mesh-mail-reader/module.json +++ b/modules/mesh-mail-reader/module.json @@ -1,6 +1,7 @@ { "module": "mesh-mail-reader", "version": "0.1", + "class": "core", "runs-as": "mesh-mail-reader", "claims": [ { @@ -32,14 +33,6 @@ "secrets": { "postgres-database": "${dir:state}/database.secret" }, - "config": { - "callers": { - "type": "list", - "description": "Who may call one of mail-reading's six verbs (entries, groups, correct, lessons, undo, status): a module's name (on every machine), ., or person. (novox/hq ADR 0459 §2). mesh-mail-web alone by default.", - "trusted": true, - "default": ["mesh-mail-web"] - } - }, "tools": [ "mail-reading.entries", "mail-reading.groups", @@ -77,17 +70,6 @@ "place": ".", "unknown": "program" }, - { - "id": "callers", - "trusted": true, - "type": "file", - "path": "${dir:state}/callers.json", - "mode": "0600", - "owner": "mesh-mail-reader", - "merge": "json", - "template": "files/callers.json", - "takes-config": ["callers"] - }, { "id": "database-url", "type": "file", @@ -127,8 +109,7 @@ "mesh-mail-reader" ], "env": { - "DATABASE_URL_FILE": "${dir:state}/database.url", - "MESH_MAIL_READER_CALLERS": "${dir:state}/callers.json" + "DATABASE_URL_FILE": "${dir:state}/database.url" } }, { diff --git a/modules/mesh-mail-web/module.json b/modules/mesh-mail-web/module.json index ddb16db66..f9192aac6 100644 --- a/modules/mesh-mail-web/module.json +++ b/modules/mesh-mail-web/module.json @@ -1,6 +1,7 @@ { "module": "mesh-mail-web", "version": "0.1", + "class": "core", "slug": "mail-web", "runs-as": "mesh-mail-web", "claims": [ diff --git a/modules/mesh-mail/module.json b/modules/mesh-mail/module.json index ce94111a8..42ad7e902 100644 --- a/modules/mesh-mail/module.json +++ b/modules/mesh-mail/module.json @@ -1,6 +1,7 @@ { "module": "mesh-mail", "version": "0.1", + "class": "core", "slug": "mail", "seats": [ { diff --git a/modules/mesh-provisioner-client/module.json b/modules/mesh-provisioner-client/module.json index 53a205b6c..c086a9afc 100644 --- a/modules/mesh-provisioner-client/module.json +++ b/modules/mesh-provisioner-client/module.json @@ -1,6 +1,7 @@ { "module": "mesh-provisioner-client", "version": "0.1", + "class": "core", "claims": [ { "name": "node-provisioner", diff --git a/modules/mesh-provisioner/module.json b/modules/mesh-provisioner/module.json index 15028d356..dd980a5c0 100644 --- a/modules/mesh-provisioner/module.json +++ b/modules/mesh-provisioner/module.json @@ -1,6 +1,7 @@ { "module": "mesh-provisioner", "version": "0.1", + "class": "core", "runs-as": "mesh-provisioner", "claims": [ { @@ -118,7 +119,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } }, { diff --git a/modules/mesh-reads/module.json b/modules/mesh-reads/module.json index 4dae766f8..1067ef63e 100644 --- a/modules/mesh-reads/module.json +++ b/modules/mesh-reads/module.json @@ -1,6 +1,7 @@ { "module": "mesh-reads", "version": "0.1", + "class": "core", "runs-as": "mesh-reads", "claims": [ { diff --git a/modules/mesh-recovery/cmd/mesh-recovery/main.go b/modules/mesh-recovery/cmd/mesh-recovery/main.go index a713dfdc1..2f9ad82db 100644 --- a/modules/mesh-recovery/cmd/mesh-recovery/main.go +++ b/modules/mesh-recovery/cmd/mesh-recovery/main.go @@ -177,9 +177,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro for _, x := range e.Start(ctx) { logger.Printf("the aside %s of %s's %s holds data the live bus lacks: recovery_restore_aside puts it back", x.Aside.ID, x.Module, x.Kept) } - // The seat list, read over the connection and heard on the module's event hub (seatlist.Part), which the seat's verbs check - // their callers against (A-179, A-186): registered before the hub starts, read again once its events are live. - seats := seatlist.NewPart("recovery", nil) + // The seat list, read over the connection and heard on the module's event hub (seatlist.Part), from which the seat's verbs + // are answered (A-179, A-186): registered before the hub starts, read again once its events are live. + seats := seatlist.NewPart("recovery") seats.Follow(seatlist.ProcessBus(conn.Call, hub), nil, logger.Printf) if err := hub.StartUntilBound(ctx, js, account, nil, seats.EventsLive); err != nil { logger.Printf("the consumer %s is not bound yet (%v): bound once the bus makes it, the seat list read then", account.EventConsumerName(), err) diff --git a/modules/mesh-recovery/cmd/mesh-recovery/main_test.go b/modules/mesh-recovery/cmd/mesh-recovery/main_test.go index 413076145..5acca9376 100644 --- a/modules/mesh-recovery/cmd/mesh-recovery/main_test.go +++ b/modules/mesh-recovery/cmd/mesh-recovery/main_test.go @@ -40,13 +40,13 @@ func TestWhatTheProcessReads(t *testing.T) { t.Run("the seat's definition from the seat list once read (A-186)", func(t *testing.T) { t.Cleanup(busretry.Waits(20*time.Millisecond, time.Millisecond, 5*time.Millisecond)) follow := func(silent bool) *seatlist.Part { - p := seatlist.NewPart("recovery", nil) + p := seatlist.NewPart("recovery") if r := p.Follow(listingCatalog{silent: silent}, nil, t.Logf); r != nil { <-r.Ready() } return p } - if _, ok := seatlist.Definition(seatlist.NewPart("recovery", nil).Reader, meshbroker.Seat)(); ok { + if _, ok := seatlist.Definition(seatlist.NewPart("recovery").Reader, meshbroker.Seat)(); ok { t.Error("a definition is answered before the seat list's reader started") } if _, ok := seatlist.Definition(follow(true).Reader, meshbroker.Seat)(); ok { diff --git a/modules/mesh-recovery/cmd/mesh-recovery/whole_integration_test.go b/modules/mesh-recovery/cmd/mesh-recovery/whole_integration_test.go index 0aad2a95a..9e7904dba 100644 --- a/modules/mesh-recovery/cmd/mesh-recovery/whole_integration_test.go +++ b/modules/mesh-recovery/cmd/mesh-recovery/whole_integration_test.go @@ -15,6 +15,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "fmt" "os" "path/filepath" "strings" @@ -258,7 +259,8 @@ func TestRecoveryWhole(t *testing.T) { events <- heard{m.Subject, b} }) var kept []heard - waitEvent := func(t *testing.T, what string, ok func(heard) bool) map[string]any { + // saidWithin waits for an event ok takes, within bound, and ends the test by fail when none came. + saidWithin := func(t *testing.T, what string, bound time.Duration, fail func(string), ok func(heard) bool) map[string]any { t.Helper() for i, h := range kept { if ok(h) { @@ -266,7 +268,7 @@ func TestRecoveryWhole(t *testing.T) { return h.body } } - deadline := time.After(30 * time.Second) + deadline := time.After(bound) for { select { case h := <-events: @@ -275,10 +277,15 @@ func TestRecoveryWhole(t *testing.T) { } kept = append(kept, h) case <-deadline: - t.Fatalf("not said within 30s: %s", what) + fail(fmt.Sprintf("not said within %s: %s", bound, what)) + return nil } } } + waitEvent := func(t *testing.T, what string, ok func(heard) bool) map[string]any { + t.Helper() + return saidWithin(t, what, 30*time.Second, func(words string) { t.Helper(); t.Fatal(words) }, ok) + } endOf := func(t *testing.T, event, act string) map[string]any { t.Helper() return waitEvent(t, event+" of "+act, func(h heard) bool { @@ -347,13 +354,16 @@ func TestRecoveryWhole(t *testing.T) { done := make(chan error, 1) go func() { done <- run(runCtx, func(k string) string { return env[k] }, testLog{t}) }() defer func() { stop(); <-done }() - waitEvent(t, "the start's removal of points past their keep days", func(h heard) bool { + // The module's start is the test's setup: its waits on the bus take the setup bound of the level's bound and say a starved + // setup in its one line, never a value of the test's own (design 47 H2 §800, H-A-327, H-A-368). + setup := testbus.SetupBound(t) + saidWithin(t, "the start's removal of points past their keep days", setup, func(words string) { testbus.Starved(t, words) }, func(h heard) bool { return h.subject == "mesh.seat.mesh-recovery.event."+seat.EventExpiryEnded }) select { case <-listed: - case <-time.After(30 * time.Second): - t.Fatal("the module did not read its seat's definition from the seat list within 30s") + case <-time.After(setup): + testbus.Starved(t, fmt.Sprintf("the module did not read its seat's definition from the seat list within %s", setup)) } var first string diff --git a/modules/mesh-recovery/module.json b/modules/mesh-recovery/module.json index 9a955a3f8..2719831e7 100644 --- a/modules/mesh-recovery/module.json +++ b/modules/mesh-recovery/module.json @@ -1,6 +1,7 @@ { "module": "mesh-recovery", "version": "0.1", + "class": "core", "runs-as": "mesh-recovery", "claims": [ { @@ -93,7 +94,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ], diff --git a/modules/mesh-self-check/cmd/mesh-self-check/probes.go b/modules/mesh-self-check/cmd/mesh-self-check/probes.go index 6e944eea3..49fc64641 100644 --- a/modules/mesh-self-check/cmd/mesh-self-check/probes.go +++ b/modules/mesh-self-check/cmd/mesh-self-check/probes.go @@ -35,7 +35,7 @@ const ( // `reads`, which its test holds to these. var ( Invokes = []string{StreamsTool, ClosedTool, SignalsVerb, BannedVerb, AssignmentsTool, SeatHoldersTool, - RevisionVerb, RegistrationsVerb, SourceVerb, HandActVerb} + RevisionVerb, RegistrationsVerb, SourceVerb, HandActVerb, TimesTool} Reads = []string{PresenceRead, HealthRead, ReadingsRead, GoodRead} // Consumes are the views families the probes follow (ADR 0615): the indexer's and the assigner's states are asked // once, by their owners' read tools, and then followed by their events, never read. @@ -104,6 +104,8 @@ func Registry() []Probe { Deferred: "the grants of restricted streams with what each machine composed for them: " + storeOnly}, {ID: "DW", Asserts: "the watchdogs answer: the watchman holds the seat mesh-watchdogs and answers signals", From: "ADR 0227 rule 6: the watchers are watched", Kind: "watchdogs-silent", Run: probeWatchdogs}, + {ID: "D-budget", Asserts: "every class's newest delivery ran on every machine within its budget from its merge call: " + + "the gate's gate_times", From: "ADR 0282 §7, design 47 H2 §810", Kind: kindOverBudget, Run: probeBudget}, {ID: "H-bus", Asserts: "every stream the mesh defines is on the bus, and a request crosses it " + "to the bus's machine and back", From: "ADR 0236, to-be 45 §8", Kind: "core-unhealthy", Run: probeBusHealth}, } diff --git a/modules/mesh-self-check/cmd/mesh-self-check/probes_budget.go b/modules/mesh-self-check/cmd/mesh-self-check/probes_budget.go new file mode 100644 index 000000000..b2e56db1b --- /dev/null +++ b/modules/mesh-self-check/cmd/mesh-self-check/probes_budget.go @@ -0,0 +1,73 @@ +package main + +// The delivery budget's probe (design 47 H2 §810; ADR 0282 §7; H-A-396): it reads the gate's times (gate_times) and raises +// over-budget with the class as its id when that class's newest delivery took longer than its budget, naming the source +// revision and its longest phase; a newest delivery within its budget clears it. It reads no records itself, and the gate +// raises nothing. + +import ( + "context" + "encoding/json" + "fmt" + "sort" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient" +) + +// TimesTool is the gate's read of its delivery times against their budgets. +const TimesTool = "mesh-delivery-gate.gate_times" + +// scopeDelivery is the scope of the delivery's findings, the gate's own (A-42). +const scopeDelivery = "delivery" + +// kindOverBudget is the finding of a class whose newest delivery took longer than its budget. +const kindOverBudget = "over-budget" + +// classTimes is one class as gate_times answers it: its budget and its newest delivery. +type classTimes struct { + Budget string `json:"budget"` + Last *struct { + Record string `json:"record"` + Milestone string `json:"milestone"` + Ended string `json:"ended"` + DeliveryTime string `json:"delivery-time"` + Longest string `json:"longest-phase"` + LongestTime string `json:"longest-phase-time"` + Over bool `json:"over"` + } `json:"last"` +} + +func probeBudget(_ context.Context, c *Checker) ([]Finding, error) { + raw, err := c.Ask(TimesTool, map[string]any{}) + if err != nil { + return nil, fmt.Errorf("the gate did not answer %s: %w", TimesTool, err) + } + var times map[string]classTimes + if err := json.Unmarshal(raw, ×); err != nil { + return nil, fmt.Errorf("the gate answered %s with something unreadable: %w", TimesTool, err) + } + classes := make([]string, 0, len(times)) + for class := range times { + classes = append(classes, class) + } + sort.Strings(classes) + var out []Finding + for _, class := range classes { + t := times[class] + if t.Last == nil || !t.Last.Over { + continue + } + longest := "no phase recorded" + if t.Last.Longest != "" { + longest = fmt.Sprintf("its longest phase %s took %s", t.Last.Longest, t.Last.LongestTime) + } + out = append(out, finding(scopeDelivery, class, "", "", Finding{Kind: kindOverBudget, Severity: meshconditionsclient.Warning, + Summary: fmt.Sprintf("the newest %s delivery, %s, took %s from its merge call to running everywhere, over its budget of %s; %s", + class, t.Last.Milestone, t.Last.DeliveryTime, t.Budget, longest), + Evidence: said(fmt.Sprintf("record %s ended %s", t.Last.Record, t.Last.Ended)), + Headline: capital(class) + " deliveries are over their budget", + Explanation: capital(fmt.Sprintf("a delivery moving a %s module should run on every machine within %s of its merge "+ + "call; the newest took %s. The next %s delivery within its budget clears this.", class, t.Budget, t.Last.DeliveryTime, class))})) + } + return sorted(out), nil +} diff --git a/modules/mesh-self-check/cmd/mesh-self-check/probes_test.go b/modules/mesh-self-check/cmd/mesh-self-check/probes_test.go index 7a369328d..9a7739169 100644 --- a/modules/mesh-self-check/cmd/mesh-self-check/probes_test.go +++ b/modules/mesh-self-check/cmd/mesh-self-check/probes_test.go @@ -34,6 +34,8 @@ type bus struct { banned map[string]string // fills are rows nats_streams answers beside the mesh's streams: a module's bucket or log with its size and cap. fills []fillRow + // times is what the gate's gate_times answers. + times string } func (b bus) rows() map[string]*streamRow { @@ -87,6 +89,8 @@ func (b bus) ask(key string, body any) (json.RawMessage, error) { return nil, errors.New("no stream called " + stream) } return json.Marshal(map[string]any{"detail": detail}) + case TimesTool: + return json.RawMessage(b.times), nil case ClosedTool: if b.closed == "" { return json.RawMessage(`{"hours":1,"reaches":true,"users":[]}`), nil @@ -133,6 +137,12 @@ func TestTheBusProbes(t *testing.T) { {"user":"g14.node-tools","closed":30,"dropped":20,"names":[{"name":"node-tools","dropped":20,"reasons":{"Stale Connection":20}}]}, {"user":"ace.records","closed":5,"dropped":3},{"user":"(unauthenticated)","closed":90,"dropped":90}]}`}, []string{"bus.g14=2enode-tools.bus-reconnects"}, "", nil}, + // design 47 H2 §810: a core delivery 11 minutes after its merge call is over its 10 minutes; the next within clears it. + {"D-budget a core delivery over", probeBudget, bus{times: `{"core":{"budget":"10m0s","last":{"record":"record/main_7","milestone":"main.7", + "ended":"2026-11-22T00:11:00Z","delivery-time":"11m0s","longest-phase":"build","longest-phase-time":"7m0s","over":true}}, + "leaf":{"budget":"3m0s"}}`}, []string{"delivery.core.over-budget"}, "", nil}, + {"D-budget the next core delivery within", probeBudget, bus{times: `{"core":{"budget":"10m0s","last":{"record":"record/main_8", + "milestone":"main.8","delivery-time":"4m0s","over":false}},"leaf":{"budget":"3m0s"}}`}, nil, "", nil}, {"DW answers", probeWatchdogs, bus{}, nil, "", nil}, {"DW silent", probeWatchdogs, bus{signals: errors.New("no responders")}, []string{"core.watchdogs.watchdogs-silent"}, "", nil}, {"H-bus healthy", probeBusHealth, bus{}, nil, "", nil}, @@ -338,7 +348,7 @@ func agents(verdicts map[string]string) *memStore { // it lacks; the probes that end with the controller or moved to the watchman are not in it (issue 1952 SC4). func TestTheRegistryIsADR0564sTable(t *testing.T) { moved := []string{"D2", "D3", "D4", "D7", "D8", "D11", "D12", "D13", "D15", "DA", "D-root", "D-fill", "D-heard", - "DW", "H-bus"} + "DW", "H-bus", "D-budget"} var ids []string for _, p := range Registry() { ids = append(ids, p.ID) diff --git a/modules/mesh-self-check/cmd/mesh-self-check/whole_integration_test.go b/modules/mesh-self-check/cmd/mesh-self-check/whole_integration_test.go index fcb372384..07a99b160 100644 --- a/modules/mesh-self-check/cmd/mesh-self-check/whole_integration_test.go +++ b/modules/mesh-self-check/cmd/mesh-self-check/whole_integration_test.go @@ -49,6 +49,8 @@ type player struct { in io.Writer next int pending map[string]chan wire + // times is what the gate's gate_times answers the budget probe (design 47 H2 §810). + times map[string]any } func (p *player) send(m map[string]any) { @@ -147,7 +149,7 @@ func (p *player) handle(m wire) { } _ = json.Unmarshal(m.Params, &g) if g.Kind == "config" && g.Key == "probes" { - p.answer(m.ID, []string{"D2", "D7", "DW", "D15"}, nil) + p.answer(m.ID, []string{"D2", "D7", "DW", "D15", "D-budget"}, nil) return } p.answer(m.ID, nil, fmt.Errorf("no %s value %s here", g.Kind, g.Key)) @@ -179,6 +181,13 @@ func (p *player) handle(m wire) { Key string `json:"key"` } _ = json.Unmarshal(m.Params, &ask) + if ask.Key == TimesTool { + p.mu.Lock() + times := p.times + p.mu.Unlock() + p.answer(m.ID, times, nil) + return + } if ask.Key != StreamsTool { p.answer(m.ID, nil, errors.New("nats: no responders available for request")) return @@ -268,7 +277,14 @@ func TestTheSelfCheckWholeRunsOnTheBus(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = stdin.Close(); cancel(); _ = cmd.Wait() }) - p := &player{ctx: ctx, nc: nc, js: js, in: stdin, pending: map[string]chan wire{}} + // SC1 (design 47 H2 §810; H-A-453 (3)): the gate's newest core delivery took 11 minutes from its merge call, over its + // budget of ten. + coreTimes := func(took string, over bool) map[string]any { + return map[string]any{"core": map[string]any{"budget": "10m0s", "last": map[string]any{"record": "record/main_7", + "milestone": "main.7", "ended": "2026-11-22T01:00:00Z", "delivery-time": took, "longest-phase": "placing", + "longest-phase-time": "6m0s", "over": over}}, "leaf": map[string]any{"budget": "3m0s"}} + } + p := &player{ctx: ctx, nc: nc, js: js, in: stdin, pending: map[string]chan wire{}, times: coreTimes("11m0s", true)} go p.serve(stdout) raw, err := p.call(DoctorTool, map[string]any{"run": true}) @@ -323,4 +339,33 @@ func TestTheSelfCheckWholeRunsOnTheBus(t *testing.T) { if raw, err := p.call(VerdictsTool, map[string]any{}); err != nil || !strings.Contains(string(raw), answer.Run.Run) { t.Errorf("the week's verdicts answered %s, %v", raw, err) } + + // SC1: the over-budget core delivery raised over-budget for the class core, naming its record and longest phase; the next + // core delivery within its budget clears it. + overBudget := func() (string, bool) { + keys, err := findings.Keys(ctx) + if err != nil { + return "", false + } + for _, k := range keys { + if strings.Contains(k, ".core.") && strings.HasSuffix(k, "."+kindOverBudget) { + e, err := findings.Get(ctx, k) + return string(e.Value()), err == nil + } + } + return "", false + } + if raised, ok := overBudget(); verdicts["D-budget"] != VerdictFail || !ok || !strings.Contains(raised, "main.7") || + !strings.Contains(raised, "placing") { + t.Errorf("the over-budget core delivery: the probe's verdict %q, the finding %q (%v)", verdicts["D-budget"], raised, ok) + } + p.mu.Lock() + p.times = coreTimes("4m0s", false) + p.mu.Unlock() + if _, err := p.call(DoctorTool, map[string]any{"run": true}); err != nil { + t.Fatal(err) + } + if raised, ok := overBudget(); ok { + t.Errorf("a core delivery within its budget left over-budget raised: %s", raised) + } } diff --git a/modules/mesh-self-check/module.json b/modules/mesh-self-check/module.json index fdff2735c..ec9dfb550 100644 --- a/modules/mesh-self-check/module.json +++ b/modules/mesh-self-check/module.json @@ -1,6 +1,7 @@ { "module": "mesh-self-check", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-catalog/modules/restic/backupgood": "0.1", "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings": "0.1" @@ -26,7 +27,8 @@ "seat:mesh-catalog.revision", "seat:mesh-catalog.registrations", "seat:mesh-delivery.source", - "seat:mesh-hand-acts.hand-act" + "seat:mesh-hand-acts.hand-act", + "mesh-delivery-gate.gate_times" ], "reads": [ "mesh-delivery-watchman.presence", @@ -114,7 +116,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/mesh-vault/README.md b/modules/mesh-vault/README.md index cd22dca7f..4d03694e6 100644 --- a/modules/mesh-vault/README.md +++ b/modules/mesh-vault/README.md @@ -247,9 +247,8 @@ restart; it is on until switched off, and `own_drift` shows it. ## Retiring an own secret: `retire` (design 32) `retire` removes one module's own secret on a node because no manifest reads it any more, and says `own-retired` -(node, module, name, ask, caller). Two proofs: the caller is on the vault's trusted list `retire-callers` (the holder of -the seat `mesh-config` alone, a file the mesh writes from the config value, read at start; a list that cannot be read -allows nobody), and `warrant` is the id of a hand act that caller recorded through `mesh-hand-acts` for this verb, +(node, module, name, ask, caller). Every caller may ask it (design 47 H §752); one proof: `warrant` is the id of a hand +act that caller recorded through `mesh-hand-acts` for this verb, naming exactly the node, module, name and the ask of the operator's Approve, within a day. A bus account and the tool runner's `ledgers` are never retired this way. A waiter on `rotated` or `own-replaced` does not wake on it. diff --git a/modules/mesh-vault/cmd/mesh-vault/adopt.go b/modules/mesh-vault/cmd/mesh-vault/adopt.go index 86fb76d25..041a02ba6 100644 --- a/modules/mesh-vault/cmd/mesh-vault/adopt.go +++ b/modules/mesh-vault/cmd/mesh-vault/adopt.go @@ -19,10 +19,11 @@ package main import ( "errors" "fmt" - engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" "sort" "strings" "time" + + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" ) // HaveRead is the node-engines' have bucket as the vault reads it (its manifest's `reads`). diff --git a/modules/mesh-vault/cmd/mesh-vault/enrolment.go b/modules/mesh-vault/cmd/mesh-vault/enrolment.go index a562add1a..110f26366 100644 --- a/modules/mesh-vault/cmd/mesh-vault/enrolment.go +++ b/modules/mesh-vault/cmd/mesh-vault/enrolment.go @@ -21,12 +21,13 @@ import ( "encoding/pem" "errors" "fmt" - enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" "os" "path/filepath" "strings" "time" + enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" + "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" stdio "git.novox.be/novox/mesh-sdk/go" "golang.org/x/crypto/bcrypt" @@ -117,13 +118,38 @@ func (v *Vault) loginKeyRefusal(caller, publicKey string) string { return "" } +// callers is the vault's one list of callers, of its enrolment verbs (ADR 0682 §10's exception, H-A-11, H-A-41): each +// entry a module on any machine, . or person., matched against the caller the runtime proved. +type callers []string + +// Allows says whether caller, as the runtime proved it, is one the list names. +func (c callers) Allows(caller string) bool { + if caller == "" || caller == stdio.Unproven { + return false + } + for _, entry := range c { + if entry == "" || strings.ContainsAny(entry, "*> ") { + continue + } + if entry == caller { + return true + } + if !strings.Contains(entry, ".") { + if _, module, ok := strings.Cut(caller, "."); ok && module == entry && !strings.HasPrefix(caller, "person.") { + return true + } + } + } + return false +} + // fromEnrolment refuses every caller but the seat mesh-node-enroller, as the runtime proved it. func (v *Vault) fromEnrolment(caller, verb string) error { - callers := v.EnrolCallers - if callers == nil { - callers = stdio.Callers{EnrolmentModule} + list := v.EnrolCallers + if list == nil { + list = callers{EnrolmentModule} } - if !callers.Allows(caller) { + if !list.Allows(caller) { if caller == "" { caller = stdio.Unproven } diff --git a/modules/mesh-vault/cmd/mesh-vault/enrolment_test.go b/modules/mesh-vault/cmd/mesh-vault/enrolment_test.go index 7b1154325..6ccec7229 100644 --- a/modules/mesh-vault/cmd/mesh-vault/enrolment_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/enrolment_test.go @@ -9,10 +9,6 @@ import ( "encoding/json" "encoding/pem" "fmt" - assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" - placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" - enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" - vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" "slices" "sort" "strings" @@ -20,6 +16,11 @@ import ( "testing" "time" + assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" + placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" + enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" + vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" + "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" "golang.org/x/crypto/bcrypt" "golang.org/x/crypto/nacl/box" diff --git a/modules/mesh-vault/cmd/mesh-vault/enrolment_tools.go b/modules/mesh-vault/cmd/mesh-vault/enrolment_tools.go index 59160165f..16e11647c 100644 --- a/modules/mesh-vault/cmd/mesh-vault/enrolment_tools.go +++ b/modules/mesh-vault/cmd/mesh-vault/enrolment_tools.go @@ -9,10 +9,11 @@ import ( "encoding/json" "errors" "fmt" - enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" "sort" "strings" "time" + + enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" ) // EnrolmentHeld is one enrolment token the vault holds, as secret_holders lists it: never the token or its hash. @@ -129,8 +130,8 @@ func enrolmentTools(env *Env) []toolDef { }}, {Name: Seat + "." + RetireVerb, Description: "Retire one module's own secret on a node because no manifest reads it any more (design 32): removed " + - "whole, and own-retired said (node, module, name, the ask, the caller; never a value). Answered to the holder of " + - "the seat mesh-config alone, as the vault's list retire-callers names it, and only for a hand act it recorded " + + "whole, and own-retired said (node, module, name, the ask, the caller; never a value). Answered to any caller, " + + "and only for a hand act it recorded " + "through mesh-hand-acts for this verb naming exactly this node, module and name and the ask of the operator's Approve " + "(`warrant`, the act's id), read back here.", Input: map[string]any{"node": node, "module": str("the module whose secret it is"), "name": str("the secret's name"), diff --git a/modules/mesh-vault/cmd/mesh-vault/intake.go b/modules/mesh-vault/cmd/mesh-vault/intake.go index 38d49d00a..04971c921 100644 --- a/modules/mesh-vault/cmd/mesh-vault/intake.go +++ b/modules/mesh-vault/cmd/mesh-vault/intake.go @@ -269,17 +269,15 @@ type AskOf struct { Node, Module, Name, Desk string } -// askedByFor is who asked a secret-ask as the bus says it (novox/hq ADR 0563 §8): a caller the manifest names, as the -// runtime proved it. Any other caller is refused: no caller names itself, and none relays another's word. +// askedByFor is who asked a secret-ask as the bus says it (novox/hq ADR 0563 §8): the caller the runtime proved, any +// caller (design 47 H §752, H-A-41: no list of callers). A caller the runtime did not prove is refused: no caller names +// itself, and none relays another's word. func (v *Vault) askedByFor(caller string, a AskOf) (string, error) { - if v.AskCallers.Allows(caller) { + if caller != "" && caller != stdio.Unproven { return askedByName(caller), nil } - if caller == "" { - caller = stdio.Unproven - } - return "", fmt.Errorf("secret-ask answers the callers the vault's manifest names, and %s is not one; nobody was "+ - "asked to type anything", caller) + return "", fmt.Errorf("secret-ask answers a caller the runtime proved, and this one is %s; nobody was asked to type "+ + "anything", stdio.Unproven) } // AskOpen records an ask for a module's own secret before any prompt opens, holding its bounds — one open ask diff --git a/modules/mesh-vault/cmd/mesh-vault/intake_test.go b/modules/mesh-vault/cmd/mesh-vault/intake_test.go index 610b84d08..8ae73ecf7 100644 --- a/modules/mesh-vault/cmd/mesh-vault/intake_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/intake_test.go @@ -13,7 +13,6 @@ import ( "encoding/base64" "encoding/json" "errors" - stdio "git.novox.be/novox/mesh-sdk/go" "os" "path/filepath" "strings" @@ -84,7 +83,6 @@ func telegramAsk(by string) AskOf { // it; the typed value opens only in the vault; the controller carries ciphertext only. func TestAnAskIsRecordedBeforeThePromptAndTheTypedValueOpensOnlyInTheVault(t *testing.T) { v := newVault(t, AllowList{"anchor.node-provisioner": {"own/anchor/telegram/telegram-token"}}) - v.AskCallers = stdio.Callers{"g14.claude-code"} opened, err := v.AskOpen("g14.claude-code", telegramAsk("g14/claude-code, via the console")) if err != nil { t.Fatal(err) @@ -126,7 +124,6 @@ func TestAnAskIsRecordedBeforeThePromptAndTheTypedValueOpensOnlyInTheVault(t *te // One open ask per secret, and three an hour (ADR 0277 §24), read from the vault's own record. func TestAnAskIsBoundedToOneOpenPerSecretAndThreeAnHour(t *testing.T) { v := newVault(t, nil) - v.AskCallers = stdio.Callers{"g14.claude-code"} first, err := v.AskOpen("g14.claude-code", telegramAsk("g14.claude-code")) if err != nil { t.Fatal(err) @@ -167,7 +164,6 @@ func TestAnAskIsBoundedToOneOpenPerSecretAndThreeAnHour(t *testing.T) { } // An ask left open counts as open for SecretAskOpenFor only: a prompt that died does not hold the secret. w := newVault(t, nil) - w.AskCallers = stdio.Callers{"g14.claude-code"} clock := time.Date(2026, 10, 14, 9, 0, 0, 0, time.UTC) w.Now = func() time.Time { return clock } if _, err := w.AskOpen("g14.claude-code", telegramAsk("g14.claude-code")); err != nil { @@ -177,13 +173,12 @@ func TestAnAskIsBoundedToOneOpenPerSecretAndThreeAnHour(t *testing.T) { if _, err := w.AskOpen("g14.claude-code", telegramAsk("g14.claude-code")); err != nil { t.Errorf("an ask left open past its time still held the secret: %v", err) } - // 774 (ADR 0563 §8): a caller the manifest names asks directly, is named by its proven caller and never by the - // asked_by it gives, and is held to the same bounds; one it does not name is refused. - t.Run("a named caller asks itself, within the bounds", func(t *testing.T) { + // 774 (ADR 0563 §8): a proved caller asks directly, is named by its proven caller and never by the asked_by it + // gives, and is held to the same bounds; one the runtime did not prove is refused (design 47 H §752, H-A-41). + t.Run("a proved caller asks itself, within the bounds", func(t *testing.T) { x := newVault(t, nil) - x.AskCallers = stdio.Callers{"node-tools"} - if _, err := x.AskOpen("ace.claude-code", telegramAsk("x")); err == nil || !strings.Contains(err.Error(), "ace.claude-code") { - t.Errorf("a caller the manifest does not name opened an ask: %v", err) + if _, err := x.AskOpen("unproven", telegramAsk("x")); err == nil { + t.Errorf("an unproven caller opened an ask: %v", err) } opened, err := x.AskOpen("g14.node-tools", telegramAsk("person.operator")) if err != nil || opened.AskedBy != "g14.node-tools" { @@ -202,12 +197,11 @@ func TestAnAskIsBoundedToOneOpenPerSecretAndThreeAnHour(t *testing.T) { }) } -// Only a caller the vault's manifest names opens an ask, and only it ends it; a value not sealed to the call's key, or -// a call that waited too long, keeps nothing. -func TestAnAskIsTakenFromANamedCallerAloneAndOnlySealedToItsCall(t *testing.T) { +// Only a caller the runtime proved opens an ask, and only it ends it; a value not sealed to the call's key, or a call +// that waited too long, keeps nothing. +func TestAnAskIsTakenFromAProvedCallerAloneAndOnlySealedToItsCall(t *testing.T) { v := newVault(t, nil) - v.AskCallers = stdio.Callers{"g14.claude-code"} - for _, caller := range []string{"g14.node-tools", "unproven", "", "person.jochen"} { + for _, caller := range []string{"unproven", ""} { if _, err := v.AskOpen(caller, telegramAsk("x")); err == nil { t.Errorf("%q opened an ask", caller) } @@ -448,7 +442,6 @@ func TestTheNamesOfWhatIsTakenIn(t *testing.T) { // Each verb takes its caller from the runtime, never from its arguments, and names its secret one way only. func TestTheVerbsTakeTheirCallerFromTheRuntime(t *testing.T) { v := newVault(t, nil) - v.AskCallers = stdio.Callers{"g14.claude-code"} env := &Env{Vault: v.Vault} defs := definitions(env) var asked []map[string]any @@ -493,7 +486,6 @@ func TestTheVerbsTakeTheirCallerFromTheRuntime(t *testing.T) { // With the lock held elsewhere, AskEnd waits, and writes nothing until it is let go. func TestTheEndOfAnAskIsWrittenUnderTheRecordsLock(t *testing.T) { v := newVault(t, nil) - v.AskCallers = stdio.Callers{"g14.claude-code"} opened, err := v.AskOpen("g14.claude-code", telegramAsk("g14.claude-code")) if err != nil { t.Fatal(err) diff --git a/modules/mesh-vault/cmd/mesh-vault/licencebindings_test.go b/modules/mesh-vault/cmd/mesh-vault/licencebindings_test.go index 403c03d58..fe32bdd6d 100644 --- a/modules/mesh-vault/cmd/mesh-vault/licencebindings_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/licencebindings_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/views" ) @@ -133,7 +134,10 @@ func TestTheFirstViewOfTheLicenceBindingsIsKept(t *testing.T) { for _, st := range m.State { kept = kept || string(st) == `"`+LicenceBindingsState+`"` } - if !slices.Contains(m.Invokes, LicenceBindingsVerb) || !slices.Contains(m.Consumes, BindingChangedEvent) || !kept { + // The manager says each change as binding.changed. (design 47 G A-134), and the bus consumer the vault's + // consumes is composed into hands it only what an entry names, so an entry naming binding.changed alone hears none. + hears := slices.ContainsFunc(m.Consumes, func(c string) bool { return stdio.TopicMatches(c, BindingChangedEvent+".g14") }) + if !slices.Contains(m.Invokes, LicenceBindingsVerb) || !hears || !kept { t.Fatalf("the manifest invokes %v, consumes %v, keeps %s", m.Invokes, m.Consumes, m.State) } } diff --git a/modules/mesh-vault/cmd/mesh-vault/licences_test.go b/modules/mesh-vault/cmd/mesh-vault/licences_test.go index 6368f4572..0ffd6add6 100644 --- a/modules/mesh-vault/cmd/mesh-vault/licences_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/licences_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "fmt" "os" "strings" "testing" @@ -59,6 +60,61 @@ func TestLicencePutKeepsTheNewestGenerationAndRefusesAnOlder(t *testing.T) { if _, err := v.LicencePutOpen("", "jane", LicenceAccess, 1); err == nil { t.Error("licence-put took an unproven caller") } + t.Run("own-put keeps a module's own secret, handed to that module alone", ownPutKeepsAModulesOwn) + t.Run("secret_holders lists every record by name and fingerprint, never the value", secretHoldersByNameAndFingerprint) +} + +// ownPutKeepsAModulesOwn: design 47 H2 §822, H-A-360. A module puts a secret in two steps and reads it back through get +// by the full name own-put answered; another module's account and a non-module account are refused it; a second put +// keeps only the newer generation; the journal says each write, never the value. +func ownPutKeepsAModulesOwn(t *testing.T) { + v := newVault(t, nil) + var journal strings.Builder + v.Log = func(format string, args ...any) { fmt.Fprintf(&journal, format+"\n", args...) } + put := func(caller, name, value string) (Changed, error) { + t.Helper() + o, err := v.OwnPutOpen(caller, name) + if err != nil { + return Changed{}, err + } + if o.Secret != "module/gitea/admin-token" { + t.Fatalf("own-put names %q, want module/gitea/admin-token", o.Secret) + } + return v.OwnPutTake(caller, o.Call, sealToCall(t, o.SealTo, value)) + } + first, err := put("novox.gitea", "admin-token", "tok-1") + if err != nil || first.Name != "module/gitea/admin-token" { + t.Fatalf("%+v %v", first, err) + } + if got := handedTo(t, v, "ace.gitea", "module/gitea/admin-token"); got != "tok-1" { + t.Fatalf("handed %q to another process of the module, want tok-1", got) + } + second, err := put("ace.gitea", "admin-token", "tok-2") + if err != nil || second.Generation <= first.Generation { + t.Fatalf("second put %+v (%v) after generation %d", second, err, first.Generation) + } + rec, _, _ := v.Store.Read("module/gitea/admin-token") + if rec.Previous != nil || handedTo(t, v, "novox.gitea", "module/gitea/admin-token") != "tok-2" { + t.Fatalf("the newer generation alone is kept: %+v", rec) + } + key, _ := seal.GenerateKeyPair() + for _, other := range []string{"novox.mesh-config", "person.jo", "novox.node-tools", "provisioner.novox"} { + if _, err := v.Get(other, "module/gitea/admin-token", key.PublicKey); err == nil { + t.Errorf("%s was handed gitea's own secret", other) + } + } + for _, c := range []struct{ caller, name string }{{"person.jo", "x"}, {"novox.node-tools", "x"}, {"node.ace", "x"}, {"novox.gitea", ""}, {"novox.gitea", "A B"}} { + if _, err := v.OwnPutOpen(c.caller, c.name); err == nil { + t.Errorf("own-put opened for %s naming %q", c.caller, c.name) + } + } + o, _ := v.OwnPutOpen("novox.gitea", "admin-token") + if _, err := v.OwnPutTake("ace.gitea", o.Call, sealToCall(t, o.SealTo, "tok-3")); err == nil { + t.Error("a call opened by one caller was taken by another") + } + if all := journal.String() + everything(t, v); strings.Contains(all, "tok-") || !strings.Contains(all, "own-put: module/gitea/admin-token kept at generation") { + t.Errorf("the journal says each write without the value: %s", all) + } } // design 39 bus-and-switch §17/AC1, §16, B3, B8, B25: a licence's access token is refused to a machine no binding names @@ -121,7 +177,7 @@ func TestATokenIsGivenOnlyToAMachineABindingNames(t *testing.T) { // issue 1409, design 39 bus-and-switch §20, parts §12: secret_holders lists every record of the store by name and // fingerprint, a licence's two secrets with their key and part, a record it cannot open with an error, and no value. -func TestSecretHoldersListsEveryStoreRecordByNameAndFingerprintNeverTheValue(t *testing.T) { +func secretHoldersByNameAndFingerprint(t *testing.T) { v := newVault(t, nil) const manager = "claude-licence-manager" grant, access := `{"refreshToken":"rt-SECRET-grant"}`, `{"accessToken":"at-SECRET-access"}` diff --git a/modules/mesh-vault/cmd/mesh-vault/main.go b/modules/mesh-vault/cmd/mesh-vault/main.go index a52660395..7919f2faa 100644 --- a/modules/mesh-vault/cmd/mesh-vault/main.go +++ b/modules/mesh-vault/cmd/mesh-vault/main.go @@ -65,8 +65,8 @@ func build() *Env { Assignments: Mirror{Keys: assignmentKeys, Read: readAssignment}, Emit: emit, Ask: stdio.Ask, Now: time.Now, Log: say, Accounts: busAccounts{}, Haves: readHave, WantRead: readWant, HaveKeys: func() ([]string, error) { return stdio.State(HaveRead).Keys() }, Assigner: seatAssignments, Signers: busSigners{}, - AskCallers: askCallers(os.Getenv("MESH_VAULT_SECRET_ASK_CALLERS")), EnrolCallers: askCallers(os.Getenv("MESH_VAULT_ENROLMENT_CALLERS")), - RetireCallers: retireCallers(os.Getenv("MESH_VAULT_RETIRE_CALLERS")), Logins: busNodeLogins{}, ReadAct: readHandAct, TokenBase: TokenBaseFromFile(os.Getenv("MESH_VAULT_STATE")), + EnrolCallers: callerList(os.Getenv("MESH_VAULT_ENROLMENT_CALLERS")), + Logins: busNodeLogins{}, ReadAct: readHandAct, TokenBase: TokenBaseFromFile(os.Getenv("MESH_VAULT_STATE")), Bound: Bound{ Get: func(key string) ([]byte, error) { e, err := stdio.State(BoundState).Get(key) @@ -414,30 +414,10 @@ func main() { } } -// retireCallers reads the vault's list `retire-callers`, the file the mesh writes from its trusted config value -// (stdio.ParseCallers): a list that cannot be read allows nobody, and says why. -func retireCallers(path string) stdio.Callers { - if path == "" { - say("the vault was started without its retire-callers list (MESH_VAULT_RETIRE_CALLERS): retire answers nobody") - return nil - } - raw, err := os.ReadFile(path) - if err != nil { - say("the retire-callers list cannot be read, so retire answers nobody: %v", err) - return nil - } - callers, err := stdio.ParseCallers(raw) - if err != nil { - say("%v: retire answers nobody", err) - return nil - } - return callers -} - -// askCallers are the callers the vault's manifest names for secret-ask besides the controller (novox/hq ADR 0563 §8): -// MESH_VAULT_SECRET_ASK_CALLERS, comma-separated, each a module (on any machine), . or person.. -func askCallers(list string) stdio.Callers { - var out stdio.Callers +// callerList is the vault's manifest's list of the enrolment verbs' callers (MESH_VAULT_ENROLMENT_CALLERS), +// comma-separated, each a module (on any machine), . or person.. +func callerList(list string) callers { + var out callers for _, c := range strings.Split(list, ",") { if c = strings.TrimSpace(c); c != "" { out = append(out, c) diff --git a/modules/mesh-vault/cmd/mesh-vault/mint_integration_test.go b/modules/mesh-vault/cmd/mesh-vault/mint_integration_test.go index f4c9bef9a..a14cd33bd 100644 --- a/modules/mesh-vault/cmd/mesh-vault/mint_integration_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/mint_integration_test.go @@ -524,14 +524,10 @@ func TestTheVaultWholeMintsOnTheBusWhoeverHoldsTheLease(t *testing.T) { if _, err := seed.keep("own/g14/dunst/token", "a-token-value", "the test", "g14.dunst", OriginMade); err != nil { t.Fatal(err) } - callers := filepath.Join(dir, "retire-callers.json") - if err := os.WriteFile(callers, []byte(`{"callers":["mesh-config"]}`), 0o600); err != nil { - t.Fatal(err) - } cmd := exec.CommandContext(ctx, bin) cmd.Env = append(os.Environ(), "MESH_VAULT_STORE="+filepath.Join(dir, "store"), "MESH_VAULT_STATE="+filepath.Join(dir, "state"), "MESH_VAULT_ROOT="+root, "MESH_VAULT_LEDGER="+filepath.Join(dir, "ledger"), "MESH_RECEIVES="+filepath.Join(dir, "mesh.json"), - "MESH_VAULT_RETIRE_CALLERS="+callers, "MESH_NODE=novox", "MESH_MODULE=mesh-vault") + "MESH_NODE=novox", "MESH_MODULE=mesh-vault") stdin, _ := cmd.StdinPipe() stdout, _ := cmd.StdoutPipe() cmd.Stderr = os.Stderr @@ -650,4 +646,45 @@ func TestTheVaultWholeMintsOnTheBusWhoeverHoldsTheLease(t *testing.T) { t.Errorf("a waiter on %s heard %s", other, extra.Subject) } } + // Design 47 H2 §822: a module puts its own secret in two steps through the seat and reads it back through get; a + // second module's get of that name is refused; a second put keeps the newer generation alone. + putOwn := func(caller, value string) Changed { + t.Helper() + raw, err := p.call(Seat+"."+OwnPutVerb, caller, map[string]any{"name": "admin-token"}) + if err != nil { + t.Fatal(err) + } + var o Opened + _ = json.Unmarshal(raw, &o) + raw, err = p.call(Seat+"."+OwnPutVerb, caller, map[string]any{"call": o.Call, "sealed": sealToCall(t, o.SealTo, value)}) + if err != nil { + t.Fatal(err) + } + var c Changed + _ = json.Unmarshal(raw, &c) + return c + } + getOwn := func(caller string) (string, error) { + key, _ := seal.GenerateKeyPair() + raw, err := p.call(Seat+".get", caller, map[string]any{"name": "module/gitea/admin-token", "public_key": key.PublicKey}) + if err != nil { + return "", err + } + var a Answer + _ = json.Unmarshal(raw, &a) + return seal.Open(a.Sealed, key.PrivateKey) + } + first := putOwn("novox.gitea", "tok-1") + if got, err := getOwn("ace.gitea"); err != nil || got != "tok-1" || first.Name != "module/gitea/admin-token" { + t.Fatalf("own-put %+v, get answered %q (%v)", first, got, err) + } + if _, err := getOwn("novox.mesh-config"); err == nil { + t.Error("another module was handed gitea's own secret") + } + if second := putOwn("ace.gitea", "tok-2"); second.Generation <= first.Generation { + t.Errorf("the second put kept generation %d after %d", second.Generation, first.Generation) + } + if got, _ := getOwn("novox.gitea"); got != "tok-2" { + t.Errorf("get answered %q after the second put, want tok-2", got) + } } diff --git a/modules/mesh-vault/cmd/mesh-vault/move_test.go b/modules/mesh-vault/cmd/mesh-vault/move_test.go index 2f55ed3bc..5d70a69c0 100644 --- a/modules/mesh-vault/cmd/mesh-vault/move_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/move_test.go @@ -10,13 +10,14 @@ package main import ( "crypto/rand" "encoding/base64" - engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" - nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" - vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" "strings" "testing" "time" + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" + nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" + "git.novox.be/novox/mesh-sdk/go/seal" "golang.org/x/crypto/nacl/box" ) diff --git a/modules/mesh-vault/cmd/mesh-vault/noderotation.go b/modules/mesh-vault/cmd/mesh-vault/noderotation.go index 0c8dbc8be..99b292983 100644 --- a/modules/mesh-vault/cmd/mesh-vault/noderotation.go +++ b/modules/mesh-vault/cmd/mesh-vault/noderotation.go @@ -22,14 +22,15 @@ import ( "encoding/json" "errors" "fmt" - vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" - "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" "slices" "sort" "strings" "sync" "time" + vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" + "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" + stdio "git.novox.be/novox/mesh-sdk/go" "golang.org/x/crypto/bcrypt" ) diff --git a/modules/mesh-vault/cmd/mesh-vault/owncalls_test.go b/modules/mesh-vault/cmd/mesh-vault/owncalls_test.go index 74352692d..6607146b3 100644 --- a/modules/mesh-vault/cmd/mesh-vault/owncalls_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/owncalls_test.go @@ -10,7 +10,6 @@ import ( "encoding/base64" "encoding/json" "errors" - stdio "git.novox.be/novox/mesh-sdk/go" "strings" "sync" "testing" @@ -94,7 +93,6 @@ func aDesk(typed string, asked *[]map[string]any) func(string, map[string]any) ( // is typed opened here alone; what crossed is a key and a sealed box. func TestTheVaultAsksTheDesksPromptItselfAndOnlyASealedValueCrosses(t *testing.T) { v := newVault(t, AllowList{"anchor.node-provisioner": {"own/anchor/telegram/telegram-token"}}) - v.AskCallers = stdio.Callers{"g14.claude-code"} var asked []map[string]any mesh := &aMesh{desk: aDesk(typedAtTheDesk, &asked)} v.Ask = mesh.ask @@ -133,7 +131,6 @@ func TestTheVaultAsksTheDesksPromptItselfAndOnlyASealedValueCrosses(t *testing.T // Dismissed and timed out end the ask so, and keep nothing. for typed, outcome := range map[string]string{"": "dismissed", "\x00timeout": "timed-out"} { w := newVault(t, nil) - w.AskCallers = stdio.Callers{"g14.claude-code"} var a []map[string]any w.Ask = (&aMesh{desk: aDesk(typed, &a)}).ask got, err := w.AskAtDesk("g14.claude-code", telegramAsk("g14.claude-code")) @@ -149,7 +146,6 @@ func TestTheVaultAsksTheDesksPromptItselfAndOnlyASealedValueCrosses(t *testing.T } // Answered empty: the operator's answer, said so, nothing kept. e := newVault(t, nil) - e.AskCallers = stdio.Callers{"g14.claude-code"} var ea []map[string]any e.Ask = (&aMesh{desk: aDesk(" ", &ea)}).ask if got, err := e.AskAtDesk("g14.claude-code", telegramAsk("g14.claude-code")); err != nil || got.Outcome != "empty" { @@ -157,7 +153,6 @@ func TestTheVaultAsksTheDesksPromptItselfAndOnlyASealedValueCrosses(t *testing.T } // The desk cannot be asked: refused, recorded so. r := newVault(t, nil) - r.AskCallers = stdio.Callers{"g14.claude-code"} r.Ask = (&aMesh{}).ask if _, err := r.AskAtDesk("g14.claude-code", telegramAsk("g14.claude-code")); err == nil { t.Error("an ask nobody answered was said to be done") @@ -165,17 +160,18 @@ func TestTheVaultAsksTheDesksPromptItselfAndOnlyASealedValueCrosses(t *testing.T if asks, _ := r.Store.Asks(1); asks[0].Outcome != "refused" { t.Errorf("an unanswered desk recorded %+v", asks[0]) } - // Only the controller asks the vault to ask: anybody else is refused before any prompt. + // Every caller the runtime proved may ask the vault to ask (design 47 H §752, H-A-41); one it did not prove is refused + // before any prompt. n := newVault(t, nil) var na []map[string]any n.Ask = (&aMesh{desk: aDesk(typedAtTheDesk, &na)}).ask - for _, caller := range []string{"g14.node-tools", "g14.claude-code", "unproven", ""} { + for _, caller := range []string{"unproven", ""} { if _, err := n.AskAtDesk(caller, telegramAsk("x")); err == nil { t.Errorf("%q had the vault ask a desk", caller) } } if len(na) != 0 { - t.Fatal("a desk was asked for a caller that is not the controller") + t.Fatal("a desk was asked for a caller the runtime did not prove") } } diff --git a/modules/mesh-vault/cmd/mesh-vault/ownput.go b/modules/mesh-vault/cmd/mesh-vault/ownput.go new file mode 100644 index 000000000..ac5d00b9b --- /dev/null +++ b/modules/mesh-vault/cmd/mesh-vault/ownput.go @@ -0,0 +1,110 @@ +package main + +// A module's own secret, written by the module itself (design 47 H2 §822, H-A-345, H-A-349 DQ-7, H-A-360): `own-put` in +// two steps modelled on `licence-put` — name the secret and get a call and a key made for it, then send the call and the +// value sealed to that key. The vault keeps it as `module//`, the module named by the caller's account as +// the bus proved it (`.`, a bundle's call named so by the runtime), never by an argument, and keeps the +// newest generation only. `get` answers that full name to a caller of the same module alone, sealed to its key. Each +// write is said in the vault's journal, never the value. + +import ( + "errors" + "fmt" + "strings" + + stdio "git.novox.be/novox/mesh-sdk/go" +) + +// OwnPutVerb is the verb a module writes its own secret with. +const OwnPutVerb = "own-put" + +// modulePrefix starts the name of every secret a module wrote itself through own-put. +const modulePrefix = "module/" + +// callerModule is the module a proved caller is an account of, `.`, or why it is none: a person, a +// machine's provisioner client or node-engine, and the tool runner's own account answer no module's secret (H-A-360). +func callerModule(caller string) (string, error) { + machine, module, ok := strings.Cut(caller, ".") + switch { + case caller == "" || caller == stdio.Unproven: + return "", errors.New("a module's own secret answers a caller the runtime proves, and it proved none") + case !ok || machine == "" || module == "" || strings.Contains(module, "."), + machine == "person", machine == "node", machine+"." == ProvisionerPrefix, + module == toolRunnerModule: + return "", fmt.Errorf("%s is no module's account (.), so it has no own secret here", caller) + } + return stdio.ModuleOf(caller), nil +} + +// ModuleSecret is the vault's name of module's own secret name: `module//`. +func ModuleSecret(module, name string) (string, error) { + full := modulePrefix + module + "/" + name + if strings.TrimSpace(name) == "" { + return "", errors.New("own-put names the secret; nothing is taken") + } + if err := validName(full); err != nil { + return "", err + } + return full, nil +} + +// moduleSecretRefusal says whether name is a module's own secret written through own-put and, when it is, why caller +// may not have it ("" when caller is an account of that module). +func moduleSecretRefusal(caller, name string) (bool, string) { + rest, ok := strings.CutPrefix(name, modulePrefix) + if !ok { + return false, "" + } + owner, _, _ := strings.Cut(rest, "/") + module, err := callerModule(caller) + if err != nil { + return true, err.Error() + } + if module != owner { + return true, fmt.Sprintf("%s is %s's own secret, handed only to an account of %s", name, owner, owner) + } + return true, "" +} + +// OwnPutOpen opens a call to take a secret of the caller's module. +func (v *Vault) OwnPutOpen(caller, name string) (Opened, error) { + module, err := callerModule(caller) + if err != nil { + return Opened{}, err + } + secret, err := ModuleSecret(module, name) + if err != nil { + return Opened{}, err + } + id, key, err := v.openCall(OwnPutVerb, secret, caller, nil) + if err != nil { + return Opened{}, err + } + return Opened{Call: id, SealTo: key, Secret: secret}, nil +} + +// OwnPutTake opens the value sealed to the call's key and keeps it as the module's own, its newest generation only. +func (v *Vault) OwnPutTake(caller, call, sealed string) (Changed, error) { + c, err := v.takeCall(OwnPutVerb, call) + if err != nil { + return Changed{}, err + } + if c.by != caller { + return Changed{}, fmt.Errorf("the own-put call %q was opened by another caller; nothing was taken", call) + } + value, err := c.open(sealed) + if err != nil { + return Changed{}, err + } + defer zero(value) + if len(value) == 0 { + return Changed{}, errors.New("the value handed in is empty; nothing was taken") + } + changed, err := v.keepWith(c.secret, string(value), caller, OwnPutVerb, OriginAccepted, keepOptions{}) + if err != nil { + v.log("own-put of %s by %s refused: %v", c.secret, caller, err) + return Changed{}, err + } + v.log("own-put: %s kept at generation %d, written by %s", c.secret, changed.Generation, caller) + return changed, nil +} diff --git a/modules/mesh-vault/cmd/mesh-vault/ownretire.go b/modules/mesh-vault/cmd/mesh-vault/ownretire.go index b85d19363..1a86636a2 100644 --- a/modules/mesh-vault/cmd/mesh-vault/ownretire.go +++ b/modules/mesh-vault/cmd/mesh-vault/ownretire.go @@ -1,12 +1,9 @@ package main // The seat's verb `retire` (design 32 *A value no longer read*, novox/hq ADR 0609): one module's own secret on one node -// removed because no manifest reads it any more, asked by the holder of the seat mesh-config alone after the operator's -// Approve. Two proofs, both required: +// removed because no manifest reads it any more, asked after the operator's Approve; every caller may ask it (design 47 +// H §752, H-A-41). One proof is required: // -// - the caller is on the vault's list `retire-callers`, a trusted config value of the vault (ADR 0363's form, as -// mesh-mail-reader's `callers`), which names the holder of mesh-config alone, checked against the caller the tool -// runner proved (stdio.Callers); and // - the warrant (the verb's argument, as the seat's definition names it): the id of a hand act the caller recorded // through mesh-hand-acts for this verb, read back here, recent, naming exactly this node, module and secret and the // ask whose Approve it answers (ADR 0259 §6). An act for another name warrants nothing. @@ -17,8 +14,6 @@ package main import ( "fmt" "strings" - - stdio "git.novox.be/novox/mesh-sdk/go" ) // OwnRetiredEvent is what the vault says when it retired an own secret. @@ -47,18 +42,6 @@ type OwnRetired struct { Retired bool `json:"retired"` } -// fromRetireCallers refuses every caller the vault's list `retire-callers` does not name. -func (v *Vault) fromRetireCallers(caller string) error { - if !v.RetireCallers.Allows(caller) { - if strings.TrimSpace(caller) == "" { - caller = stdio.Unproven - } - return fmt.Errorf("retire is asked by the holder of the seat mesh-config alone, as the vault's list retire-callers "+ - "names it; %s is not on it (design 32)", caller) - } - return nil -} - // warrantsRetire reads the hand act back and refuses what it does not warrant for exactly this secret; it answers the // ask the act names. func (v *Vault) warrantsRetire(caller string, a RetireArgs) (ask string, err error) { @@ -99,9 +82,6 @@ func (v *Vault) warrantsRetire(caller string, a RetireArgs) (ask string, err err // RetireOwn removes one module's own secret on a node on the warrant of a hand act, and says `own-retired`. func (v *Vault) RetireOwn(caller string, a RetireArgs) (OwnRetired, error) { - if err := v.fromRetireCallers(caller); err != nil { - return OwnRetired{}, err - } secret, err := OwnSecret(a.Node, a.Module, a.Name) if err != nil { return OwnRetired{}, err diff --git a/modules/mesh-vault/cmd/mesh-vault/owntake.go b/modules/mesh-vault/cmd/mesh-vault/owntake.go index e5c0ca07e..f250c9d96 100644 --- a/modules/mesh-vault/cmd/mesh-vault/owntake.go +++ b/modules/mesh-vault/cmd/mesh-vault/owntake.go @@ -26,15 +26,16 @@ import ( "encoding/json" "errors" "fmt" - engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" - nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" - vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" "os" "path/filepath" "sort" "strings" "time" + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" + nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" + stdio "git.novox.be/novox/mesh-sdk/go" ) diff --git a/modules/mesh-vault/cmd/mesh-vault/placed.go b/modules/mesh-vault/cmd/mesh-vault/placed.go index fb37a1411..733206fd6 100644 --- a/modules/mesh-vault/cmd/mesh-vault/placed.go +++ b/modules/mesh-vault/cmd/mesh-vault/placed.go @@ -9,11 +9,12 @@ package main import ( "errors" "fmt" - assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" - placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" "slices" "sort" "strings" + + assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" + placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" ) // AssignerReader reads the seat's assignments: every key, and one key's value (nil when there is none). diff --git a/modules/mesh-vault/cmd/mesh-vault/retire_test.go b/modules/mesh-vault/cmd/mesh-vault/retire_test.go index 613764804..a40be7a25 100644 --- a/modules/mesh-vault/cmd/mesh-vault/retire_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/retire_test.go @@ -83,14 +83,13 @@ func TestAWantGoneRetiresItsAccountOnlyWithinTheBounds(t *testing.T) { } } -// 1966/CAT-V1 (design 32): `retire` removes one module's own secret on a node, and says own-retired, only for a caller on -// the vault's list retire-callers who carries a hand act it recorded for this verb naming exactly this node, module and -// secret. Without the act, with another name's, with another caller's or an older one, from a caller not on the list, or -// for a bus account, nothing is removed and nothing is said; a waiter on rotated or own-replaced is not woken. -func TestRetireRemovesAnOwnSecretOnlyOnTheWarrantOfTheListedCaller(t *testing.T) { +// 1966/CAT-V1 (design 32): `retire` removes one module's own secret on a node, and says own-retired, only for a caller +// who carries a hand act it recorded for this verb naming exactly this node, module and secret; every caller may ask it +// (design 47 H §752, H-A-41: no list of callers). Without the act, with another name's, with another caller's or an older +// one, or for a bus account, nothing is removed and nothing is said; a waiter on rotated or own-replaced is not woken. +func TestRetireRemovesAnOwnSecretOnlyOnTheCallersWarrant(t *testing.T) { v := newVault(t, nil) const caller = "novox.mesh-config" - v.RetireCallers = stdio.Callers{"mesh-config"} acts := map[string]*HandActSeen{} v.ReadAct = func(id string) (*HandActSeen, error) { return acts[id], nil } act := func(id, by, verb, what string, age time.Duration) { @@ -125,8 +124,7 @@ func TestRetireRemovesAnOwnSecretOnlyOnTheWarrantOfTheListedCaller(t *testing.T) {"no ask", caller, RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "ok"}, "names the ask"}, {"an act that names no ask", caller, RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "no-ask", Ask: "ret-1"}, "a warrant retires nothing else"}, {"an act older than a day", caller, RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "old", Ask: "ret-1"}, "older than"}, - {"a caller not on the list", "g14.claude-code", RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "other-caller", Ask: "ret-1"}, "retire-callers"}, - {"an unproven caller", stdio.Unproven, RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "ok", Ask: "ret-1"}, "retire-callers"}, + {"an unproven caller", stdio.Unproven, RetireArgs{Node: "g14", Module: "dunst", Name: "token", Warrant: "ok", Ask: "ret-1"}, "was recorded by novox.mesh-config"}, {"the tool runner's ledgers", caller, RetireArgs{Node: "g14", Module: "node-tools", Name: "ledgers", Warrant: "ledgers", Ask: "ret-1"}, "bus account or the tool runner's ledgers"}, } { t.Run(tc.name, func(t *testing.T) { diff --git a/modules/mesh-vault/cmd/mesh-vault/rotation_integration_test.go b/modules/mesh-vault/cmd/mesh-vault/rotation_integration_test.go index 4feb85df4..5a274a589 100644 --- a/modules/mesh-vault/cmd/mesh-vault/rotation_integration_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/rotation_integration_test.go @@ -15,11 +15,6 @@ import ( "encoding/base64" "encoding/json" "errors" - assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" - engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" - placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" - nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" - vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" "os" "os/exec" "path/filepath" @@ -28,6 +23,12 @@ import ( "testing" "time" + assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" + placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" + nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" + "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" "golang.org/x/crypto/bcrypt" diff --git a/modules/mesh-vault/cmd/mesh-vault/signing.go b/modules/mesh-vault/cmd/mesh-vault/signing.go index db4cd9ec2..0ba246247 100644 --- a/modules/mesh-vault/cmd/mesh-vault/signing.go +++ b/modules/mesh-vault/cmd/mesh-vault/signing.go @@ -16,11 +16,12 @@ import ( "encoding/pem" "errors" "fmt" + "strings" + "time" + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" enrollerclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshnodeenrollerclient" vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" - "strings" - "time" "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" diff --git a/modules/mesh-vault/cmd/mesh-vault/signing_test.go b/modules/mesh-vault/cmd/mesh-vault/signing_test.go index 8abf89c51..980f02182 100644 --- a/modules/mesh-vault/cmd/mesh-vault/signing_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/signing_test.go @@ -5,14 +5,15 @@ import ( "crypto/rand" "encoding/base64" "encoding/json" + "strings" + "testing" + assignerclient "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient" engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" placing "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner" nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" vaultclient "git.novox.be/novox/mesh-contracts/identity-and-access/go/clients/meshvaultclient" "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshvault" - "strings" - "testing" "git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay" "git.novox.be/novox/mesh-sdk/go/seal" diff --git a/modules/mesh-vault/cmd/mesh-vault/tools.go b/modules/mesh-vault/cmd/mesh-vault/tools.go index ad424f8fa..3b78a65e2 100644 --- a/modules/mesh-vault/cmd/mesh-vault/tools.go +++ b/modules/mesh-vault/cmd/mesh-vault/tools.go @@ -12,13 +12,14 @@ import ( "encoding/json" "errors" "fmt" - "git.novox.be/novox/mesh-sdk/go/seal" "os" "path/filepath" "strings" "sync" "time" + "git.novox.be/novox/mesh-sdk/go/seal" + stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -230,6 +231,26 @@ func definitions(env *Env) []toolDef { g, _ := a["generation"].(float64) return v.LicencePutOpen(caller, arg(a, "licence"), arg(a, "part"), int(g)) }}, + {Name: Seat + "." + OwnPutVerb, + Description: "Store a secret as the calling module's own (design 47 H2 §822), in two steps: name the secret and " + + "get a call and a key made for it; then send the call and the value sealed to that key. Kept as " + + "module//, the module named by the caller's account as the bus proved it, never by an " + + "argument, its newest generation only; get answers that name to an account of the same module alone. " + + "Answers the call and the key, then the secret's name and generation; never the value.", + Input: map[string]any{"type": "object", "properties": map[string]any{ + "name": str("the first step: the secret's name, among the calling module's own"), + "call": str("the second step: the call the first step answered"), + "sealed": str("the second step: the value sealed to the call's key (NaCl anonymous box, base64) — never the value")}}, + run: func(caller string, a map[string]any) (any, error) { + v, err := env.ready() + if err != nil { + return nil, err + } + if call := arg(a, "call"); call != "" { + return v.OwnPutTake(caller, call, arg(a, "sealed")) + } + return v.OwnPutOpen(caller, arg(a, "name")) + }}, {Name: Seat + ".move-in", Description: "Take one value of the controller's store into the vault, as it is (design 57's V3): from the " + "node-engine of a machine it was sealed to, and no other caller, in two steps — name the row (node, " + diff --git a/modules/mesh-vault/cmd/mesh-vault/tools_test.go b/modules/mesh-vault/cmd/mesh-vault/tools_test.go index da747cdea..daabdb6ad 100644 --- a/modules/mesh-vault/cmd/mesh-vault/tools_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/tools_test.go @@ -6,14 +6,15 @@ package main import ( "encoding/base64" "encoding/json" - engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" - nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "os" "path/filepath" "strings" "testing" "time" + engineclient "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" + nodeseat "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + "git.novox.be/novox/mesh-sdk/go/seal" ) diff --git a/modules/mesh-vault/cmd/mesh-vault/vault.go b/modules/mesh-vault/cmd/mesh-vault/vault.go index aac01cdf1..bdccc343f 100644 --- a/modules/mesh-vault/cmd/mesh-vault/vault.go +++ b/modules/mesh-vault/cmd/mesh-vault/vault.go @@ -46,12 +46,8 @@ type Vault struct { // account (ADR 0259 §8's runs-as, issue 723): the desks' secret prompt and each issuing provider's tool, which // the bus lets the vault's account alone call in its own name. Nil asks nobody. Ask func(key string, body any) (json.RawMessage, error) - // AskCallers are the callers besides the controller that may ask secret-ask themselves, as the vault's manifest names - // them (MESH_VAULT_SECRET_ASK_CALLERS; novox/hq ADR 0563 §8): each is named by the runtime's proof. Empty: the - // controller alone. - AskCallers stdio.Callers - Now func() time.Time - Log func(format string, args ...any) + Now func() time.Time + Log func(format string, args ...any) // Accounts is the vault's state of bus-account hashes (accounts.go, ADR 0547 clause 9): nil writes none. Accounts AccountStore // HashCost is the bcrypt cost of those hashes: zero is the controller's, bcrypt's default. @@ -82,10 +78,7 @@ type Vault struct { Signers SignersStore // EnrolCallers are the callers of the enrolment verbs `enrolment-token` and `node-account` and of `sign` for an // enrolment: the seat mesh-node-enroller (enrolment.go). Nil: that module alone. - EnrolCallers stdio.Callers - // RetireCallers are the callers of the seat's verb `retire`: the vault's trusted config value `retire-callers`, the - // holder of the seat mesh-config alone (ownretire.go). Nil: nobody. - RetireCallers stdio.Callers + EnrolCallers callers // TokenBase says where the bus is and its certificate's fingerprint, for the token shown (enrolment.go): nil shows none. TokenBase func() (TokenBase, error) // Logins is the vault's state node-logins (noderotation.go): nil writes none. @@ -390,8 +383,16 @@ func (v *Vault) Get(caller, name, publicKey string) (Answer, error) { return Answer{}, fmt.Errorf("%s may not ask for %s: %s", caller, name, why) } isLicence, licenceWhy := v.licenceRefusal(caller, name) + isModule, moduleWhy := moduleSecretRefusal(caller, name) if isLogin { // Judged above: the node's own engine, sealed to its own key. + } else if isModule { + // A module's own secret written through own-put, to an account of that module alone (design 47 H2 §822). + if moduleWhy != "" { + v.log("refused %s to %s: %s", name, caller, moduleWhy) + _ = v.recordHanding(Handing{To: caller, Name: name, Outcome: "refused", Why: moduleWhy}) + return Answer{}, fmt.Errorf("%s may not ask for %s: %s", caller, name, moduleWhy) + } } else if isLicence { // A licence's secret, by the licence rule (design 39 bus-and-switch §16, §17). if licenceWhy != "" { diff --git a/modules/mesh-vault/files/retire-callers.json b/modules/mesh-vault/files/retire-callers.json deleted file mode 100644 index 6d0792abe..000000000 --- a/modules/mesh-vault/files/retire-callers.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "callers": ["mesh-config"] -} diff --git a/modules/mesh-vault/module.json b/modules/mesh-vault/module.json index a29064c11..1e9300a8e 100644 --- a/modules/mesh-vault/module.json +++ b/modules/mesh-vault/module.json @@ -1,6 +1,7 @@ { "module": "mesh-vault", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate": "0.1" }, @@ -149,25 +150,16 @@ "mode": "0700", "owner": "mesh-vault", "unknown": "program" - }, - { - "id": "retire-callers", - "trusted": true, - "type": "file", - "path": "${dir:state}/retire-callers.json", - "mode": "0600", - "owner": "mesh-vault", - "merge": "json", - "template": "files/retire-callers.json", - "takes-config": [ - "retire-callers" - ] } ], "streams": [ { "name": "mesh-vault-findings", - "events": ["finding-written.*", "finding-cleared.*", "findings-stated.*"], + "events": [ + "finding-written.*", + "finding-cleared.*", + "findings-stated.*" + ], "max-age-days": 7, "max-mib": 16 } @@ -190,15 +182,8 @@ "MESH_VAULT_ROOT": "${dir:root}", "MESH_VAULT_STORE": "${dir:store}", "MESH_VAULT_STATE": "${dir:state}", - "MESH_VAULT_SECRET_ASK_CALLERS": "node-tools", - "MESH_VAULT_ENROLMENT_CALLERS": "mesh-enrolment", - "MESH_VAULT_RETIRE_CALLERS": "${dir:state}/retire-callers.json" + "MESH_VAULT_ENROLMENT_CALLERS": "mesh-enrolment" } - }, - { - "name": "files", - "kind": "archive", - "from": "files" } ] }, @@ -249,23 +234,14 @@ "node-account-confirm", "abandon", "retire", - "licence-put" + "licence-put", + "own-put" ] } ], - "config": { - "retire-callers": { - "type": "list", - "description": "Who may call the seat's verb retire, which removes one module's own secret on a node because no manifest reads it any more: a module's name (on every machine), ., or person.. The holder of the seat mesh-config alone by default (design 32); the verb also needs a hand act the caller recorded for exactly that node, module and secret.", - "trusted": true, - "default": [ - "mesh-config" - ] - } - }, "consumes": [ "mesh-delivery-assigner.views.assignments", "mesh-conditions.findings-asked", - "claude-licence-manager.binding.changed" + "claude-licence-manager.binding.changed.*" ] } diff --git a/modules/mesh-watcher/module.json b/modules/mesh-watcher/module.json index 020e049a6..23877ef24 100644 --- a/modules/mesh-watcher/module.json +++ b/modules/mesh-watcher/module.json @@ -1,6 +1,7 @@ { "module": "mesh-watcher", "version": "0.1", + "class": "leaf", "slug": "watch", "consumes": [ "mesh-self-check.checked", @@ -92,7 +93,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/messenger/cmd/messenger/asks.go b/modules/messenger/cmd/messenger/asks.go index 729ee7af9..133503419 100644 --- a/modules/messenger/cmd/messenger/asks.go +++ b/modules/messenger/cmd/messenger/asks.go @@ -46,6 +46,12 @@ const StateOpen = "open" // expiry, and offered the moment a channel can carry it (novox/hq ADR 0397, issue 926). It counts as open. const StateHeld = "held" +// liveState is whether an ask has not ended: offered, or held for want of a channel. The channel holds no ask back behind +// its asker's newer ones (design 47 H §764, H-A-57). +func liveState(state string) bool { + return state == StateOpen || state == StateHeld +} + // Ticket is one option's one-time ticket on one channel kind. type Ticket struct { Option string `json:"option"` @@ -65,9 +71,6 @@ type AskRecord struct { Warrant *oc.Warrant `json:"warrant,omitempty"` // Told: the warrant, or the end, was published to the asker. Told bool `json:"told,omitempty"` - // HeldBackSince is, while the ask is held back, since when: kept open behind newer asks of its asker, its tickets - // withdrawn, offered again when one of its asker's offered asks ends (novox/hq ADR 0666 §12). - HeldBackSince time.Time `json:"held-back-since,omitempty"` // HeldSince and HeldWhy say, while the ask is held, since when and why no channel can carry it: per kind, the // reason from the judgement that judges an answer. The asker reads them in this record, as it reads // the state (the asks protocol has no word for a held ask on `decided`, which means an ask ended). @@ -564,7 +567,7 @@ func (h *Holder) TakeAsk(verb, asker string, body json.RawMessage) error { return nil } // Every ask is offered when it is raised: the channel keeps no count of an asker's open asks and holds none back for room - // (design 47 G A-424). An ask with the same `about` replaces the open one, a held-back one of before too. + // (design 47 G A-424; H §764). An ask with the same `about` replaces the open one. replaced := "" h.mu.Lock() for k, e := range h.asks { @@ -646,6 +649,9 @@ func (h *Holder) holdWhy(a oc.Ask) string { } parts = append(parts, why) } + case answerLevel(a) == occ.Destroy: + // Design 47 H-A-237 (3): the held ask names its level, which no channel carries yet (carriers). + parts = append(parts, Display(k.Kind)+": the ask is at the destroy level, and no channel carries a destroy answer yet (it needs a code)") } } if len(parts) == 0 { @@ -963,9 +969,7 @@ func (h *Holder) closeAsk(key string, outcome string, words string, w *oc.Warran return ErrChanged } now := h.Now() - freed := rec.State == StateOpen || rec.State == StateHeld // a slot of the asker's offered asks, unless a newer ask takes it rec.State = string(outcome) - rec.HeldBackSince = time.Time{} rec.HeldWhy = "" rec.Closed = now if t, ok := rec.Tickets[used]; ok { @@ -989,9 +993,6 @@ func (h *Holder) closeAsk(key string, outcome string, words string, w *oc.Warran rev = newRev } h.keepAsk(key, rec, rev) - if freed && outcome != occ.OutcomeReplaced { - defer h.offerHeldBack(rec.Asker) - } h.sayClosed(key, rec, outcome, words) if rec.Asker == SelfAsker { // The router's own ask: it does what was decided, and tells nobody else (selfact.go). @@ -1261,8 +1262,6 @@ func (h *Holder) judge(kind string, c oc.Choice, key string, root func(KindInfo) return "chosen", nil } switch { - case rec.State == StateHeldBack: - return h.refuseChoice(kind, c, "the question waits behind newer questions of its asker, and is offered again when one of them ends") case !issued: return h.refuseChoice(kind, c, "it belongs to no ask this router holds") case t.Kind != kind: @@ -1454,10 +1453,6 @@ type AskView struct { // HeldSince and HeldWhy: while the ask is held, since when and why no channel can carry it yet (ADR 0397 §4). HeldSince string `json:"held_since,omitempty"` HeldWhy string `json:"held_why,omitempty"` - // HeldBackSince and Behind: while the ask is held back (ADR 0666 §12), since when and the keys of the newer asks of its - // asker it waits behind, in the names of the seat operator-channel's asks answer. - HeldBackSince string `json:"held-since,omitempty"` - Behind []string `json:"behind,omitempty"` } // AsksNow is every ask, open first, newest first. @@ -1472,9 +1467,6 @@ func (h *Holder) AsksNow() []AskView { if e.rec.State == StateHeld { v.HeldSince, v.HeldWhy = e.rec.HeldSince.UTC().Format(time.RFC3339), e.rec.HeldWhy } - if e.rec.State == StateHeldBack { - v.HeldBackSince, v.Behind = e.rec.HeldBackSince.UTC().Format(time.RFC3339), h.behindLocked(k, e.rec) - } kinds := map[string]bool{} for _, t := range e.rec.Tickets { kinds[t.Kind] = true @@ -1554,7 +1546,7 @@ func (h *Holder) sayClosed(key string, rec AskRecord, outcome string, words stri } } -// AsksQuery narrows what the tool `operator-channel.asks` answers (issue 595): Key one ask, State open (open, held and held-back) or +// AsksQuery narrows what the tool `operator-channel.asks` answers (issue 595): Key one ask, State open (open and held) or // ended (all takes both), Since the asks opened at or after that time, Bound the most bytes of the answer's asks. With no // argument at all the query is the open asks within DefaultAsksBound (issue 1974), and the answer says so. type AsksQuery struct { diff --git a/modules/messenger/cmd/messenger/holdback.go b/modules/messenger/cmd/messenger/holdback.go deleted file mode 100644 index d08d22b6c..000000000 --- a/modules/messenger/cmd/messenger/holdback.go +++ /dev/null @@ -1,177 +0,0 @@ -package main - -import ( - "fmt" - oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" - "sort" - "time" -) - -// An ask held back (novox/hq ADR 0666 §12, design 46 § 6) was one kept open behind newer asks of its asker, offered again when -// one of them ended. The channel holds none back any more (design 47 G A-424): every ask is offered when it is raised, and one -// held back before the change is offered at the router's start (offerAllHeldBack) and by ask-again. `held` is another state, an -// ask no ready channel can carry (ADR 0397). - -// StateHeldBack is an ask kept open behind newer asks of its asker. -const StateHeldBack = "held-back" - -// liveState is whether an ask has not ended: offered, held for want of a channel, or held back. -func liveState(state string) bool { - return state == StateOpen || state == StateHeld || state == StateHeldBack -} - -// behindLocked are the keys of the newer offered asks of the asker of rec, oldest first; h.mu is held. -func (h *Holder) behindLocked(key string, rec AskRecord) []string { - var behind []string - for k, e := range h.asks { - if k != key && e.rec.Asker == rec.Asker && (e.rec.State == StateOpen || e.rec.State == StateHeld) && e.rec.Opened.After(rec.Opened) { - behind = append(behind, k) - } - } - sort.Slice(behind, func(i, j int) bool { - a, b := h.asks[behind[i]].rec, h.asks[behind[j]].rec - if !a.Opened.Equal(b.Opened) { - return a.Opened.Before(b.Opened) - } - return behind[i] < behind[j] - }) - return behind -} - -// pickLocked is the key of the asker's asks in one of the states, the oldest first (by opening, then key); "" when -// there is none, never except; h.mu is held. -func (h *Holder) pickLocked(asker, except string, states ...string) string { - pick := "" - for k, e := range h.asks { - if e.rec.Asker != asker || k == except { - continue - } - in := false - for _, s := range states { - in = in || e.rec.State == s - } - if !in { - continue - } - if pick == "" || e.rec.Opened.Before(h.asks[pick].rec.Opened) || (e.rec.Opened.Equal(h.asks[pick].rec.Opened) && k < pick) { - pick = k - } - } - return pick -} - -// offeredCount is how many of the asker's asks are offered now: open, or held for want of a channel. -func (h *Holder) offeredCount(asker string) int { - h.mu.Lock() - defer h.mu.Unlock() - n := 0 - for _, e := range h.asks { - if e.rec.Asker == asker && (e.rec.State == StateOpen || e.rec.State == StateHeld) { - n++ - } - } - return n -} - -// freshAsk is an ask's record read again from the store, where there is one. -func (h *Holder) freshAsk(key string) (AskRecord, uint64, bool) { - e := h.askOf(key) - if e == nil { - return AskRecord{}, 0, false - } - rec, rev := e.rec, e.rev - if h.Asks != nil { - if got, r, err := h.Asks.GetAsk(key); err == nil && got != nil { - rec, rev = *got, r - } - } - return rec, rev, true -} - -// offerHeldBack offers the asker's held-back asks of before the change again (A-424): there is no room to wait for. The work -// lock is held. -func (h *Holder) offerHeldBack(asker string) { - for { - h.mu.Lock() - key := h.pickLocked(asker, "", StateHeldBack) - h.mu.Unlock() - if key == "" { - return - } - h.offerOneHeldBack(key) - if after := h.askOf(key); after == nil || after.rec.State == StateHeldBack { - return // not offered (its record changed meanwhile): left for the next start rather than tried forever - } - } -} - -// offerAllHeldBack offers every ask held back before the change, at each tick of the router (A-424). The work lock is held. -func (h *Holder) offerAllHeldBack() { - h.mu.Lock() - askers := map[string]bool{} - for _, e := range h.asks { - if e.rec.State == StateHeldBack { - askers[e.rec.Asker] = true - } - } - h.mu.Unlock() - for asker := range askers { - h.offerHeldBack(asker) - } -} - -// offerOneHeldBack offers one held-back ask again now. -func (h *Holder) offerOneHeldBack(key string) { - rec, rev, ok := h.freshAsk(key) - if !ok || rec.State != StateHeldBack { - return - } - now := h.Now() - rec.HeldBackSince = time.Time{} - rec.Tickets = h.ticketsFor(rec.Ask) - rec.State = StateOpen - if len(rec.Tickets) == 0 { - rec.Tickets, rec.State, rec.HeldSince, rec.HeldWhy = nil, StateHeld, now, h.holdWhy(rec.Ask) - } - if !h.saveHeld(key, rec, rev) { - return - } - h.Logf("[messenger] %s's ask %q (%s) is offered again", rec.Asker, rec.Ask.Headline, rec.Ask.ID) - if rec.State != StateOpen { - return - } - h.mu.Lock() - r := h.open[rec.Record] - h.mu.Unlock() - if r != nil && r.Origin == "ask" { - h.mu.Lock() - r.Answered, r.Ask = "", key - h.mu.Unlock() - h.offerAsk(r) - h.persist(r) - return - } - rec.Record = h.recordFor(rec.Asker, key, rec.Ask) - h.showAsk(key, rec, now) -} - -// AskAgain is the seat operator-channel's verb ask-again (G §394, §450): it offers an ask held back before the channel stopped -// holding any back (A-424), and holds back nothing in its place. It answers the ask's state after it, or the error that says why -// it was not offered. -func (h *Holder) AskAgain(key string) oc.AskAgainAnswer { - h.work.Lock() - defer h.work.Unlock() - h.mu.Lock() - h.init() - h.mu.Unlock() - rec, _, ok := h.freshAsk(key) - switch { - case !ok: - return oc.AskAgainAnswer{Error: fmt.Sprintf("this router holds no ask %q: its key is ., as operator-channel.asks lists", key)} - case rec.State != StateHeldBack: - return oc.AskAgainAnswer{Error: fmt.Sprintf("the ask %s is %s, not held back: only a held-back ask is offered again, and the channel holds none back any more", key, rec.State)} - } - h.offerOneHeldBack(key) - got, _, _ := h.freshAsk(key) - return oc.AskAgainAnswer{State: string(got.State)} -} diff --git a/modules/messenger/cmd/messenger/holdback_test.go b/modules/messenger/cmd/messenger/holdback_test.go deleted file mode 100644 index 9e0d8d4e1..000000000 --- a/modules/messenger/cmd/messenger/holdback_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package main - -import ( - "encoding/json" - "strings" - "testing" - "time" - - occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" -) - -// Design 47 G A-424: the channel keeps no count of an asker's open asks and holds none back: every ask is offered when it is -// raised, five of one asker at once too, and none is refused. An ask held back before the change is offered again at the -// router's next tick, with new tickets; ask-again offers one now and holds nothing back in its place. -func TestEveryAskIsOfferedAndOneHeldBackBeforeIsOfferedAgain(t *testing.T) { - h, _, _, c, store, w := newRouter(t) - link(h, store, c, "42", c.now().Add(-2*time.Hour)) - state := func(id string) string { return store.asks["mesh-delivery."+id].State } - for i, id := range []string{"d-1", "d-2", "d-3", "d-4", "d-5"} { - a := ackAsk(c, id) - a.About = "about-" + string(rune('1'+i)) - submit(t, h, "mesh-delivery", a) - c.pass(time.Second) - settle(h, c) - } - for _, id := range []string{"d-1", "d-2", "d-3", "d-4", "d-5"} { - if state(id) != StateOpen || len(store.asks["mesh-delivery."+id].Tickets) == 0 { - t.Fatalf("%s is %s with %d tickets: every ask is offered", id, state(id), len(store.asks["mesh-delivery."+id].Tickets)) - } - } - // One held back before the change, as the store kept it. - key := "mesh-delivery.d-2" - got, rev, _ := store.GetAsk(key) - got.State, got.Tickets, got.HeldBackSince = StateHeldBack, nil, c.now() - rev, err := store.UpdateAsk(key, *got, rev) - if err != nil { - t.Fatal(err) - } - h.keepAsk(key, *got, rev) - if a := h.AskAgain("mesh-delivery.d-1"); !strings.Contains(a.Error, "not held back") { - t.Errorf("ask-again of an offered ask: %+v", a) - } - if a := h.AskAgain("mesh-delivery.d-none"); a.Error == "" || a.State != "" { - t.Errorf("ask-again of an ask the router holds none of: %+v", a) - } - h.Tick() - settle(h, c) - if rec := store.asks[key]; rec.State != StateOpen || len(rec.Tickets) == 0 || !rec.HeldBackSince.IsZero() { - t.Fatalf("the ask held back before the change, after a tick: %+v", rec) - } - for _, id := range []string{"d-1", "d-3", "d-4", "d-5"} { - if state(id) != StateOpen { - t.Errorf("%s is %s after the held-back one was offered: nothing is held back in its place", id, state(id)) - } - } - for _, wt := range w.of("mesh-delivery") { - if wt.Outcome == occ.OutcomeRefused { - t.Errorf("refused: %+v", wt) - } - } -} - -func mustJSON(v any) []byte { raw, _ := json.Marshal(v); return raw } diff --git a/modules/messenger/cmd/messenger/holder.go b/modules/messenger/cmd/messenger/holder.go index 09debb721..d87b60e68 100644 --- a/modules/messenger/cmd/messenger/holder.go +++ b/modules/messenger/cmd/messenger/holder.go @@ -778,7 +778,6 @@ func (h *Holder) Tick() { h.mu.Unlock() sort.Slice(recs, func(i, j int) bool { return recs[i].Raised.Before(recs[j].Raised) }) h.sweepAsks(now) - h.offerAllHeldBack() // held back before the channel stopped holding any back, offered at the first tick (design 47 G A-424) h.releaseHeld() h.offerUnsent() h.breakGlass() diff --git a/modules/messenger/cmd/messenger/main.go b/modules/messenger/cmd/messenger/main.go index e74264b9f..ac39a618a 100644 --- a/modules/messenger/cmd/messenger/main.go +++ b/modules/messenger/cmd/messenger/main.go @@ -761,7 +761,7 @@ func tools(h *Holder, l *listening) []stdio.Tool { "most bytes of the answer.", Input: map[string]any{ "key": str("one ask, by its key (asker.id); none for the open asks"), - "state": str("open (open, held and held-back), ended or all; none is open when no key or since is given, else both"), + "state": str("open (open and held), ended or all; none is open when no key or since is given, else both"), "since": str("only the asks opened at or after this time, RFC 3339"), "bound": map[string]any{"type": "integer", "description": "the most bytes of the asks in the answer; said when it cuts the answer short"}}, Run: func(a map[string]any) (any, error) { @@ -771,15 +771,6 @@ func tools(h *Holder, l *listening) []stdio.Tool { } return q.Narrow(h.AsksNow()), nil }}, - {Name: "operator-channel." + oc.VerbAskAgain, - Description: "Offer a held-back ask again now (G §394, §450): an asker has at most three asks offered at once, and a fourth " + - "holds its oldest back behind it (operator-channel.asks lists it with state held-back, since when and the newer asks it waits behind). " + - "It is offered again by itself when one of the asker's asks ends; this offers it now, holding back the asker's oldest offered ask in its " + - "place. Answers the ask's state, or why it was not offered (an ask that is not held back).", - Input: map[string]any{"key": str("the held-back ask, by its key (asker.id)")}, - Run: func(a map[string]any) (any, error) { - return h.AskAgain(strArg(a, "key")), nil - }}, {Name: "messenger_identities", Description: "The accounts linked as the operator, one per channel kind: the account, the name its " + "service shows, when it was linked, and from when it can approve (an hour after linking).", diff --git a/modules/messenger/cmd/messenger/manifest_test.go b/modules/messenger/cmd/messenger/manifest_test.go index 354ed6f63..3145cc45e 100644 --- a/modules/messenger/cmd/messenger/manifest_test.go +++ b/modules/messenger/cmd/messenger/manifest_test.go @@ -68,7 +68,7 @@ func readManifest(t *testing.T) (manifest, string) { func TestItDeclaresTheSeatsOfAnAskAndHoldsTheOperatorChannel(t *testing.T) { // 1217/AC6: condition beside ask and cancel m, _ := readManifest(t) - verbs := []string{"open", "history", "notify", "tell", "asks", oc.VerbAskAgain} + verbs := oc.Verbs() // every verb of the seat, and no more: ask-again went with the channel's limit (design 47 H §764) want := []seat{ {Name: oc.Seat, Scope: "mesh", Serves: verbs, Accepts: []string{"ask", "cancel", "condition"}, Emits: []string{"decided"}, ByCaller: []string{"ask", "cancel", "condition", "decided"}, Records: []string{"asks"}}, diff --git a/modules/messenger/cmd/messenger/review_test.go b/modules/messenger/cmd/messenger/review_test.go index 1bcac1d5b..51f01003e 100644 --- a/modules/messenger/cmd/messenger/review_test.go +++ b/modules/messenger/cmd/messenger/review_test.go @@ -149,6 +149,12 @@ func TestAFailedRootAskIsSaidAndKeepsAFreshWord(t *testing.T) { if why := h.holdWhy(heldAsk(c, "d-9")); !strings.Contains(why, "no responders") { t.Errorf("a held ask does not say why: %q", why) } + // Design 47 H-A-237 (3): an ask held at the destroy level says its level, which no channel carries yet. + destroy := heldAsk(c, "d-10") + destroy.Options[0].Level = occ.Destroy + if why := h.holdWhy(destroy); !strings.Contains(why, "destroy level") || !strings.Contains(why, "no channel carries a destroy answer yet") { + t.Errorf("a destroy ask held does not name its level: %q", why) + } } // H3: a message rendered while root is not free offers no approval; a word kept for rendering is never the diff --git a/modules/messenger/module.json b/modules/messenger/module.json index f3b66dd47..4f89a31b8 100644 --- a/modules/messenger/module.json +++ b/modules/messenger/module.json @@ -1,6 +1,7 @@ { "module": "messenger", "version": "0.1", + "class": "core", "slug": "msgr", "runs-as": "messenger", "seats": [ @@ -12,8 +13,7 @@ "history", "notify", "tell", - "asks", - "ask-again" + "asks" ], "accepts": [ "ask", @@ -67,8 +67,7 @@ "history", "notify", "tell", - "asks", - "ask-again" + "asks" ] } ], diff --git a/modules/minio/module.json b/modules/minio/module.json index 4f829c495..956a69fb6 100644 --- a/modules/minio/module.json +++ b/modules/minio/module.json @@ -1,6 +1,7 @@ { "module": "minio", "version": "0.1", + "class": "core", "upgrade": { "policy": "record", "why": "holds the photos themselves (irreplaceable, kept by photos) for its consumers: a person takes each build, after a backup (hq ADR 0236)" @@ -36,7 +37,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ], diff --git a/modules/model-usage/module.json b/modules/model-usage/module.json index 6e5b3c96f..86ef6f202 100644 --- a/modules/model-usage/module.json +++ b/modules/model-usage/module.json @@ -1,6 +1,7 @@ { "module": "model-usage", "version": "0.1", + "class": "leaf", "slug": "usage", "capabilities": [ "container-runtime" diff --git a/modules/mongodb/module.json b/modules/mongodb/module.json index 5e0961211..27ab92027 100644 --- a/modules/mongodb/module.json +++ b/modules/mongodb/module.json @@ -1,6 +1,7 @@ { "module": "mongodb", "version": "0.1", + "class": "leaf", "upgrade": { "policy": "record", "why": "a provider whose restart drops every consumer on its machine, and which holds the photos' albums (irreplaceable, kept by photos): a person takes each build, after a backup (hq ADR 0236)" diff --git a/modules/mosquitto/module.json b/modules/mosquitto/module.json index e1e0bf0c6..a8bb15153 100644 --- a/modules/mosquitto/module.json +++ b/modules/mosquitto/module.json @@ -1,6 +1,7 @@ { "module": "mosquitto", "version": "0.1", + "class": "leaf", "slug": "mosq", "provides": [ { diff --git a/modules/mounts/module.json b/modules/mounts/module.json index cd89f3659..2da577468 100644 --- a/modules/mounts/module.json +++ b/modules/mounts/module.json @@ -1,6 +1,7 @@ { "module": "mounts", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings": "0.1" }, diff --git a/modules/mssql/module.json b/modules/mssql/module.json index a34bcea2e..52f62daa9 100644 --- a/modules/mssql/module.json +++ b/modules/mssql/module.json @@ -1,6 +1,7 @@ { "module": "mssql", "version": "0.1", + "class": "leaf", "upgrade": { "policy": "record", "why": "a provider whose restart drops every consumer on its machine, and whose new version may upgrade its databases in place: a person takes each build, after a backup (hq ADR 0236)" diff --git a/modules/n8n/module.json b/modules/n8n/module.json index bdbfbd24d..d67bc7a60 100644 --- a/modules/n8n/module.json +++ b/modules/n8n/module.json @@ -1,6 +1,7 @@ { "module": "n8n", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/nats/cmd/nats-tools/catalogview.go b/modules/nats/cmd/nats-tools/catalogview.go index 095a49362..a4a21b4c6 100644 --- a/modules/nats/cmd/nats-tools/catalogview.go +++ b/modules/nats/cmd/nats-tools/catalogview.go @@ -45,11 +45,15 @@ func AsksOf(e catalog.CatalogEntry) (Asks, error) { return Asks{}, fmt.Errorf("the manifest of %s is not readable: %w", e.Module, err) } state := m.BusState + // The old sections' entries are asked for too (design 47 H H-A-229, H-A-230), every manifest's, named and capped as + // the grants part composes them. + m.Module = cmp.Or(m.Module, e.Module) + old := keeper.OldPlansOf(m) if e.Verdict != "" && e.Verdict != "accepted" { - state = nil + state, old = nil, nil } sum := sha256.Sum256(mustJSON(state)) - out := Asks{Accepted: keeper.Accepted{Module: e.Module, Digest: hex.EncodeToString(sum[:]), BusState: state}, + out := Asks{Accepted: keeper.Accepted{Module: e.Module, Digest: hex.EncodeToString(sum[:]), BusState: state, Old: old}, EmitsOwn: len(m.Emits) > 0 || len(e.Streams) > 0} for _, c := range m.Claims { out.Claims = append(out.Claims, c.Name) @@ -81,7 +85,7 @@ type Branch struct { // branches in its registration's order (order: the registration's branches; a branch it does not name comes after, in // the order given) whose entry asks it; another branch asking that local name with other settings is a drift naming // the branch, and plans nothing. The module sends when a branch's entry says so; it is a foundation part, and its old -// sections' caps are read, from the first branch. +// sections' caps and entries are read, from the first branch (design 47 H H-A-229). func ViewOf(branches []Branch, order func(module string) []string) (keeper.CatalogView, error) { modules := map[string]bool{} for _, b := range branches { @@ -117,8 +121,8 @@ func ViewOf(branches []Branch, order func(module string) []string) (keeper.Catal return keeper.CatalogView{}, fmt.Errorf("the branch %s: %w", b.Name, err) } if i == 0 { - cm = keeper.CatalogModule{Accepted: keeper.Accepted{Module: module, Digest: b.Entries[module].ManifestDigest, Revision: uint64(max(b.Revision, 0))}, - Foundation: a.Foundation, OldBytes: a.OldBytes} + cm = keeper.CatalogModule{Accepted: keeper.Accepted{Module: module, Digest: b.Entries[module].ManifestDigest, Revision: uint64(max(b.Revision, 0)), + Old: a.Accepted.Old}, Foundation: a.Foundation, OldBytes: a.OldBytes} } cm.EmitsOwn = cm.EmitsOwn || a.EmitsOwn for _, c := range a.Claims { diff --git a/modules/nats/cmd/nats-tools/catalogview_test.go b/modules/nats/cmd/nats-tools/catalogview_test.go index bffa977c4..d67a41fb8 100644 --- a/modules/nats/cmd/nats-tools/catalogview_test.go +++ b/modules/nats/cmd/nats-tools/catalogview_test.go @@ -1,9 +1,14 @@ package main import ( + "encoding/json" + "fmt" + "slices" "testing" catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + + "nats-tools/internal/keeper" ) func TestAsksOf(t *testing.T) { @@ -22,6 +27,42 @@ func TestAsksOf(t *testing.T) { if b.Accepted.Digest != a.Accepted.Digest { t.Errorf("the digest is of the bus-state asked alone: %s vs %s", b.Accepted.Digest, a.Accepted.Digest) } + // Design 47 H H-A-229, H-A-230: the old sections of the artifact registry and the forge, as their manifests declare + // them, are asked for under the bus names the grants part gives them, the names the live orphans of 2026-11-21 hold; + // a manifest not accepted asks none. + for _, row := range []struct{ module, sections, want string }{ + {"distribution", `{"state": ["transfers", {"name": "idle", "key-ttl": true}, "holds", "windows", "mirrors", "findings"], + "streams": [{"name": "distribution-events", "events": ["old-name-closed"], "max-age-days": 7, "max-mib": 16}], + "objects": [{"name": "incoming", "max-mib": 8192}]}`, + "[KV_distribution_transfers KV_distribution_idle KV_distribution_holds KV_distribution_windows KV_distribution_mirrors KV_distribution_findings OBJ_distribution_incoming DISTRIBUTION_EVENTS]"}, + {"gitea", `{"state": ["bound", {"name": "idle", "key-ttl": true}, "transfers"], "objects": [{"name": "incoming", "max-mib": 2048}], + "logs": [{"name": "calls", "max-mib": 8}]}`, + "[KV_gitea_bound KV_gitea_idle KV_gitea_transfers OBJ_gitea_incoming LOG_gitea_calls]"}, + } { + var m map[string]any + if err := json.Unmarshal([]byte(row.sections), &m); err != nil { + t.Fatal(err) + } + m["module"] = row.module + a, err := AsksOf(catalog.CatalogEntry{Module: row.module, Verdict: "accepted", Manifest: m}) + if err != nil { + t.Fatal(err) + } + var names []string + for _, p := range a.Accepted.Old { + names = append(names, p.Objects[0].Stream()) + } + if fmt.Sprint(names) != row.want { + t.Errorf("%s asks %v of its old sections, want %s", row.module, names, row.want) + } + i := slices.IndexFunc(a.Accepted.Old, func(p keeper.Plan) bool { return p.Local == "incoming" }) + if i < 0 || a.Accepted.Old[i].Objects[0].Settings.MaxBytes != int64(m["objects"].([]any)[0].(map[string]any)["max-mib"].(float64))*keeper.MiB { + t.Errorf("%s's incoming is not capped as declared: %+v", row.module, a.Accepted.Old) + } + if n, _ := AsksOf(catalog.CatalogEntry{Module: row.module, Verdict: "refused", Manifest: m}); len(n.Accepted.Old) != 0 { + t.Errorf("a refused manifest of %s asks %v", row.module, n.Accepted.Old) + } + } if _, err := AsksOf(catalog.CatalogEntry{}); err == nil { t.Error("an entry with no module was read") } diff --git a/modules/nats/cmd/nats-tools/consumer.go b/modules/nats/cmd/nats-tools/consumer.go index ccaa14555..bb37e3d42 100644 --- a/modules/nats/cmd/nats-tools/consumer.go +++ b/modules/nats/cmd/nats-tools/consumer.go @@ -11,6 +11,7 @@ import ( "encoding/json" "errors" "fmt" + "sort" "strings" "time" @@ -254,7 +255,7 @@ func decodeStored(b []byte) (*Stored, error) { return &Stored{Seq: doc.Message.Seq, Subject: doc.Message.Subject, Time: doc.Message.Time, Data: doc.Message.Data}, nil } -// readTools are the two reads that locate a lost event. +// readTools are the reads that locate a lost event, and the consumers' flow. func readTools(jsz func() ([]byte, error), open MsgOpen) []stdio.Tool { return []stdio.Tool{ {Name: "nats_consumer", @@ -270,6 +271,7 @@ func readTools(jsz func() ([]byte, error), open MsgOpen) []stdio.Tool { } return Consumer(doc, arg(a, "stream"), arg(a, "consumer")) }}, + flowTool(jsz, time.Sleep), {Name: "nats_stream_messages", Description: "The messages a stream keeps for one subject (a filter with * or > is allowed), newest first: sequence, subject, time and size of each, and the body only when asked for, no larger than 4 KiB, and only on the stream EVENTS (every kept event is there); on every other stream (kept events, asks, calls and replies, mail, dead letters, records, logs) only sequence, subject, time and size. Bounded by count (default 20, at most 200) and bytes (default 1 MiB); says when it stopped before the oldest the stream keeps. Read on the bus module's own credential. Refuses the streams of a module's kept state (KV_*, OBJ_*): their values are read through their owners' tools; this tool is for lost events.", Input: map[string]any{"stream": str("the stream, e.g. EVENTS"), "subject": str("a subject or filter, e.g. mesh.mod.mesh-delivery-indexer.event.view-changed"), @@ -313,3 +315,99 @@ func readTools(jsz func() ([]byte, error), open MsgOpen) []stdio.Tool { }}, } } + +// defaultRateWindow is how long nats_consumers measures each consumer's deliveries when the call names no rate-window +// (design 47 H2 §813 (5)). +const defaultRateWindow = 10 * time.Second + +// ConsumerFlow is one consumer's flow: how many messages a second it was delivered over the window, and when it was made. +type ConsumerFlow struct { + Stream string `json:"stream"` + Consumer string `json:"consumer"` + Created string `json:"created"` + DeliveredRate float64 `json:"delivered-rate"` + Delivered int64 `json:"delivered"` + Pending int64 `json:"pending"` + Unacknowledged int64 `json:"unacknowledged"` +} + +// ConsumerFlows is every consumer of every stream, its delivered-rate the deliveries between the two monitoring documents +// before and after, read window apart, a second; sorted by delivered-rate, the fastest first, or by created, the newest +// first (design 47 H2 §813 (5)). A consumer the second document does not hold is left out: it was removed meanwhile. +func ConsumerFlows(before, after []byte, window time.Duration, by string) (map[string]any, error) { + if by == "" { + by = "delivered-rate" + } + if by != "delivered-rate" && by != "created" { + return nil, fmt.Errorf("sort is delivered-rate or created, not %q", by) + } + var a, b jszDoc + if err := json.Unmarshal(before, &b); err != nil { + return nil, err + } + if err := json.Unmarshal(after, &a); err != nil { + return nil, err + } + was := map[string]int64{} + for _, acc := range b.Accounts { + for _, s := range acc.Streams { + for _, c := range s.Consumers { + was[s.Name+"\x00"+c.Name] = c.Delivered.Consumer + } + } + } + rows := []ConsumerFlow{} + for _, acc := range a.Accounts { + for _, s := range acc.Streams { + for _, c := range s.Consumers { + rate := 0.0 + if start, ok := was[s.Name+"\x00"+c.Name]; ok && window > 0 && c.Delivered.Consumer > start { + rate = float64(c.Delivered.Consumer-start) / window.Seconds() + } + rows = append(rows, ConsumerFlow{Stream: s.Name, Consumer: c.Name, Created: c.Created, DeliveredRate: rate, + Delivered: c.Delivered.Consumer, Pending: c.NumPending, Unacknowledged: c.NumAckPending}) + } + } + } + sort.SliceStable(rows, func(i, j int) bool { + if by == "created" { + return createdAt(rows[i].Created).After(createdAt(rows[j].Created)) + } + return rows[i].DeliveredRate > rows[j].DeliveredRate + }) + return map[string]any{"sort": by, "rate-window-seconds": window.Seconds(), "consumers": rows}, nil +} + +func createdAt(s string) time.Time { t, _ := time.Parse(time.RFC3339Nano, s); return t } + +// flowTool is nats_consumers: the monitoring document read twice, rate-window apart, within the one call; wait is how the +// window passes (time.Sleep live, a stand-in in a test). +func flowTool(jsz func() ([]byte, error), wait func(time.Duration)) stdio.Tool { + return stdio.Tool{Name: "nats_consumers", + Description: "Every consumer of every stream with its flow: delivered-rate (messages delivered a second, measured over rate-window within this one call), delivered, pending and unacknowledged, and when it was created; sorted by delivered-rate (the fastest first, the default) or by created (the newest first). The question behind a bus that is busy and no one knows with what.", + Input: map[string]any{"sort": str("delivered-rate (default) or created"), + "rate-window": num("seconds the deliveries are measured over, within this call (default 10)")}, + Run: func(a map[string]any) (any, error) { + window := defaultRateWindow + if v, ok := a["rate-window"].(float64); ok { + if v <= 0 { + return nil, errors.New("rate-window is a number of seconds above 0") + } + window = time.Duration(v * float64(time.Second)) + } + by := arg(a, "sort") + if by != "" && by != "delivered-rate" && by != "created" { + return nil, fmt.Errorf("sort is delivered-rate or created, not %q", by) + } + before, err := jsz() + if err != nil { + return nil, err + } + wait(window) + after, err := jsz() + if err != nil { + return nil, err + } + return ConsumerFlows(before, after, window, by) + }} +} diff --git a/modules/nats/cmd/nats-tools/consumer_test.go b/modules/nats/cmd/nats-tools/consumer_test.go index b8adf93d5..e0ca69ccf 100644 --- a/modules/nats/cmd/nats-tools/consumer_test.go +++ b/modules/nats/cmd/nats-tools/consumer_test.go @@ -47,6 +47,42 @@ func TestAConsumerIsReadWithItsConfigAndItsState(t *testing.T) { t.Fatalf("%v answered", c) } } + t.Run("nats_consumers measures the flow within the call and sorts it", consumersFlow) +} + +// consumersFlow: design 47 H2 §813 (5). Two consumers, the older delivered 40 messages over the 4 s window, the newer +// 4; the window passes through the stand-in wait, never a real sleep. +func consumersFlow(t *testing.T) { + doc := func(oldSeq, newSeq int) []byte { + return []byte(fmt.Sprintf(`{"account_details":[{"stream_detail":[{"name":"EVENTS","consumer_detail":[ + {"name":"old","created":"2026-11-01T10:00:00Z","delivered":{"consumer_seq":%d},"num_pending":7}, + {"name":"new","created":"2026-11-21T10:00:00Z","delivered":{"consumer_seq":%d}}]}]}]}`, oldSeq, newSeq)) + } + reads, waited := 0, time.Duration(0) + tool := flowTool(func() ([]byte, error) { + reads++ + if reads%2 == 1 { + return doc(100, 10), nil + } + return doc(140, 14), nil + }, func(d time.Duration) { waited += d }) + out, err := tool.Run(map[string]any{"rate-window": float64(4)}) + if err != nil { + t.Fatal(err) + } + rows := out.(map[string]any)["consumers"].([]ConsumerFlow) + if waited != 4*time.Second || len(rows) != 2 || rows[0].Consumer != "old" || rows[0].DeliveredRate != 10 || rows[1].DeliveredRate != 1 || rows[0].Pending != 7 { + t.Fatalf("waited %s: %+v", waited, rows) + } + out, _ = tool.Run(map[string]any{"sort": "created"}) + if rows := out.(map[string]any)["consumers"].([]ConsumerFlow); waited != 14*time.Second || rows[0].Consumer != "new" { + t.Fatalf("the default window or the sort by created: waited %s, %+v", waited, rows) + } + for _, bad := range []map[string]any{{"sort": "name"}, {"rate-window": float64(0)}} { + if _, err := tool.Run(bad); err == nil { + t.Fatalf("%v answered", bad) + } + } } func TestMessagesComeNewestFirstBoundedAndBodiesOnlyWhenAsked(t *testing.T) { @@ -82,9 +118,11 @@ func TestMessagesComeNewestFirstBoundedAndBodiesOnlyWhenAsked(t *testing.T) { if r := got["messages"].([]MessageRow)[0]; r.Body != "" || r.BodyOmitted == "" { t.Fatalf("%+v", r) } + t.Run("messages scan back across blocks and say an unanswered read", messagesScanBack) } -func TestMessagesScanBackAcrossBlocksAndSayAnUnansweredRead(t *testing.T) { +// messagesScanBack is run by TestMessagesComeNewestFirstBoundedAndBodiesOnlyWhenAsked (design 47 H2 §819: fewer tests). +func messagesScanBack(t *testing.T) { ctx := context.Background() got, _ := NewestMessages(ctx, func(_ context.Context, _ string, seq uint64, _ string) (*Stored, error) { if seq <= 3 { diff --git a/modules/nats/cmd/nats-tools/keep.go b/modules/nats/cmd/nats-tools/keep.go index 366aacda6..1a946c07a 100644 --- a/modules/nats/cmd/nats-tools/keep.go +++ b/modules/nats/cmd/nats-tools/keep.go @@ -219,6 +219,9 @@ func runKeeper(ctx context.Context, getenv func(string) string, logOut io.Writer return err }, Warrant: WarrantFrom(conn.Ask), Finding: writer, + Cancel: func(id string) error { + return conn.Accept("operator-channel", "cancel", map[string]string{"id": id}, stdio.EmitOptions{MessageID: "cancel." + id}) + }, Logf: logger.Printf, Raise: percent(getenv, "MESH_NATS_FULL_RAISE", 75), Clear: percent(getenv, "MESH_NATS_FULL_CLEAR", 70), // The settings snapshots-cap (20 GiB) and snapshot-keep-days (90) of the manifest, read from the file it declares diff --git a/modules/nats/cmd/nats-tools/keep_test.go b/modules/nats/cmd/nats-tools/keep_test.go index a5724d859..5b12da3d9 100644 --- a/modules/nats/cmd/nats-tools/keep_test.go +++ b/modules/nats/cmd/nats-tools/keep_test.go @@ -21,7 +21,7 @@ import ( // newest revision lists, each local name from the first of its watched branches in its registration's order whose entry // asks it, another branch asking it with other settings a drift naming that branch; a branch the registration does not // name after; a verdict not accepted asks nothing; the claims of every branch; a foundation part and its old sections' -// caps from the first branch. +// caps and entries from the first branch (design 47 H H-A-229). func TestTheCatalogHalfIsReadPerWatchedBranch(t *testing.T) { entryOf := func(verdict string, manifest map[string]any) catalog.CatalogEntry { manifest["module"] = "m" @@ -44,17 +44,17 @@ func TestTheCatalogHalfIsReadPerWatchedBranch(t *testing.T) { want string }{ {"one branch", []Branch{{Name: "main", Revision: 3, Entries: map[string]catalog.CatalogEntry{"m": main}}}, []string{"main"}, - "m 3 [drafts/key-value/state] [a] false 0;"}, + "m 3 [drafts/key-value/state] [a] false 0 0;"}, {"a feature branch asking a local name with other settings drifts, its new one planned", []Branch{{Name: "feature", Revision: 9, Entries: map[string]catalog.CatalogEntry{"m": feature}}, {Name: "main", Revision: 3, Entries: map[string]catalog.CatalogEntry{"m": main}}}, - []string{"main", "feature"}, "m 3 [drafts/key-value/state log/stream/log] [a b] false 0; drifted m drafts feature from main"}, + []string{"main", "feature"}, "m 3 [drafts/key-value/state log/stream/log] [a b] false 0 0; drifted m drafts feature from main"}, {"the registration's order decides", []Branch{{Name: "main", Revision: 3, Entries: map[string]catalog.CatalogEntry{"m": main}}, {Name: "feature", Revision: 9, Entries: map[string]catalog.CatalogEntry{"m": feature}}}, - []string{"feature"}, "m 9 [drafts/key-value/state log/stream/log] [b a] false 0; drifted m drafts main from feature"}, + []string{"feature"}, "m 9 [drafts/key-value/state log/stream/log] [b a] false 0 0; drifted m drafts main from feature"}, {"a verdict not accepted asks nothing", []Branch{{Name: "main", Revision: 3, Entries: map[string]catalog.CatalogEntry{"m": entryOf("refused", map[string]any{"bus-state": []any{state("")}})}}}, []string{"main"}, - "m 3 [] [] false 0;"}, + "m 3 [] [] false 0 0;"}, {"a foundation part, its old sections counted", []Branch{{Name: "main", Revision: 3, Entries: map[string]catalog.CatalogEntry{"m": entryOf("accepted", map[string]any{ "objects": []any{map[string]any{"name": "sent-objects", "max-mib": 256}}, "logs": []any{map[string]any{"name": "l", "max-mib": 4}}, "streams": []any{map[string]any{"name": "s"}}})}}}, []string{"main"}, - "m 3 [] [] true 1284;"}, + "m 3 [] [] true 1284 3;"}, } { t.Run(row.name, func(t *testing.T) { v, err := ViewOf(row.branches, func(string) []string { return row.order }) @@ -67,7 +67,7 @@ func TestTheCatalogHalfIsReadPerWatchedBranch(t *testing.T) { for _, e := range m.BusState { es = append(es, e.Name+"/"+e.Storage+"/"+e.Template) } - got += fmt.Sprintf("%s %d [%s] %v %v %d;", m.Module, m.Revision, strings.Join(es, " "), m.Claims, m.Foundation, m.OldBytes/keeper.MiB) + got += fmt.Sprintf("%s %d [%s] %v %v %d %d;", m.Module, m.Revision, strings.Join(es, " "), m.Claims, m.Foundation, m.OldBytes/keeper.MiB, len(m.Old)) } for _, d := range v.Drifts { got += fmt.Sprintf(" drifted %s %s %s from %s", d.Module, d.Local, d.Branch, d.From) diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index 2f7e0f14b..8f9ca6c45 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -316,7 +316,9 @@ func TestTheBusModuleRunsWhole(t *testing.T) { _ = Keep(kctx, deaf, func(context.Context, func(string, []byte) error) error { return errors.New("no consumer yet") }, nil, nil, t.Logf) close(done) }() - eventually(t, "the first view answered", func() bool { return !deaf.Status().FirstView.Answered.IsZero() }) + // A first view listing no module is none yet and never marked answered (A-367): the first fill pass is waited + // for instead, then taken as the first (design 47 H, H-A-268). + eventually(t, "the first fill pass", func() bool { return !deaf.Status().Pass.IsZero() }) first := deaf.Status().Pass eventually(t, "a fill pass while the consumer is bound again", func() bool { return deaf.Status().Pass.After(first) }) stopDeaf() @@ -397,8 +399,8 @@ func TestTheBusModuleRunsWhole(t *testing.T) { } put(keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused"}) eventually(t, "the drop with no ask refused", func() bool { return strings.Contains(get("r1").Error, "operator's warrant") }) - r := keeper.Request{ID: "r2", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused", At: time.Now()} - a, _ := askFor(r, time.Now()) + r := keeper.Request{ID: "r2", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused", At: time.Now(), AskExpires: time.Now().Add(keeper.AskLasts)} + a, _ := askFor(r) r.Ask = a.ID record := func(w *oc.Warrant) { raw, _ := json.Marshal(map[string]any{"asker": keeper.Module, "ask": a, "state": "open", "warrant": w}) @@ -415,7 +417,7 @@ func TestTheBusModuleRunsWhole(t *testing.T) { // The operator chooses: the router records the warrant and says decided; the keeper acts on decided, on its // durable consumer, with no timer between and no call of its pass by the test (seams F1). w := &oc.Warrant{Ask: a.ID, Asker: keeper.Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, - Option: "go", Label: "Remove", Level: occ.Destroy, At: occ.FormatTime(time.Now()), AskDigest: occ.Digest(a)} + Option: "go", Label: "Remove", Level: occ.Approve, At: occ.FormatTime(time.Now()), AskDigest: occ.Digest(a)} record(w) decided := time.Now() body, _ := json.Marshal(w) diff --git a/modules/nats/cmd/nats-tools/main.go b/modules/nats/cmd/nats-tools/main.go index 9b43093f5..fc35315a5 100644 --- a/modules/nats/cmd/nats-tools/main.go +++ b/modules/nats/cmd/nats-tools/main.go @@ -57,10 +57,10 @@ func tools(monitor Monitor, users func(context.Context) ([]byte, error), written return Server(varz, health) }}, {Name: "nats_connections", - Description: "Every client connected to the bus, named by the mesh user it is (a machine's host `node.`, a machine's runtime `.node-tools`, the controller, a person): address, uptime, round trip, traffic and pending bytes. Narrowed by a user or connection name, sorted by out_bytes (default), in_bytes, pending, msgs or subscriptions.", + Description: "Every client connected to the bus, named by the mesh user it is (a machine's host `node.`, a machine's runtime `.node-tools`, the controller, a person): address, uptime, round trip, traffic and pending bytes, and its five busiest subscriptions by messages (subject, queue group, messages). Narrowed by a user or connection name, sorted by out_bytes (default), in_bytes, pending, msgs or subscriptions.", Input: map[string]any{"user": str("part of a user or connection name, e.g. g14"), "sort": str("out_bytes, in_bytes, pending, msgs or subscriptions"), "limit": num("at most this many (default 50)")}, Run: func(a map[string]any) (any, error) { - connz, err := get("/connz?auth=1&limit=1024") + connz, err := get("/connz?auth=1&limit=1024&subs=detail") if err != nil { return nil, err } @@ -191,7 +191,7 @@ func allTools() []stdio.Tool { defer cancel() return monitor(ctx, heldJsz) } - out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState)...) + out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState, PlansInState, RecordedBySeat, bundleTwinCurrent)...) out = append(out, expiryTools(LiveBus(), SaidByTheRuntime, RecordedBySeat)...) out = append(out, brokerTools(HeldInState, StatusInState, jsz, StreamHistory(LiveBus()))...) out = append(out, keeperHealthTool(StatusInState, HeldInState, jsz)) diff --git a/modules/nats/cmd/nats-tools/manifest_test.go b/modules/nats/cmd/nats-tools/manifest_test.go index a6330a88a..4c0790563 100644 --- a/modules/nats/cmd/nats-tools/manifest_test.go +++ b/modules/nats/cmd/nats-tools/manifest_test.go @@ -346,6 +346,11 @@ func TestTheKeepersSnapshotSettingsAreAFileItsManifestDeclares(t *testing.T) { if m.Config["snapshots-cap"].Default != 21474836480 || m.Config["snapshot-keep-days"].Default != 90 { t.Errorf("config %v: snapshots-cap 20 GiB and snapshot-keep-days 90 are the defaults", m.Config) } + // Design 47 H2, H-A-472 third addendum (2): twin-current-hours, the bound of a current twin, defaults to 24, the field + // name the grants part's manifest names too. + if m.Config["twin-current-hours"].Default != DefaultTwinCurrentHours || DefaultTwinCurrentHours != 24 { + t.Errorf("config %v: twin-current-hours defaults to 24", m.Config) + } found := false for _, r := range m.Resources { if r.ID == "keeper-settings" { diff --git a/modules/nats/cmd/nats-tools/removal.go b/modules/nats/cmd/nats-tools/removal.go index d6a9e0ae5..df6c982dc 100644 --- a/modules/nats/cmd/nats-tools/removal.go +++ b/modules/nats/cmd/nats-tools/removal.go @@ -13,6 +13,7 @@ package main import ( "context" + "encoding/json" "errors" "fmt" "regexp" @@ -20,9 +21,12 @@ import ( "strings" "time" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" stdio "git.novox.be/novox/mesh-sdk/go" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" + + "nats-tools/internal/keeper" ) // Bus opens JetStream on the bus as the module's credential for one call; close ends the connection. @@ -338,7 +342,39 @@ func RemoveStream(ctx context.Context, bus Bus, said Said, a map[string]any) (an // recreate, so a stream, a bucket or a consumer of a stream the keeper made (its state asked, read through newForm) is // refused, naming nats_drop, before the bus is reached; the old sections' entries are removed as before. A newForm // that cannot be read refuses too: what cannot be told apart is not removed. -func removalTools(bus Bus, said Said, newForm heldEntries) []stdio.Tool { +// +// **A consumer is judged by its name, not by its stream** (design 47 H, H-A-126, H-A-127): the mesh names a module's +// durable _, so a durable of that form for a module of an accepted manifest (the keeper's accepted set: +// every module it heard as accepted, its state plans, one key per module of a watched branch's newest revision whether +// it asks for kept data or not, design 47 G §538) is refused, on any stream; every other durable is an orphan and goes, `why` its warrant, at once, and its removal is +// recorded as a hand act through mesh-hand-acts, as nats_bucket_expiry's change is. +func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration) []stdio.Tool { + removeConsumer := func(a map[string]any) (any, error) { + within := DefaultTwinCurrentHours * time.Hour + if twinWithin != nil { + within = twinWithin() + } + twin, err := refuseAcceptedDurable(context.Background(), bus, accepted, arg(a, "stream"), arg(a, "consumer"), time.Now(), within) + if err != nil { + return nil, err + } + out, err := RemoveConsumer(context.Background(), bus, said, a) + if err != nil { + return nil, err + } + r := out.(ConsumerRemoved) + what := fmt.Sprintf("removed the consumer %s of the stream %s", r.Consumer, r.Stream) + if twin != "" { + what += fmt.Sprintf(", an orphan: its module's twin %s on that stream is current (design 47 H2, H-A-472)", twin) + } + if record == nil { + return nil, fmt.Errorf("%s WAS done (%s) but the hand-act log cannot be reached here", what, r.Why) + } + if err := record(meshhandactsclient.Request{What: what, Why: r.Why, Cause: "consumer-remove"}); err != nil { + return nil, fmt.Errorf("%s WAS done (%s) but the hand act could not be recorded: %w", what, r.Why, err) + } + return r, nil + } run := func(f func(context.Context, Bus, Said, map[string]any) (any, error)) func(map[string]any) (any, error) { return func(a map[string]any) (any, error) { stream := arg(a, "stream") @@ -353,9 +389,9 @@ func removalTools(bus Bus, said Said, newForm heldEntries) []stdio.Tool { } return []stdio.Tool{ {Name: "nats_consumer_remove", - Description: "Removes (deletes) one named JetStream consumer of one stream, e.g. a consumer the controller left, such as `controller` of DEAD_LETTER_NOTICES or `controller-merges` of EVENTS (novox/hq ADR 0590 §6, recorded as a hand act under issue 1126). Needs `why`, kept in the audit trail; refuses an unknown stream or consumer; reads the consumer first and answers what it was (filters, pending, unacknowledged); the stream and its other consumers are not touched. The bus refuses any consumer the module's credential is not granted.", + Description: "Removes (deletes) one named JetStream consumer of one stream, e.g. a consumer the controller left, such as `controller` of DEAD_LETTER_NOTICES or `controller-merges` of EVENTS (novox/hq ADR 0590 §6), or an orphan on a module's kept-data stream. Refuses a durable named _ or beginning __ for a module of an accepted manifest, on any stream, unless it is an orphan: no pulls waiting on it while its twin (_ for __tools, and back) on the same stream is current, with pulls waiting and a delivery within the setting twin-current-hours (24 by default), both read at the call, and the hand act names that twin (design 47 H2, H-A-472); any other durable goes. Needs `why`, its warrant, kept in the audit trail and recorded as a hand act through mesh-hand-acts (design 47 H, H-A-127); refuses an unknown stream or consumer; reads the consumer first and answers what it was (filters, pending, unacknowledged); the stream and its other consumers are not touched. The bus refuses any consumer the module's credential is not granted.", Input: map[string]any{"stream": str("the stream, e.g. DEAD_LETTER_NOTICES"), "consumer": str("the consumer's name, e.g. controller"), "why": str("why it is removed, for the audit trail (required)")}, - Run: run(RemoveConsumer)}, + Run: removeConsumer}, {Name: "nats_stream_remove", Description: "Removes (deletes) one named JetStream stream whole, e.g. a stream the controller left: CONTROL, ASSIGNMENTS, one of its buckets as KV_ or a node's declaration files as OBJ_declaration-files- (novox/hq ADR 0590 §6; a bucket's whole removal is this tool's, never nats_bucket_remove's). Needs `why`, kept in the audit trail; reads the stream first and answers its messages, bytes and consumers; refuses a stream that still has a consumer; a stream already gone is answered as such and is no error, so asking again is safe. `dry_run` only reads. The bus refuses any stream the module's credential is not granted.", Input: map[string]any{"stream": str("the stream, e.g. ASSIGNMENTS"), "why": str("why it is removed, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "read the stream, remove nothing"}}, @@ -373,6 +409,115 @@ func removalTools(bus Bus, said Said, newForm heldEntries) []stdio.Tool { } } +// refuseAcceptedDurable refuses a durable named _, or beginning __, for a module of the +// keeper's accepted set, on any node (design 47 H, H-A-127, H-A-128): every module it heard as accepted, read from its +// state plans (design 47 G §538), never from its state asked, which holds only a module that asks for kept data (a +// module keeping none would lose its live durables: H-A-128's silent failure, P3). A set that cannot be read refuses +// too: what cannot be told apart is not removed. +// +// **An orphaned durable goes** (design 47 H2, H-A-472 (1) and its third addendum): a module's durable that is itself an +// orphan (no pulls waiting on it) while its live twin on the same stream exists and is current is not refused, and the +// twin's name is answered, for the hand act to name it; both are read from the bus at the call. The twins are the +// module's program's durable _ and its tool runner's __tools (design 47 G, A-340): a module +// that moved into the tool runner left the first, one that runs its own program again left the second. A module's +// only durable, any other suffix, a durable with pulls waiting, and a durable or twin that cannot be read or a twin +// that is not current, stay refused (H-A-127/128). within is the bound of "current", the setting twin-current-hours. +func refuseAcceptedDurable(ctx context.Context, bus Bus, accepted acceptedModules, stream, consumer string, now time.Time, within time.Duration) (string, error) { + if accepted == nil { + return "", nil + } + node, module, ok := strings.Cut(consumer, "_") + if !ok || node == "" || module == "" { + return "", nil + } + held, err := accepted() + if err != nil { + return "", fmt.Errorf("whether %s is the durable of a module of an accepted manifest cannot be read (%v), so nothing was removed", consumer, err) + } + for m := range held { + if module != m && !strings.HasPrefix(module, m+"_") { + continue + } + refused := fmt.Errorf("%s is %s's durable on %s, a module of an accepted manifest: it is not removed; nothing was removed", consumer, m, node) + twin := twinOf(node, m, module) + if twin == "" || bus == nil || !name.MatchString(stream) { + return "", refused + } + js, closeBus, err := bus(ctx) + if err != nil { + return "", fmt.Errorf("%v (it and its twin %s on %s cannot be read: %v)", refused, twin, stream, err) + } + defer closeBus() + sctx, cancel := step(ctx) + self, err := readConsumer(sctx, js, stream, consumer) + cancel() + if err != nil { + return "", fmt.Errorf("%v (it cannot be read on %s: %v)", refused, stream, err) + } + if self.NumWaiting > 0 { + return "", fmt.Errorf("%v (it is no orphan: %d pulls waiting on it)", refused, self.NumWaiting) + } + sctx, cancel = step(ctx) + info, err := readConsumer(sctx, js, stream, twin) + cancel() + if err != nil { + return "", fmt.Errorf("%v (its twin %s on %s cannot be read: %v)", refused, twin, stream, err) + } + if !current(info, now, within) { + return "", fmt.Errorf("%v (its twin %s on %s is not current: %d pulls waiting, last delivery %s, the bound %s)", refused, twin, stream, info.NumWaiting, lastDelivery(info), within) + } + return twin, nil + } + return "", nil +} + +// twinOf names the twin of a module's durable: __tools for _, and back; "" for any other. +func twinOf(node, module, durable string) string { + switch durable { + case module: + return node + "_" + module + "_tools" + case module + "_tools": + return node + "_" + module + } + return "" +} + +// DefaultTwinCurrentHours is the setting twin-current-hours's default (design 47 H2, H-A-472 third addendum): how recent a +// twin's last delivery is for it to be current, within the day; the grants part reads the same field name of its own +// manifest for its orphaned durables. +const DefaultTwinCurrentHours = 24 + +// twinCurrentWithin is the setting twin-current-hours as the configuration answers it, in hours, as a bound: its default +// when the configuration gives none, or a value that is not a positive whole number. +func twinCurrentWithin(raw json.RawMessage, err error) time.Duration { + var n int + if err != nil || json.Unmarshal(raw, &n) != nil || n < 1 { + n = DefaultTwinCurrentHours + } + return time.Duration(n) * time.Hour +} + +// bundleTwinCurrent is the setting twin-current-hours as this bundle's configuration holds it, read at each call +// (never while the tools are listed: see bundleKeepDays). +func bundleTwinCurrent() time.Duration { + return twinCurrentWithin(stdio.Config("twin-current-hours")) +} + +// current says whether a durable is live: pulls waiting on it and a delivery within the bound (H-A-472 (1)). +func current(info *jetstream.ConsumerInfo, now time.Time, within time.Duration) bool { + return info != nil && info.NumWaiting > 0 && info.Delivered.Last != nil && now.Sub(*info.Delivered.Last) < within +} + +func lastDelivery(info *jetstream.ConsumerInfo) string { + if info == nil || info.Delivered.Last == nil { + return "never" + } + return info.Delivered.Last.UTC().Format(time.RFC3339) +} + +// acceptedModules reads the keeper's accepted set: every module it heard as accepted, by name (its state plans, §538). +type acceptedModules func() (map[string]keeper.Planned, error) + // refuseNewForm refuses a stream the keeper made for a module's bus state, naming the tool that removes it. func refuseNewForm(newForm heldEntries, stream string) error { if newForm == nil || stream == "" { diff --git a/modules/nats/cmd/nats-tools/removal_test.go b/modules/nats/cmd/nats-tools/removal_test.go index 680fee08c..257431722 100644 --- a/modules/nats/cmd/nats-tools/removal_test.go +++ b/modules/nats/cmd/nats-tools/removal_test.go @@ -5,6 +5,7 @@ package main import ( "context" "fmt" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "os" "path/filepath" "sort" @@ -17,6 +18,8 @@ import ( "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" + + "nats-tools/internal/keeper" ) // The tools that change the bus, against a server shaped like the mesh's, on the credential the module's @@ -191,6 +194,14 @@ accounts { MESH { jetstream: enabled, users: [ } // Issue 1126: the controller's leftovers were push consumers too, which js.Consumer refuses ("not a pull consumer"): // a pull and a push consumer are read, removed and confirmed alike. + // Through the tool, `why` its warrant: each removal is recorded as a hand act (design 47 H, H-A-127). + var handActs []meshhandactsclient.Request + var removeConsumer func(map[string]any) (any, error) + for _, tl := range removalTools(bus, say, nil, nil, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + if tl.Name == "nats_consumer_remove" { + removeConsumer = tl.Run + } + } for _, row := range []struct{ name, kind, deliver string }{ {"controller-merges", "pull", ""}, {"controller", "push", "deliver.controller"}, @@ -200,7 +211,7 @@ accounts { MESH { jetstream: enabled, users: [ t.Fatal(err) } } - got, err := RemoveConsumer(ctx, bus, say, map[string]any{"stream": "EVENTS", "consumer": row.name, "why": "the controller ended"}) + got, err := removeConsumer(map[string]any{"stream": "EVENTS", "consumer": row.name, "why": "the controller ended"}) if err != nil { t.Fatalf("the controller's %s consumer %s of EVENTS: %v", row.kind, row.name, err) } @@ -214,6 +225,88 @@ accounts { MESH { jetstream: enabled, users: [ if _, err := ajs.Consumer(ctx, "EVENTS", "mesh-grants"); err != nil { t.Fatalf("the other consumer of EVENTS went: %v", err) } + if len(handActs) != 2 || handActs[0].Why != "the controller ended" || !strings.Contains(handActs[1].What, "controller of the stream EVENTS") { + t.Fatalf("the hand acts: %+v", handActs) + } + // Design 47 H2, H-A-472 (1): an accepted module's durable goes when its twin on the same stream is current (pulls + // waiting, a delivery within the day), the hand act naming the twin; its only durable, and one whose twin is not + // current, stay refused. On the admin's credential: the grant of the old sections names no module's durable. + adminBus := func(context.Context) (jetstream.JetStream, func(), error) { + nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "admin")) + if err != nil { + return nil, nil, err + } + js, err := jetstream.New(nc) + return js, nc.Close, err + } + accepted := func() (map[string]keeper.Planned, error) { + return map[string]keeper.Planned{"m": {Module: "m"}, "q": {Module: "q"}, "solo": {Module: "solo"}, "both": {Module: "both"}}, nil + } + for _, d := range []string{"novox_m", "novox_m_tools", "ace_q", "ace_q_tools", "ace_solo", "g14_both", "g14_both_tools"} { + if _, err := ajs.CreateConsumer(ctx, "EVENTS", jetstream.ConsumerConfig{Durable: d, AckPolicy: jetstream.AckExplicitPolicy}); err != nil { + t.Fatal(err) + } + } + if _, err := ajs.Publish(ctx, "mesh.events.one", []byte("{}")); err != nil { + t.Fatal(err) + } + for _, d := range []string{"novox_m_tools", "ace_q", "g14_both", "g14_both_tools"} { + c, _ := ajs.Consumer(ctx, "EVENTS", d) + if _, err := c.Next(jetstream.FetchMaxWait(2 * time.Second)); err != nil { + t.Fatalf("a delivery to %s: %v", d, err) + } + } + // novox_m_tools has a pull waiting (a fetch held open on the admin's connection); ace_q has none; both twins of + // g14_both have one each (the third addendum: a durable with pulls waiting is no orphan, its twin current or not). + for _, d := range []string{"novox_m_tools", "g14_both", "g14_both_tools"} { + live, _ := ajs.Consumer(ctx, "EVENTS", d) + held, err := live.Consume(func(jetstream.Msg) {}, jetstream.PullExpiry(time.Minute)) + if err != nil { + t.Fatal(err) + } + defer held.Stop() + for i := 0; ; i++ { + ci, err := live.Info(ctx) + if err != nil { + t.Fatal(err) + } + if ci.NumWaiting > 0 { + break + } + if i == 1000 { + t.Fatalf("the held fetch of %s never shows as a pull waiting", d) + } + } + } + handActs = nil + for _, tl := range removalTools(adminBus, say, nil, accepted, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + if tl.Name == "nats_consumer_remove" { + removeConsumer = tl.Run + } + } + for _, row := range []struct{ consumer, refused string }{ + {"novox_m_tools", "it is no orphan: 1 pulls waiting on it"}, + {"ace_q_tools", "its twin ace_q on EVENTS is not current"}, + {"ace_solo", "a module of an accepted manifest"}, + {"g14_both", "it is no orphan: 1 pulls waiting on it"}, + {"g14_both_tools", "it is no orphan: 1 pulls waiting on it"}, + {"novox_m", ""}, + } { + _, err := removeConsumer(map[string]any{"stream": "EVENTS", "consumer": row.consumer, "why": "an orphaned durable"}) + _, still := ajs.Consumer(ctx, "EVENTS", row.consumer) + if row.refused == "" { + if err != nil || still == nil { + t.Fatalf("the orphan %s: %v, still there: %v", row.consumer, err, still == nil) + } + continue + } + if err == nil || !strings.Contains(err.Error(), row.refused) || still != nil { + t.Fatalf("%s: %v (still there: %v), want a refusal saying %q", row.consumer, err, still == nil, row.refused) + } + } + if len(handActs) != 1 || !strings.Contains(handActs[0].What, "novox_m of the stream EVENTS") || !strings.Contains(handActs[0].What, "twin novox_m_tools") { + t.Fatalf("the orphan's hand act: %+v", handActs) + } if r, err := RemoveStream(ctx, bus, say, map[string]any{"stream": "KV_mesh-controller_rollouts", "why": "the controller ended"}); err != nil || !r.(StreamRemoved).Removed || r.(StreamRemoved).Messages != 1 { t.Fatalf("the controller's bucket: %+v %v", r, err) } @@ -260,7 +353,7 @@ accounts { MESH { jetstream: enabled, users: [ if k := keys(other); k != "g14.1" { t.Fatalf("another bucket changed: %s", k) } - if strings.Join(said, ",") != "consumer-removed,stream-removed,consumer-removed,consumer-removed,stream-removed,bucket-keys-removed" { + if strings.Join(said, ",") != "consumer-removed,stream-removed,consumer-removed,consumer-removed,consumer-removed,stream-removed,bucket-keys-removed" { t.Fatalf("the audit events said: %v", said) } } diff --git a/modules/nats/cmd/nats-tools/requests.go b/modules/nats/cmd/nats-tools/requests.go index 2602ab542..b0902d809 100644 --- a/modules/nats/cmd/nats-tools/requests.go +++ b/modules/nats/cmd/nats-tools/requests.go @@ -40,6 +40,9 @@ type requestStore struct { Ended func(id string, within time.Duration) *keeper.Request // Record records a hand act through the seat mesh-hand-acts. Record Recorded + // Standing reads the router's record of one of this module's asks, by its id, or nil while it holds none (design 47 + // H-A-237, H-A-239). + Standing func(askID string) (*stdio.StateEntry, error) } // RequestsInState is the store through the runtime that launched this bundle: one watch of the state requests for the @@ -80,10 +83,11 @@ func RequestsInState() requestStore { } return out, nil }, - Ask: func(a oc.Ask) error { return stdio.SeatPublish(oc.AcceptSubjectAsk(keeper.Module), a, a.ID) }, - Now: func() time.Time { return time.Now().UTC() }, - Ended: ends.wait, - Record: RecordedBySeat, + Ask: func(a oc.Ask) error { return stdio.SeatPublish(oc.AcceptSubjectAsk(keeper.Module), a, a.ID) }, + Now: func() time.Time { return time.Now().UTC() }, + Ended: ends.wait, + Record: RecordedBySeat, + Standing: func(id string) (*stdio.StateEntry, error) { return stdio.SeatRecord("", id) }, } } @@ -146,36 +150,130 @@ func requestID(now time.Time) string { return now.Format("20060102t150405") + "-" + hex.EncodeToString(b[:]) } -// askFor is the operator's ask for a recreate or a drop of one entry, its approve option binding exactly that act. -func askFor(r keeper.Request, now time.Time) (oc.Ask, error) { +// The bounds of the caller's expiry of a recreate's or a drop's ask, in minutes (design 47 H-A-237, H-A-239): the +// channel's own, the longest under the day the state requests keeps a key. +const ( + askLeastMinutes = 5 + askMostMinutes = 1430 +) + +// askExpiry is the caller's expiry of the ask, expires_minutes, or the default AskLasts: a value outside its bounds is +// refused, naming them, never clamped (design 47 H-A-239). +func askExpiry(a map[string]any) (time.Duration, error) { + v, given := a["expires_minutes"] + if !given || v == nil { + return keeper.AskLasts, nil + } + m, ok := v.(float64) + if !ok || m < askLeastMinutes || m > askMostMinutes { + return 0, fmt.Errorf("expires_minutes is %d to %d minutes, and %v is not: nothing is asked", askLeastMinutes, askMostMinutes, v) + } + return time.Duration(m * float64(time.Minute)), nil +} + +// askFor is the operator's ask for a recreate or a drop of one entry, its approve option binding exactly that act: at +// the approve level until a channel carries a destroy answer, ending at the request's AskExpires, the caller's (design +// 47 H-A-237); the bend ends with the research effort that designs the channel carrying the destroy proof (design 47 H2 +// §813 (11)). +func askFor(r keeper.Request) (oc.Ask, error) { binds, err := occ.ActDigest(r.Act()) if err != nil { return oc.Ask{}, err } what := map[string]string{keeper.VerbDrop: "remove", keeper.VerbRecreate: "rebuild"}[r.Verb] name := keeper.BusName(r.Module, r.Local) - return oc.Ask{ID: "bus-" + r.ID, Who: occ.Operator, Expires: occ.FormatTime(now.Add(keeper.AskLasts)), + return oc.Ask{ID: "bus-" + r.ID, Who: occ.Operator, Expires: occ.FormatTime(r.AskExpires), OnExpiry: "nothing is removed and the entry stays as it is", About: keeper.ConditionKey(map[string]string{keeper.VerbDrop: "orphaned", keeper.VerbRecreate: "drifted"}[r.Verb], r.Module, r.Local), Headline: fmt.Sprintf("%s's kept data %s: %s it?", r.Module, r.Local, what), Explanation: fmt.Sprintf("%s asks to %s %s on the bus, %s. A snapshot of it is taken first; its data is lost from the bus.", r.Caller, what, name, r.Why), Options: []oc.Option{ - {ID: "go", Label: strings.ToUpper(what[:1]) + what[1:], Does: fmt.Sprintf("%s %s after a snapshot", what, name), Level: occ.Destroy, Binds: binds}, + {ID: "go", Label: strings.ToUpper(what[:1]) + what[1:], Does: fmt.Sprintf("%s %s after a snapshot", what, name), Level: occ.Approve, Binds: binds}, {ID: "keep", Label: "Keep it", Does: "nothing is removed", Level: occ.Acknowledge}, }}, nil } +// notTakenIn is what the tool says of an ask the router holds no record of yet (design 47 H-A-239). +const notTakenIn = "raised, not yet taken in by the router: read the request for its standing" + +// standingOf is the router's standing of an ask, in words, from one read of its record (design 47 H-A-237, H-A-239): +// offered (where), held (why), refused (why), or how it ended; "the operator is asked" is said only for an offered ask. +func standingOf(rs requestStore, askID string) string { + if rs.Standing == nil { + return notTakenIn + } + e, err := rs.Standing(askID) + if err != nil { + return "raised; the router's record of it cannot be read now (" + err.Error() + "): read the request for its standing" + } + if e == nil || len(e.Value) == 0 || string(e.Value) == "null" { + return notTakenIn + } + var rec struct { + State string `json:"state"` + Held string `json:"held"` + Tickets map[string]struct { + Kind string `json:"kind"` + } `json:"tickets"` + Warrant *oc.Warrant `json:"warrant"` + } + if err := json.Unmarshal(e.Value, &rec); err != nil { + return "raised; the router's record of it is not readable (" + err.Error() + "): read the request for its standing" + } + switch rec.State { + case "open": + var kinds []string + for _, t := range rec.Tickets { + if !slices.Contains(kinds, t.Kind) { + kinds = append(kinds, t.Kind) + } + } + sort.Strings(kinds) + where := "offered on " + strings.Join(kinds, ", ") + if len(kinds) == 0 { + where = "offered, channel not yet named" + } + return where + ": the operator is asked; the keeper acts once they approve, after a snapshot" + case "held": + return "held by the router, not shown to the operator: " + rec.Held + case string(occ.OutcomeRefused): + words := "" + if rec.Warrant != nil { + words = rec.Warrant.Words + } + return "refused by the router, so nothing will be removed: " + words + } + words := "" + if rec.Warrant != nil { + words = ": " + occ.Says(*rec.Warrant) + } + return "ended " + rec.State + words +} + func requestTools(rs requestStore) []stdio.Tool { entry := map[string]any{"module": str("the module, e.g. mesh-knowledge"), "local": str("its local name, e.g. records"), "why": str("why, in plain words: kept with the act"), "request": str("a request this tool made before: its end is read, nothing new is asked")} + warranted := map[string]any{"expires_minutes": num(fmt.Sprintf("how long the operator's ask waits for an answer, %d to %d minutes (default %d)", + askLeastMinutes, askMostMinutes, int(keeper.AskLasts/time.Minute)))} + for k, v := range entry { + warranted[k] = v + } tool := func(verb, description string) stdio.Tool { - return stdio.Tool{Name: "nats_" + verb, Description: description, Input: entry, Run: func(a map[string]any) (any, error) { + input := entry + if verb == keeper.VerbRecreate || verb == keeper.VerbDrop { + input = warranted + } + return stdio.Tool{Name: "nats_" + verb, Description: description, Input: input, Run: func(a map[string]any) (any, error) { if id := arg(a, "request"); id != "" { r, err := rs.Get(id) if err != nil || r == nil { return nil, fmt.Errorf("no request %s is held (%v)", id, err) } + // The router's standing of its ask beside the keeper's (design 47 H-A-239). + if r.Ask != "" { + return map[string]any{"request": r, "router": standingOf(rs, r.Ask)}, nil + } return r, nil } r := keeper.Request{Verb: verb, Module: arg(a, "module"), Local: arg(a, "local"), Why: strings.TrimSpace(arg(a, "why")), @@ -186,7 +284,12 @@ func requestTools(rs requestStore) []stdio.Tool { } r.ID = requestID(r.At) if verb == keeper.VerbRecreate || verb == keeper.VerbDrop { - ask, err := askFor(r, r.At) + lasts, err := askExpiry(a) + if err != nil { + return nil, err + } + r.AskExpires = r.At.Add(lasts) + ask, err := askFor(r) if err != nil { return nil, err } @@ -199,7 +302,8 @@ func requestTools(rs requestStore) []stdio.Tool { if err := rs.Put(r.ID, r); err != nil { return nil, fmt.Errorf("the request cannot be handed to the keeper, so nothing will be removed whatever the operator answers: %w", err) } - return map[string]any{"request": r.ID, "ask": ask.ID, "state": "the operator is asked; the keeper acts once they approve, after a snapshot", + // One read of the router's record right after the publish, no timer (design 47 H-A-237, H-A-239). + return map[string]any{"request": r.ID, "ask": ask.ID, "state": standingOf(rs, ask.ID), "read": fmt.Sprintf("nats_%s with request %s", verb, r.ID)}, nil } if err := rs.Put(r.ID, r); err != nil { diff --git a/modules/nats/cmd/nats-tools/requests_test.go b/modules/nats/cmd/nats-tools/requests_test.go index 474f06fbb..b7c380fbb 100644 --- a/modules/nats/cmd/nats-tools/requests_test.go +++ b/modules/nats/cmd/nats-tools/requests_test.go @@ -2,7 +2,6 @@ package main import ( "errors" - "runtime" "strings" "testing" "time" @@ -52,6 +51,10 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) { Ask: func(a oc.Ask) error { raised = append(raised, a); return nil }, Now: func() time.Time { return time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) }, Record: func(q meshhandactsclient.Request) error { acts = append(acts, q); return nil }, + // Design 47 H-A-237: the router held the ask (no channel carries its level), as it held every one live. + Standing: func(id string) (*stdio.StateEntry, error) { + return &stdio.StateEntry{Key: keeper.Module + "." + id, Value: []byte(`{"asker":"nats","state":"held","held":"telegram: Destroy needs a code"}`)}, nil + }, } tools := map[string]stdio.Tool{} for _, tl := range requestTools(rs) { @@ -74,14 +77,21 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) { t.Fatalf("raised %+v, held %+v: the ask raised, the request waiting for it", raised, r) } binds, _ := occ.ActDigest(occ.Act{"verb": "drop", "module": "m", "local": "old"}) - if o, _ := occ.OptionOf(raised[0], "go"); o.Level != occ.Destroy || o.Binds != binds || !strings.Contains(raised[0].Explanation, "snapshot") { - t.Errorf("the ask is %+v: its option destroys exactly this drop, after a snapshot", raised[0]) + // Design 47 H-A-237: the ask is at the approve level, naming the entry, the removal and the snapshot, for the default + // sixty minutes; an ask the router held is said held, with its why, never "the operator is asked". + if o, _ := occ.OptionOf(raised[0], "go"); o.Level != occ.Approve || o.Binds != binds || !strings.Contains(raised[0].Explanation, "snapshot") || + !strings.Contains(raised[0].Explanation, "remove m_old") || raised[0].Expires != occ.FormatTime(rs.Now().Add(time.Hour)) || !r.AskExpires.Equal(rs.Now().Add(time.Hour)) { + t.Errorf("the ask is %+v: its option approves exactly this drop, after a snapshot, for sixty minutes", raised[0]) + } + if st := answer["state"].(string); !strings.Contains(st, "held by the router") || !strings.Contains(st, "Destroy needs a code") || strings.Contains(st, "operator is asked") { + t.Errorf("the tool answered %q for an ask the router held", st) } if _, err := tools["nats_drop"].Run(map[string]any{"module": "m", "local": "old"}); err == nil || !strings.Contains(err.Error(), "says why") { t.Errorf("a drop without why: %v", err) } - if got, _ := tools["nats_drop"].Run(map[string]any{"request": r.ID}); got.(*keeper.Request).ID != r.ID { - t.Errorf("reading the request back answered %+v", got) + if got, _ := tools["nats_drop"].Run(map[string]any{"request": r.ID}); got.(map[string]any)["request"].(*keeper.Request).ID != r.ID || + !strings.Contains(got.(map[string]any)["router"].(string), "held by the router") { + t.Errorf("reading the request back answered %+v: the request, and the router's standing of its ask beside it", got) } // Review round 1 (tools F3): nats_requests reads what waits, what ended and each warrant spent, and drops a waiting // request by hand, recorded; an ended one is not dropped. @@ -122,20 +132,14 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) { t.Errorf("an ask not raised: %v, %d requests held (was %d)", err, len(held), before) } // A request's end is heard on the one watch of the state, handed to the call that waits for it. - var handle func(string, []byte) + // The watch hands its handler over a channel, never a variable both goroutines touch (the race on main, H-A-356); the + // call registered its wait before it took the watch, so the handler's arrival means the call waits. + handles := make(chan func(string, []byte), 1) watches := 0 - e := newEnds(func(h func(string, []byte)) error { watches++; handle = h; return nil }) + e := newEnds(func(h func(string, []byte)) error { watches++; handles <- h; return nil }) got := make(chan *keeper.Request, 1) go func() { got <- e.wait("r1", time.Minute) }() - for { - e.mu.Lock() - ready := len(e.waiting["r1"]) == 1 && handle != nil - e.mu.Unlock() - if ready { - break - } - runtime.Gosched() - } + handle := <-handles handle("r1", []byte(`{"id":"r1"}`)) handle("r1", []byte(`{"id":"r1","done":"2026-11-04T12:00:01Z","outcome":"created"}`)) if r := <-got; r == nil || r.Outcome != "created" || watches != 1 { @@ -146,20 +150,53 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) { } } -// The ask for a recreate or a drop lasts what its highest option level allows (design 47 G §570), so the asker client -// takes it: an expiry at the bound passes occ.Check, and the fixed 12 hours it was is refused. -func TestTheAskLastsWhatItsLevelAllows(t *testing.T) { +// The ask for a recreate or a drop is at the approve level, for the caller's expires_minutes, 5 to 1430, a value outside +// refused naming its bounds (design 47 H-A-237, H-A-239); the tool's answer is the router's standing as one read finds +// it, "the operator is asked" only for an offered ask. +func TestTheAskLastsTheCallersExpiryAndTheToolSaysTheRoutersStanding(t *testing.T) { now := time.Now() - r := keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Why: "unused", Caller: "person.jo"} - a, err := askFor(r, now) + r := keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Why: "unused", Caller: "person.jo", AskExpires: now.Add(1430 * time.Minute)} + a, err := askFor(r) if err != nil { t.Fatal(err) } - if err := occ.Check(a, now); err != nil { - t.Errorf("the ask is refused by the asker client: %v", err) + if err := occ.Check(a, now); err != nil || occ.Highest(a) != occ.Approve { + t.Errorf("the ask at %s is refused by the asker client (%v), or not at the approve level", occ.Highest(a), err) } - a.Expires = occ.FormatTime(now.Add(12 * time.Hour)) - if err := occ.Check(a, now); err == nil || !strings.Contains(err.Error(), "at most") { - t.Errorf("12 hours is held to the level's bound: %v", err) + for _, c := range []struct { + minutes any + want time.Duration + refused bool + }{{nil, time.Hour, false}, {5.0, 5 * time.Minute, false}, {1430.0, 1430 * time.Minute, false}, {4.0, 0, true}, {1431.0, 0, true}, {"60", 0, true}} { + a := map[string]any{} + if c.minutes != nil { + a["expires_minutes"] = c.minutes + } + got, err := askExpiry(a) + if c.refused != (err != nil) || got != c.want || (c.refused && !strings.Contains(err.Error(), "5 to 1430")) { + t.Errorf("expires_minutes %v: %s, %v", c.minutes, got, err) + } + } + for _, c := range []struct { + record string + err error + want string + }{ + {"", nil, "not yet taken in by the router"}, + {`{"state":"open","tickets":{"a":{"kind":"telegram"},"b":{"kind":"telegram"},"c":{"kind":"desktop"}}}`, nil, "offered on desktop, telegram: the operator is asked"}, + {`{"state":"open"}`, nil, "offered, channel not yet named: the operator is asked"}, + {`{"state":"held","held":"no channel carries destroy"}`, nil, "held by the router, not shown to the operator: no channel carries destroy"}, + {`{"state":"refused","warrant":{"ask":"bus-r1","asker":"nats","outcome":"refused","words":"its words carry a path"}}`, nil, "refused by the router, so nothing will be removed: its words carry a path"}, + {"", errors.New("no responders"), "cannot be read now (no responders)"}, + } { + rs := requestStore{Standing: func(string) (*stdio.StateEntry, error) { + if c.record == "" { + return nil, c.err + } + return &stdio.StateEntry{Value: []byte(c.record)}, nil + }} + if got := standingOf(rs, "bus-r1"); !strings.Contains(got, c.want) || (!strings.HasPrefix(c.want, "offered") && strings.Contains(got, "operator is asked")) { + t.Errorf("the record %s (%v) is said %q, not %q", c.record, c.err, got, c.want) + } } } diff --git a/modules/nats/cmd/nats-tools/tools.go b/modules/nats/cmd/nats-tools/tools.go index 8235f97de..60a3107e1 100644 --- a/modules/nats/cmd/nats-tools/tools.go +++ b/modules/nats/cmd/nats-tools/tools.go @@ -57,13 +57,30 @@ type Connection struct { OutBytes int64 `json:"out_bytes"` PendingBytes int64 `json:"pending_bytes"` Subscriptions int64 `json:"subscriptions"` + // Busiest is the connection's busiest subscriptions by messages, at most busiestKept (design 47 H2 §813 (5), H-A-356). + Busiest []ConnSubscription `json:"busiest_subscriptions,omitempty"` } +// ConnSubscription is one subscription of a connection: its subject, queue group and the messages it received. +type ConnSubscription struct { + Subject string `json:"subject"` + Queue string `json:"queue,omitempty"` + Msgs int64 `json:"msgs"` +} + +// busiestKept is how many of a connection's subscriptions it carries, the busiest by messages (H-A-356: five). +const busiestKept = 5 + func connectionsOf(connz []byte) ([]Connection, error) { var doc struct { Connections []struct { Connection AuthorizedUser string `json:"authorized_user"` + Subs []struct { + Subject string `json:"subject"` + Queue string `json:"qgroup"` + Msgs int64 `json:"msgs"` + } `json:"subscriptions_list_detail"` } `json:"connections"` } if err := json.Unmarshal(connz, &doc); err != nil { @@ -73,6 +90,13 @@ func connectionsOf(connz []byte) ([]Connection, error) { for _, c := range doc.Connections { conn := c.Connection conn.User = c.AuthorizedUser + for _, sub := range c.Subs { + conn.Busiest = append(conn.Busiest, ConnSubscription{Subject: sub.Subject, Queue: sub.Queue, Msgs: sub.Msgs}) + } + sort.SliceStable(conn.Busiest, func(i, j int) bool { return conn.Busiest[i].Msgs > conn.Busiest[j].Msgs }) + if len(conn.Busiest) > busiestKept { + conn.Busiest = conn.Busiest[:busiestKept] + } out = append(out, conn) } return out, nil diff --git a/modules/nats/cmd/nats-tools/tools_test.go b/modules/nats/cmd/nats-tools/tools_test.go index ce2b827d1..1bc0b8eb4 100644 --- a/modules/nats/cmd/nats-tools/tools_test.go +++ b/modules/nats/cmd/nats-tools/tools_test.go @@ -17,7 +17,9 @@ import ( const connz = `{"connections":[ {"cid":1,"ip":"192.0.2.1","name":"mesh-host/anchor","authorized_user":"node.anchor","out_bytes":10,"in_bytes":5,"pending_bytes":0,"subscriptions":2,"in_msgs":3,"out_msgs":4}, - {"cid":2,"ip":"192.0.2.2","name":"laptop.node-tools","authorized_user":"laptop.node-tools","out_bytes":900,"in_bytes":50,"pending_bytes":7,"subscriptions":300,"in_msgs":30,"out_msgs":40}]}` + {"cid":2,"ip":"192.0.2.2","name":"laptop.node-tools","authorized_user":"laptop.node-tools","out_bytes":900,"in_bytes":50,"pending_bytes":7,"subscriptions":300,"in_msgs":30,"out_msgs":40, + "subscriptions_list_detail":[{"subject":"a","msgs":1},{"subject":"b","qgroup":"q","msgs":60},{"subject":"c","msgs":5}, + {"subject":"d","msgs":40},{"subject":"e","msgs":3},{"subject":"f","msgs":2}]}]}` const subsz = `{"num_subscriptions":3,"subscriptions_list":[ {"subject":"$SRV.INFO","msgs":4,"cid":2}, @@ -59,6 +61,10 @@ func TestConnectionsAreNamedByTheirUserAndSorted(t *testing.T) { if len(cs) != 2 || cs[0].User != "laptop.node-tools" || cs[1].User != "node.anchor" { t.Fatalf("%+v", cs) } + // Design 47 H2 §813 (5), H-A-356: a connection's five busiest subscriptions by messages, its queue group named. + if b := cs[0].Busiest; fmt.Sprint(b) != "[{b q 60} {d 40} {c 5} {e 3} {f 2}]" || cs[1].Busiest != nil { + t.Fatalf("busiest %v, %v", b, cs[1].Busiest) + } narrowed, _ := Connections([]byte(connz), "anchor", "pending", 10) if n := narrowed["total"].(int); n != 1 { t.Fatalf("narrowed to %d", n) @@ -216,11 +222,11 @@ func TestAGrantIsInForceOnlyWhenTheServerReloadedAfterTheListWasWritten(t *testi } // **The tools that change the bus are two, each refuses before it reaches the bus, and every other tool reads** -// (issue 1952 N1-N3). A row per refusal: the bus is never opened for them. +// (issue 1952 N1-N3). A row per refusal: the bus is never opened for them, but to read an accepted module's durable's +// twin (H-A-472), and a twin that cannot be read refuses. func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { bus := func(context.Context) (jetstream.JetStream, func(), error) { - t.Fatal("the bus was opened for a call that must be refused") - return nil, nil, nil + return nil, nil, errors.New("the bus is opened here only to read a twin, and cannot be") } said := func(string, any) error { t.Fatal("an audit event was said for a refused call"); return nil } newForm := func() (map[string]keeper.Asked, error) { @@ -234,6 +240,11 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { } return map[string]keeper.Asked{"m": {Module: "m", Made: made}}, nil } + // The keeper's accepted set (its state plans, §538): m, which asks for kept data, and quiet, which asks for none and + // so has no key in asked (review round 2: a module keeping no bus data still has live durables). + accepted := func() (map[string]keeper.Planned, error) { + return map[string]keeper.Planned{"m": {Module: "m"}, "quiet": {Module: "quiet"}}, nil + } for _, c := range []struct { tool string args map[string]any @@ -255,10 +266,20 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { // CAT-N9: an entry of the new form goes only by drop or recreate; an old section's goes as before. {"nats_stream_remove", map[string]any{"stream": "m_log", "why": "x"}, "removed only by nats_drop"}, {"nats_bucket_remove", map[string]any{"bucket": "m_drafts", "node": "g14", "why": "x"}, "m's kept data \"drafts\""}, - {"nats_consumer_remove", map[string]any{"stream": "m_log", "consumer": "c", "why": "x"}, "removed only by nats_drop"}, + // Design 47 H, H-A-127: a consumer is judged by its name: an accepted module's durable is refused on any stream. + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_m", "why": "x"}, "a module of an accepted manifest"}, + {"nats_consumer_remove", map[string]any{"stream": "m_log", "consumer": "ace_m", "why": "x"}, "a module of an accepted manifest"}, + // H-A-128: a durable beginning __ is the module's too. + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_m_keeper", "why": "x"}, "a module of an accepted manifest"}, + // H-A-128: an accepted module that asks for no kept data is refused too, its durables and its suffixed ones. + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_quiet", "why": "x"}, "a module of an accepted manifest"}, + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_quiet_tools", "why": "x"}, "a module of an accepted manifest"}, + // H-A-472 (1): a twin that cannot be read keeps the durable refused, saying so. + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_m", "why": "x"}, "its twin novox_m_tools on EVENTS cannot be read"}, + {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_quiet_tools", "why": "x"}, "its twin novox_quiet on EVENTS cannot be read"}, } { var run func(map[string]any) (any, error) - for _, tl := range removalTools(bus, said, newForm) { + for _, tl := range removalTools(bus, said, newForm, accepted, nil, nil) { if tl.Name == c.tool { run = tl.Run } @@ -270,6 +291,64 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { t.Errorf("%s %v: %v, want a refusal saying %q", c.tool, c.args, err, c.want) } } + // H-A-472 (1): a module's durable whose twin (_ and __tools, A-340) is current goes; the + // twin is current with pulls waiting and a delivery within the day; a durable with another suffix has no twin. + now := time.Date(2026, 11, 22, 14, 0, 0, 0, time.UTC) + hourAgo, twoDaysAgo := now.Add(-time.Hour), now.Add(-48*time.Hour) + day := DefaultTwinCurrentHours * time.Hour + for _, c := range []struct { + name string + info *jetstream.ConsumerInfo + within time.Duration + want bool + }{ + {"pulls waiting, delivered an hour ago", &jetstream.ConsumerInfo{NumWaiting: 1, Delivered: jetstream.SequenceInfo{Last: &hourAgo}}, day, true}, + {"no pull waiting", &jetstream.ConsumerInfo{Delivered: jetstream.SequenceInfo{Last: &hourAgo}}, day, false}, + {"delivered two days ago", &jetstream.ConsumerInfo{NumWaiting: 2, Delivered: jetstream.SequenceInfo{Last: &twoDaysAgo}}, day, false}, + {"delivered two days ago, the setting at 72 hours", &jetstream.ConsumerInfo{NumWaiting: 2, Delivered: jetstream.SequenceInfo{Last: &twoDaysAgo}}, 72 * time.Hour, true}, + {"delivered an hour ago, the setting at 1 hour", &jetstream.ConsumerInfo{NumWaiting: 2, Delivered: jetstream.SequenceInfo{Last: &hourAgo}}, time.Hour, false}, + {"never delivered", &jetstream.ConsumerInfo{NumWaiting: 2}, day, false}, + {"not read", nil, day, false}, + } { + if got := current(c.info, now, c.within); got != c.want { + t.Errorf("current, %s: %v, want %v", c.name, got, c.want) + } + } + // H-A-472 third addendum (2): the setting twin-current-hours, in hours; its default 24 when the configuration gives + // none or no positive whole number. + for _, c := range []struct { + raw string + err error + want time.Duration + }{ + {"72", nil, 72 * time.Hour}, {"1", nil, time.Hour}, {"", errors.New("no configuration"), 24 * time.Hour}, + {"0", nil, 24 * time.Hour}, {"-3", nil, 24 * time.Hour}, {`"x"`, nil, 24 * time.Hour}, + } { + if got := twinCurrentWithin(json.RawMessage(c.raw), c.err); got != c.want { + t.Errorf("twin-current-hours %q (%v): %s, want %s", c.raw, c.err, got, c.want) + } + } + for _, c := range []struct{ module, durable, want string }{ + {"m", "m", "novox_m_tools"}, {"m", "m_tools", "novox_m"}, {"m", "m_keeper", ""}, {"m", "m_tools_x", ""}, + } { + if got := twinOf("novox", c.module, c.durable); got != c.want { + t.Errorf("the twin of novox_%s: %q, want %q", c.durable, got, c.want) + } + } + // An orphan on a module's kept-data stream is not refused by its stream (H-A-126): the call reaches the bus. + unreachable := func(context.Context) (jetstream.JetStream, func(), error) { + return nil, nil, errors.New("the bus is not reached here") + } + for _, tl := range removalTools(unreachable, said, newForm, accepted, nil, nil) { + if tl.Name != "nats_consumer_remove" { + continue + } + for _, orphan := range []string{"c", "novox_mx", "novox_mx_keeper"} { + if _, err := tl.Run(map[string]any{"stream": "m_log", "consumer": orphan, "why": "an orphan"}); err == nil || !strings.Contains(err.Error(), "not reached") { + t.Errorf("the orphan %s on m_log: %v, want the call to reach the bus", orphan, err) + } + } + } // The read tools stay read tools: none of the first ten takes a `why`, and the list is these ten. for _, tl := range tools(nil, nil, nil) { if _, ok := tl.Input["why"]; ok || strings.Contains(tl.Name, "remove") { diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 68788bed4..41428e100 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -8,6 +8,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "sort" "strings" "sync" @@ -84,11 +85,14 @@ type EventFill struct { // Accepted is one module's entry as the catalog half's watched branches give it (design 47 G §344, §433, §532): the // module, its manifest's digest, the catalog revision of the branch it was read from, and its bus-state entries whole. +// Old are the entries its old sections declare, as OldPlansOf names and caps them (design 47 H H-A-229, H-A-230): asked +// for too, but never made by the keeper. type Accepted struct { Module string `json:"module"` Digest string `json:"digest"` Revision uint64 `json:"revision"` BusState []catalogue.BusStateEntry `json:"bus-state"` + Old []Plan `json:"old-sections,omitempty"` } // CatalogModule is one module of the catalog half for the bus module (design 47 G §344, §532, §533, §547): what its @@ -146,7 +150,9 @@ type Asked struct { Digest string `json:"digest,omitempty"` Revision uint64 `json:"revision"` Entries []catalogue.BusStateEntry `json:"entries"` - Made map[string]Made `json:"made,omitempty"` + // Old are the entries its old sections declare, as last planned (Accepted's Old; design 47 H H-A-229, H-A-230). + Old []Plan `json:"old-sections,omitempty"` + Made map[string]Made `json:"made,omitempty"` // Drifts are the local names a later watched branch asks with other settings, as last said (design 47 G §532). Drifts map[string]Drift `json:"drifts,omitempty"` At time.Time `json:"at"` @@ -259,7 +265,8 @@ type Limits struct { } // CapSum is the sum, in bytes, of the caps of every object the entries made hold, but for the entry of skipModule and -// skipLocal (design 47 G §547): what the bus's limits are read against. An entry never made, or refused, holds none. +// skipLocal (design 47 G §547): what the bus's limits are read against. An entry never made, or refused, holds none, and +// one an old objects, log or stream section keeps is counted once, in the old sections' caps (design 47 H H-A-229). func CapSum(held map[string]Asked, skipModule, skipLocal string) int64 { var sum int64 for module, a := range held { @@ -267,6 +274,11 @@ func CapSum(held map[string]Asked, skipModule, skipLocal string) int64 { if (module == skipModule && local == skipLocal) || !(m.Created || m.Orphaned) { continue } + // A kept entry of an objects, log or stream section is in the old sections' caps already; a state's is not + // (design 47 G §547, H H-A-229). + if p, kept := oldKept(a.Old, local, m); kept && p.Storage != catalogue.StorageKeyValue { + continue + } for _, o := range m.Plan.Objects { sum += o.Settings.MaxBytes } @@ -337,8 +349,11 @@ type Keeper struct { // Act records a hand act through the seat mesh-hand-acts; Warrant reads the router's record of an ask. Act func(what, why, cause string) error Warrant func(askID string) (*oc.Ask, *oc.Warrant, error) - Now func() time.Time - Logf func(string, ...any) + // Cancel takes an ask back on the seat operator-channel (ADR 0259 §3's cancel): a drop or recreate the keeper refuses at + // once withdraws the ask its tool raised, in the same pass (design 47 H2 §813 (6)). + Cancel func(askID string) error + Now func() time.Time + Logf func(string, ...any) // Raise and Clear are the fill marks in percent (ADR 0595 §6): settings of the bus module, 75 and 70 by default. Raise, Clear int64 // Files are the snapshot files (the disk when nil); SnapshotsCap the cap of their directory in bytes and @@ -596,6 +611,15 @@ func (k *Keeper) Heard(a Accepted) { held.Made = map[string]Made{} } digest := EntriesDigest(a.BusState) + if len(a.Old) > 0 { + // The old sections' entries are planned too (design 47 H H-A-229): a module that declares none keeps its digest. + raw, _ := json.Marshal(struct { + BusState []catalogue.BusStateEntry `json:"bus-state"` + Old []Plan `json:"old-sections"` + }{a.BusState, a.Old}) + sum := sha256.Sum256(raw) + digest = "sha256:" + hex.EncodeToString(sum[:]) + } if p, ok := k.planned(a.Module); ok && found && p.Digest == digest { if held.Digest != a.Digest || held.Revision != a.Revision { held.Digest, held.Revision, held.At = a.Digest, a.Revision, k.now() @@ -603,13 +627,18 @@ func (k *Keeper) Heard(a Accepted) { } return } - held.Digest, held.Entries, held.Revision, held.At = a.Digest, a.BusState, a.Revision, k.now() + held.Digest, held.Entries, held.Old, held.Revision, held.At = a.Digest, a.BusState, a.Old, a.Revision, k.now() defer k.writePlan(a.Module, digest, held.Revision, a.BusState) asked := map[string]bool{} for _, e := range a.BusState { asked[e.Name] = true k.makeEntry(&held, e) } + for _, local := range sortedKeys(held.Made) { + if !asked[local] && k.keepOld(&held, local) { + asked[local] = true + } + } for _, local := range sortedKeys(held.Made) { m := held.Made[local] if asked[local] || m.Orphaned || local == SentLocal { @@ -650,6 +679,35 @@ func (k *Keeper) Sends(module string) { k.write(held) } +// keepOld keeps an entry the keeper made that an old section of the module declares under the same bus name (design 47 +// H H-A-229, H-A-230, H-A-231): never an orphan (one that was is asked for again, its condition cleared), compared with +// the bus and grown to the declared cap, and rebuilt on request; the keeper creates none of its objects the bus lacks and +// says no created for it, as the grants part makes and binds them. It answers whether an old section keeps it. An entry +// never made is none of the keeper's: every other old-section entry is the grants part's alone. +func (k *Keeper) keepOld(held *Asked, local string) bool { + m := held.Made[local] + p, ok := oldKept(held.Old, local, m) + if !ok || !m.Created || local == SentLocal { + return false + } + if m.Orphaned { + m.Orphaned = false + k.clear(conditionOrphaned, held.Module, local) + } + // Only the objects the keeper made are its own: one the old plan names beside them (a state's `-objects` the + // grants part made) is never compared, grown or rebuilt by the keeper (H-A-231). + var objects []Object + for _, o := range p.Objects { + if slices.ContainsFunc(m.Plan.Objects, func(made Object) bool { return made.Stream() == o.Stream() }) { + objects = append(objects, o) + } + } + m.Plan.Objects = objects + k.ensureMade(held, &m, false) + held.Made[local] = m + return true +} + // makeEntry makes one asked entry where the bus lacks it, compares it where it holds it, and says what it did. func (k *Keeper) makeEntry(held *Asked, e catalogue.BusStateEntry) { module := held.Module @@ -679,7 +737,11 @@ func (k *Keeper) makeEntry(held *Asked, e catalogue.BusStateEntry) { // ensure brings one planned entry onto the bus: each object the bus lacks created, a held one compared. A difference // that only grows is applied; any other is a drift, said and never fixed quietly. -func (k *Keeper) ensure(held *Asked, m *Made) { +func (k *Keeper) ensure(held *Asked, m *Made) { k.ensureMade(held, m, true) } + +// ensureMade is ensure; with create false an object the bus lacks is left to the part that makes it (an old section's, +// the grants part: design 47 H H-A-230) and nothing is created. +func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() asked, holds := map[string]Settings{}, map[string]Settings{} @@ -694,6 +756,9 @@ func (k *Keeper) ensure(held *Asked, m *Made) { m.Waiting = fmt.Sprintf("%s cannot be read: %v", o.Stream(), err) return } + if !found && !create { + continue + } if !found { if err := k.capRoom(ctx, held, m); err != nil { if errors.Is(err, ErrRetry) { @@ -794,11 +859,16 @@ func (k *Keeper) CheckAll() []CheckLine { out = append(out, lineOf(module, local, m)) continue } + asked := false for _, e := range held.Entries { if e.Name == local { + asked = true k.makeEntry(&held, e) } } + if !asked { + k.keepOld(&held, local) + } out = append(out, lineOf(module, local, held.Made[local])) } k.write(held) @@ -1005,13 +1075,14 @@ func (k *Keeper) asked(module string) (Asked, uint64, bool) { } // write keeps a module's key, or removes it when its manifest asks for nothing and nothing it made is held: a key goes -// only so, never because a module is missing from a first view. +// only so, never because a module is missing from a first view. Its plan key stays: plans is the accepted set, one key +// per module of a watched branch's newest revision, deleted only when no such revision lists it (design 47 G §538; +// H-A-128: nats_consumer_remove judges a module's durables by it). func (k *Keeper) write(a Asked) { if len(a.Entries) == 0 && len(a.Made) == 0 && len(a.Drifts) == 0 { if err := k.Store.Delete(StateAsked, a.Module); err != nil { k.logf("the key of %s cannot be removed from its own %s: %v", a.Module, StateAsked, err) } - _ = k.Store.Delete(StatePlans, a.Module) return } raw, _ := json.Marshal(a) diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index 500eb3d04..aaa61f679 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -327,6 +327,11 @@ func entry(name, storage, template string, options map[string]string) catalogue. func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}) ledger.Types = []catalogue.LedgerType{{Name: "decision", Indexes: []catalogue.LedgerIndex{{Name: "by-topic", On: []string{"topic"}}}}} + // A ledger's state and index buckets take its max-mib and no other option of it (design 47 H2's corrections, item 12, H-A-636). + bigLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024", "history": "5"}) + bigLedger.Types = ledger.Types + plainLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, nil) + plainLedger.Types = ledger.Types bare := entry("raw", catalogue.StorageStream, "", nil) bare.Configuration = map[string]json.RawMessage{"when-full": json.RawMessage(`"drop-oldest"`), "max-mib": json.RawMessage("8"), "max-age-days": json.RawMessage("3")} forGood := entry("reviews", catalogue.StorageStream, "", nil) @@ -363,11 +368,26 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { {name: "objects", entry: entry("files", catalogue.StorageObjectStore, catalogue.TemplateObjects, map[string]string{"max-mib": "32"}), objects: "object-store mesh-knowledge_files {32 MiB, age 0, history 0, new, size 0}", binding: "objects mesh-knowledge_files"}, + {name: "objects kept 7 days", entry: entry("outputs", catalogue.StorageObjectStore, catalogue.TemplateObjects, map[string]string{"max-mib": "1024", "max-age-days": "7"}), + objects: "object-store mesh-knowledge_outputs {1024 MiB, age 604800, history 0, new, size 0}", + binding: "objects mesh-knowledge_outputs"}, {name: "ledger", entry: ledger, objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {16 MiB, age 0, history 0, new, size 262144}; " + + "key-value mesh-knowledge_records_state {16 MiB, age 0, history 1, new, size 262144}; " + + "key-value mesh-knowledge_records_index-by-topic {16 MiB, age 0, history 1, new, size 262144}; " + + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}", + binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, + {name: "ledger naming max-mib 1024 and past values: its state and index buckets at 1 GiB, no other option reaching them (H-A-636)", entry: bigLedger, + objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + + "key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144}; " + + "key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144}; " + + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", + binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, + {name: "ledger naming no max-mib: its state and index buckets at the state default (H-A-636)", entry: plainLedger, + objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {64 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {64 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, {name: "bare stream", entry: bare, objects: "stream mesh-knowledge_raw [mesh.bus.mesh-knowledge.raw.>] {8 MiB, age 259200, history 0, old, size 0}", @@ -544,6 +564,30 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("old sections %d: 8 MiB counted", k.Status().OldBytes) } }}, + // §538, H-A-128: plans is the accepted set: a module that asks for no kept data keeps its plan key (no key in + // asked), even when a drift it had clears; the key goes only when no watched branch's newest revision lists it. + {"a module asking for no kept data keeps its plan key while it is listed", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + quiet := CatalogModule{Accepted: Accepted{Module: "quiet", Revision: 1}} + k.Catalog = func() (CatalogView, error) { + return CatalogView{Modules: []CatalogModule{quiet}, Drifts: []Drift{{Module: "quiet", Local: "x", Branch: "feature", From: "main"}}}, nil + } + _ = k.PlanCatalog() + k.Catalog = func() (CatalogView, error) { return CatalogView{Modules: []CatalogModule{quiet}}, nil } + _ = k.PlanCatalog() + if _, _, found, _ := k.Store.Get(StatePlans, "quiet"); !found { + t.Errorf("quiet is listed but has no plan key: the accepted set lost a module that keeps no bus data") + } + if _, ok := k.Held()["quiet"]; ok { + t.Errorf("quiet asks for nothing and has a key in asked: %+v", k.Held()["quiet"]) + } + k.Catalog = func() (CatalogView, error) { + return CatalogView{Modules: []CatalogModule{{Accepted: Accepted{Module: "m", Revision: 2}}}}, nil + } + _ = k.PlanCatalog() + if _, _, found, _ := k.Store.Get(StatePlans, "quiet"); found { + t.Errorf("quiet is listed nowhere and keeps its plan key") + } + }}, // A-367: a trunk with no revision yet (none-yet) is not yet viewed: nothing is planned, deleted or orphaned. {"a none-yet catalog half plans nothing and orphans nothing until a module is listed", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { k.Heard(Accepted{Module: "m", Revision: 9, BusState: []catalogue.BusStateEntry{drafts}}) @@ -822,6 +866,26 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { if got.Done.IsZero() || got.Waiting != "" || !strings.Contains(got.Error, "refused") || !strings.Contains(got.Error, w.Words) || len(bus.deleted) != 0 { t.Errorf("ended %+v, deleted %v: the router's refusal and its words, nothing removed", got, bus.deleted) } + // Design 47 H2 §813 (6): the refused request withdraws its ask in the same pass; a cancel that fails is said. + var cancelled []string + k.Cancel = func(id string) error { + cancelled = append(cancelled, id) + if id == "bus-2" { + return errors.New("no responders") + } + return nil + } + for _, r := range []Request{{ID: "rc", Verb: VerbRecreate, Module: "m", Local: "drafts", Ask: "bus-1", Caller: "person.jo"}, + {ID: "rd", Verb: VerbDrop, Module: "m", Local: "drafts", Ask: "bus-2", Caller: "person.jo"}} { + raw, _ = json.Marshal(r) + _, _ = store.Put(StateRequests, r.ID, raw) + } + k.ActOnRequests() + raw, _, _, _ = store.Get(StateRequests, "rd") + _ = json.Unmarshal(raw, &got) + if fmt.Sprint(cancelled) != "[bus-1 bus-2]" || !strings.Contains(got.Error, "bus-2 could not be withdrawn: no responders") { + t.Errorf("cancelled %v, ended %+v: each refused request's ask withdrawn once, a failed cancel said", cancelled, got) + } }}, {"a drop waits for the warrant, refuses another act's, then acts after a snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { store := k.Store.(*memStore) @@ -848,10 +912,11 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Fatalf("acted with no warrant: %+v, deleted %v", got, bus.deleted) } binds := func(act occ.Act) string { d, _ := occ.ActDigest(act); return d } + // Design 47 H-A-237: the ask's option is at the approve level, and an approve-level choice warrants the drop. choose := func(act occ.Act) { - ask.Options = []oc.Option{{ID: "go", Label: "Remove", Level: occ.Destroy, Binds: binds(act)}} + ask.Options = []oc.Option{{ID: "go", Label: "Remove", Level: occ.Approve, Binds: binds(act)}, {ID: "keep", Label: "Keep it", Does: "nothing is removed", Level: occ.Acknowledge}} w = &oc.Warrant{Ask: "bus-1", Asker: Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, - Option: "go", Label: "Remove", Level: occ.Destroy, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)} + Option: "go", Label: "Remove", Level: occ.Approve, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)} } choose(occ.Act{"verb": "drop", "module": "m", "local": "log"}) if got := put(Request{ID: "r1", Verb: VerbDrop, Module: "m", Local: "drafts", Ask: "bus-1", Caller: "person.jo"}); !strings.Contains(got.Error, "bound") || len(bus.deleted) != 0 { @@ -866,8 +931,7 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { } refused(Request{ID: "r1a", Verb: VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo"}, "names no ask") choose(occ.Act{"verb": "drop", "module": "m", "local": "drafts"}) - w.Level, w.Label, ask.Options[0].Level = occ.Approve, "Keep", occ.Approve - w.AskDigest = occ.Digest(ask) + w.Option, w.Level, w.Label = "keep", occ.Acknowledge, "Keep it" refused(Request{ID: "r1b", Verb: VerbDrop, Module: "m", Local: "drafts", Ask: "bus-1", Caller: "person.jo"}, "nothing is removed") choose(occ.Act{"verb": "drop", "module": "m", "local": "drafts"}) w.Asker = "mesh-grants" @@ -1088,6 +1152,90 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("the hand acts: %v", acts) } }}, + // Design 47 H H-A-229, H-A-230, H-A-231: an entry the keeper made, now declared in the module's old sections under + // the same bus name, is asked for: its orphan cleared, grown to the declared cap, rebuilt on request; the keeper + // creates nothing an old section declares and says no created for it. + {"an entry an old section declares is no orphan and is rebuilt, nothing of the old sections made", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + store := k.Store.(*memStore) + incoming := entry("incoming", catalogue.StorageObjectStore, catalogue.TemplateObjects, map[string]string{"max-mib": "8"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{drafts, incoming}}) + k.Heard(Accepted{Module: "m", Revision: 2}) + if a := k.Held()["m"]; !a.Made["incoming"].Orphaned || !a.Made["drafts"].Orphaned { + t.Fatalf("held %+v: both orphans once no section asks for them", a.Made) + } + delete(bus.held, "OBJ_m_drafts-objects") + made := fmt.Sprint(bus.created) + out.reset() + old := OldPlansOf(catalogue.Manifest{Module: "m", State: []catalogue.StateDeclaration{{Name: "drafts"}, {Name: "bound"}}, + Objects: []catalogue.ObjectsDeclaration{{Name: "incoming", MaxMiB: 16}}}) + k.Heard(Accepted{Module: "m", Revision: 3, Old: old}) + a := k.Held()["m"] + if a.Made["incoming"].Orphaned || a.Made["drafts"].Orphaned || len(a.Made) != 2 { + t.Errorf("held %+v: incoming and drafts asked for by the old sections, bound none of the keeper's", a.Made) + } + if fmt.Sprint(bus.created) != made || len(out.events) != 0 || bus.held["OBJ_m_incoming"].MaxBytes != 16*MiB { + t.Errorf("created %v (was %s), said %v, incoming held %+v: nothing made or said, grown to the declared 16 MiB", + bus.created, made, out.events, bus.held["OBJ_m_incoming"]) + } + if fmt.Sprint(out.conds) != "[cleared nats.orphaned.m_drafts cleared nats.orphaned.m_incoming]" { + t.Errorf("conditions %v: both orphans cleared", out.conds) + } + k.CheckAll() + if fmt.Sprint(bus.created) != made { + t.Errorf("the check created %v (was %s): the grants part makes an old section's objects", bus.created, made) + } + binds, _ := occ.ActDigest(occ.Act{"verb": "recreate", "module": "m", "local": "incoming"}) + ask := oc.Ask{ID: "bus-9", Who: occ.Operator, Expires: occ.FormatTime(k.now().Add(time.Hour)), Options: []oc.Option{{ID: "go", Label: "Rebuild", Level: occ.Destroy, Binds: binds}}} + w := &oc.Warrant{Ask: "bus-9", Asker: Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, + Option: "go", Label: "Rebuild", Level: occ.Destroy, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)} + k.Warrant = func(string) (*oc.Ask, *oc.Warrant, error) { return &ask, w, nil } + out.reset() + raw, _ := json.Marshal(Request{ID: "r9", Verb: VerbRecreate, Module: "m", Local: "incoming", Ask: "bus-9"}) + _, _ = store.Put(StateRequests, "r9", raw) + k.ActOnRequests() + raw, _, _, _ = store.Get(StateRequests, "r9") + var got Request + _ = json.Unmarshal(raw, &got) + if got.Error != "" || fmt.Sprint(out.events) != "[recreated m incoming]" || bus.held["OBJ_m_incoming"].MaxBytes != 16*MiB { + t.Errorf("request %+v, said %v, held %+v: rebuilt at the declared cap", got, out.events, bus.held["OBJ_m_incoming"]) + } + }}, + // Design 47 H H-A-231, G §547: a state the keeper made as its bucket alone keeps only that bucket; the store beside it + // the grants part made is neither compared, grown nor rebuilt by the keeper; a kept state's cap stays in the sum, a + // kept objects section's is counted in the old sections' caps alone. + {"a kept state's store made by the grants part is left alone, its bucket's cap summed", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + store := k.Store.(*memStore) + incoming := entry("incoming", catalogue.StorageObjectStore, catalogue.TemplateObjects, map[string]string{"max-mib": "8"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{incoming}}) + old := OldPlansOf(catalogue.Manifest{Module: "m", State: []catalogue.StateDeclaration{{Name: "findings"}}, + Objects: []catalogue.ObjectsDeclaration{{Name: "incoming", MaxMiB: 8}}}) + bucket := old[0].Objects[0] + bus.held[bucket.Stream()] = bucket.Settings + bus.held["OBJ_m_findings-objects"] = Settings{MaxBytes: 8 * MiB, Discard: DiscardNew} + held := k.Held()["m"] + held.Made["findings"] = Made{Plan: Plan{Module: "m", Local: "findings", Storage: catalogue.StorageKeyValue, Template: catalogue.TemplateState, + Objects: []Object{bucket}}, Created: true, Orphaned: true} + k.write(held) + k.Heard(Accepted{Module: "m", Revision: 2, Old: old}) + k.CheckAll() + if m := k.Held()["m"].Made["findings"]; m.Orphaned || len(m.Plan.Objects) != 1 || len(bus.updated) != 0 || m.Drift != "" { + t.Errorf("findings %+v, updated %v: kept, its bucket alone, the grants part's store not grown", m, bus.updated) + } + if sum := CapSum(k.Held(), "", ""); sum != 64*MiB { + t.Errorf("the sum is %d MiB, want 64: the kept state's bucket, not the kept objects section's store", sum/MiB) + } + binds, _ := occ.ActDigest(occ.Act{"verb": "recreate", "module": "m", "local": "findings"}) + ask := oc.Ask{ID: "bus-8", Who: occ.Operator, Expires: occ.FormatTime(k.now().Add(time.Hour)), Options: []oc.Option{{ID: "go", Label: "Rebuild", Level: occ.Destroy, Binds: binds}}} + w := &oc.Warrant{Ask: "bus-8", Asker: Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, + Option: "go", Label: "Rebuild", Level: occ.Destroy, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)} + k.Warrant = func(string) (*oc.Ask, *oc.Warrant, error) { return &ask, w, nil } + raw, _ := json.Marshal(Request{ID: "r8", Verb: VerbRecreate, Module: "m", Local: "findings", Ask: "bus-8"}) + _, _ = store.Put(StateRequests, "r8", raw) + k.ActOnRequests() + if fmt.Sprint(bus.deleted) != "[KV_m_findings]" || bus.held["OBJ_m_findings-objects"].MaxBytes != 8*MiB { + t.Errorf("deleted %v, store held %+v: the recreate rebuilds the bucket alone", bus.deleted, bus.held["OBJ_m_findings-objects"]) + } + }}, {"a recreate rebuilds a drifted entry after a snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { store := k.Store.(*memStore) k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{log}}) @@ -1165,9 +1313,12 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { _, _ = store.Put(StateRequests, "r7", raw) raw, _ = json.Marshal(Request{ID: "r8", Verb: VerbDrop, Module: "m", Local: "drafts", Ask: "bus-8", Caller: "person.jo", At: k.now().Add(-AskLasts - time.Minute)}) _, _ = store.Put(StateRequests, "r8", raw) + // Design 47 H-A-239: the ask's own expiry as asked bounds it, past the default. + raw, _ = json.Marshal(Request{ID: "r7a", Verb: VerbDrop, Module: "m", Local: "drafts", Ask: "bus-7a", Caller: "person.jo", At: k.now().Add(-2 * AskLasts), AskExpires: k.now().Add(time.Hour)}) + _, _ = store.Put(StateRequests, "r7a", raw) k.ActOnRequests() - if got := get("r7"); !got.Done.IsZero() { - t.Errorf("a request whose ask still runs ended: %+v", got) + if got, longer := get("r7"), get("r7a"); !got.Done.IsZero() || !longer.Done.IsZero() { + t.Errorf("a request whose ask still runs ended: %+v, %+v", got, longer) } if got := get("r8"); got.Done.IsZero() || !strings.Contains(got.Error, "ended at") || len(bus.deleted) != 0 { t.Errorf("a request whose ask ended unanswered: %+v, deleted %v", got, bus.deleted) diff --git a/modules/nats/internal/keeper/plan.go b/modules/nats/internal/keeper/plan.go index 396f8b82c..c9c8fb2f1 100644 --- a/modules/nats/internal/keeper/plan.go +++ b/modules/nats/internal/keeper/plan.go @@ -211,8 +211,13 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { if capMiB <= 0 { return Plan{}, fmt.Errorf("objects %q gives no %s, which the template objects requires", e.Name, catalogue.OptionCapMiB) } + // An object is kept for good unless the objects name max-age-days (design 47 H2 H-A-434): the store's max age. + age, err := opts.int(catalogue.OptionAgeDays, 0) + if err != nil { + return Plan{}, err + } p.Binding.ObjectStore = name - p.Objects = []Object{{Kind: KindObjects, Name: name, Settings: Settings{MaxBytes: capMiB * MiB, Discard: DiscardNew}}} + p.Objects = []Object{{Kind: KindObjects, Name: name, Settings: Settings{MaxBytes: capMiB * MiB, MaxAgeSeconds: days(age), Discard: DiscardNew}}} case e.Storage == catalogue.StorageLedger && e.Template == catalogue.TemplateLedger: history, err := logSettings(opts) if err != nil { @@ -224,7 +229,13 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { return Plan{}, err } history.MaxAgeSeconds = days(age) - state, err := stateSettings(options{}) + // The state bucket and each index bucket take the ledger's own max-mib, as its history and snapshot do, and no + // other option of it; with none they keep the state default (design 47 H2's corrections, item 12, H-A-636). + stateOpts := options{} + if raw, ok := opts.raw[catalogue.OptionCapMiB]; ok { + stateOpts.raw = map[string]json.RawMessage{catalogue.OptionCapMiB: raw} + } + state, err := stateSettings(stateOpts) if err != nil { return Plan{}, err } @@ -423,3 +434,70 @@ func Differs(asked, held Settings) string { add("key-ttl", asked.KeyTTL, held.KeyTTL) return strings.Join(out, "; ") } + +// OldPlansOf are the entries a manifest declares in its old sections (state, objects, logs, streams), each named on the +// bus and capped as the grants part composes it, by the SDK's one naming per section (design 47 H H-A-229, H-A-230): a +// state `_` with its object store `-objects` beside it (none for a state only read, or one whose +// store's name is one of the module's own object buckets), an objects section `_`, a log +// `LOG__` and a stream its local name in capitals. They are asked for: an entry the keeper made under one +// of their bus names is never an orphan, is kept, compared and grown to the declared cap, and rebuilt on request; the +// keeper creates none of them and says no created for one (the grants part makes and binds them). Pure. +func OldPlansOf(m catalogue.Manifest) []Plan { + module := m.Module + var out []Plan + own := map[string]bool{} + for _, o := range m.Objects { + own[o.Name] = true + } + for _, s := range m.State { + capMiB := int64(s.MaxMiB) + if capMiB <= 0 { + capMiB = StateCap / MiB + } + p := Plan{Module: module, Local: s.Name, Storage: catalogue.StorageKeyValue, Template: catalogue.TemplateState, + Objects: []Object{{Kind: KindBucket, Name: buscompose.BucketName(module, s.Name), + Settings: Settings{MaxBytes: capMiB * MiB, MaxAgeSeconds: int64(s.TTLSeconds), History: int64(max(s.History, 1)), + Discard: DiscardNew, MaxMsgSize: ValueMost, KeyTTL: s.KeyTTL}}}} + if objects := catalogue.StateObjectsName(s.Name); !s.ReadOnly && !own[objects] { + objCap := int64(s.MaxMiB) + if objCap <= 0 { + objCap = StateObjectsCapMiB + } + objCap = min(max(objCap, catalogue.ObjectsLeastMiB), catalogue.ObjectsMostMiB) + p.Objects = append(p.Objects, Object{Kind: KindObjects, Name: catalogue.ObjectsBucket(module, objects), + Settings: Settings{MaxBytes: objCap * MiB, Discard: DiscardNew}}) + } + out = append(out, p) + } + for _, o := range m.Objects { + out = append(out, Plan{Module: module, Local: o.Name, Storage: catalogue.StorageObjectStore, Template: catalogue.TemplateObjects, + Objects: []Object{{Kind: KindObjects, Name: o.Bucket(module), Settings: Settings{MaxBytes: int64(o.MaxMiB) * MiB, Discard: DiscardNew}}}}) + } + for _, l := range m.Logs { + out = append(out, Plan{Module: module, Local: l.Name, Storage: catalogue.StorageStream, Template: catalogue.TemplateLog, + Objects: []Object{{Kind: KindStream, Name: buscompose.LogStreamName(module, l.Name), Subjects: []string{buscompose.LogSubject(module, l.Name) + ".>"}, + Settings: Settings{MaxBytes: int64(l.Cap()) * MiB, MaxAgeSeconds: days(int64(l.MaxAgeDays)), Discard: DiscardNew, MaxMsgSize: buscompose.LogMaxMessageBytes}}}}) + } + for _, s := range m.Streams { + discard := DiscardOld + if s.KeepsHistory() { + discard = DiscardNew + } + out = append(out, Plan{Module: module, Local: s.Name, Storage: catalogue.StorageStream, + Objects: []Object{{Kind: KindStream, Name: s.BusName(), Settings: Settings{MaxBytes: int64(s.Cap()) * MiB, + MaxAgeSeconds: days(int64(s.Days())), Discard: discard, WorkQueue: s.Retention == catalogue.StreamRetentionWorkQueue}}}}) + } + return out +} + +// oldKept is the old-section plan that keeps the entry made under local, or false: one of olds of the same local name +// whose objects are on the bus under the same names as the entry's (design 47 H H-A-229, H-A-230). +func oldKept(olds []Plan, local string, m Made) (Plan, bool) { + for _, p := range olds { + if p.Local != local || len(p.Objects) == 0 || len(m.Plan.Objects) == 0 || p.Objects[0].Stream() != m.Plan.Objects[0].Stream() { + continue + } + return p, true + } + return Plan{}, false +} diff --git a/modules/nats/internal/keeper/requests.go b/modules/nats/internal/keeper/requests.go index 9367b5546..0f1b08821 100644 --- a/modules/nats/internal/keeper/requests.go +++ b/modules/nats/internal/keeper/requests.go @@ -40,6 +40,9 @@ type Request struct { At time.Time `json:"at"` // Ask is the id of the operator's ask the tool raised for a recreate or a drop; the keeper acts only on its warrant. Ask string `json:"ask,omitempty"` + // AskExpires is when that ask ends unanswered, as its caller asked it (design 47 H-A-237, H-A-239): the keeper's + // bound where the router holds no record of the ask. + AskExpires time.Time `json:"ask-expires,omitempty"` // Done is when the keeper ended it, Outcome what it did, Error why not. Done time.Time `json:"done,omitempty"` Outcome string `json:"outcome,omitempty"` @@ -68,11 +71,12 @@ type Request struct { Unrecorded string `json:"unrecorded,omitempty"` } -// AskLasts is how long the operator's ask for a recreate or a drop waits for an answer: the bound of its highest option -// level, destroy (design 47 G §570: no asker asks for longer than its level allows; the asker client refuses more). It is -// shorter than the day the state requests keeps a key, so a request whose ask ended unanswered is ended by the keeper, -// saying so, before its key ages out, and the warrant's acted key (ActedKey) outlives the ask it spends. -const AskLasts = occ.DestroyLasts +// AskLasts is how long the operator's ask for a recreate or a drop waits for an answer when its caller names no expiry: +// sixty minutes (design 47 H-A-237: the ask is at the approve level, with the asker's expiry, a bend that ends with the +// research effort designing the channel that carries the destroy proof, design 47 H2 §813 (11)). It is shorter than the day the state requests keeps a key, so a request whose ask ended unanswered is +// ended by the keeper, saying so, before its key ages out, and the warrant's acted key (ActedKey) outlives the ask it +// spends. +const AskLasts = 60 * time.Minute // ActedPrefix started the spend record's key while it was kept in StateRequests (`acted.`); a key of that form // still met there is no request and is skipped. @@ -165,6 +169,7 @@ func (k *Keeper) ActOnRequests() { r.Done, r.Outcome = k.now(), outcome if err != nil { r.Error = err.Error() + k.withdraw(&r) } data, _ := json.Marshal(r) if _, err := k.Store.Put(StateRequests, key, data); err != nil { @@ -287,7 +292,7 @@ func (k *Keeper) act(r *Request) (string, error) { } // warranted holds a recreate or a drop to the operator's warrant on the ask its tool raised: chosen by the operator, -// on that ask, binding exactly this act. +// on that ask, at the approve level or above, binding exactly this act. func (k *Keeper) warranted(r *Request) error { if r.Ask == "" || k.Warrant == nil { return fmt.Errorf("a %s acts only on the operator's warrant, and this request names no ask", r.Verb) @@ -303,8 +308,12 @@ func (k *Keeper) warranted(r *Request) error { } // An ask that ended unanswered ends its request, said: never a request that waits until its key ages out. And a // warrant is not acted on once its ask ended, so a request handed after its acted key aged out acts on nothing. + // Where the router holds no record, the ask's own expiry as asked bounds it (design 47 H-A-239), else the default. var expires time.Time - if !r.At.IsZero() { + switch { + case !r.AskExpires.IsZero(): + expires = r.AskExpires + case !r.At.IsZero(): expires = r.At.Add(AskLasts) } if ask != nil { @@ -323,7 +332,10 @@ func (k *Keeper) warranted(r *Request) error { if err != nil { return fmt.Errorf("no warrant: %w", err) } - if o.Level != occ.Destroy { + // An approve-level choice warrants a recreate or a drop (design 47 H-A-237): no channel carries a destroy answer yet, + // so the ask is at the approve level; a destroy-level choice still warrants it. The bend ends with the research effort + // that designs the channel carrying the destroy proof (design 47 H2 §813 (11)); this check then asks the destroy level. + if occ.Rank(o.Level) < occ.Rank(occ.Approve) { return fmt.Errorf("the operator chose %s, so nothing is removed", o.Label) } return occ.Performs(o, r.Act()) @@ -357,3 +369,19 @@ func (k *Keeper) record(r *Request, what string) { k.logf("the hand act %q could not be recorded: %v", what, err) } } + +// withdraw takes back the operator's ask of a drop or recreate the keeper refused (design 47 H2 §813 (6)): nothing is left +// for the operator to answer once the request ended. A cancel that cannot be sent is said on the request's end. +func (k *Keeper) withdraw(r *Request) { + if r.Ask == "" || (r.Verb != VerbDrop && r.Verb != VerbRecreate) { + return + } + if k.Cancel == nil { + r.Error += "; its ask " + r.Ask + " is not withdrawn: the keeper holds no cancel" + return + } + if err := k.Cancel(r.Ask); err != nil { + k.logf("the ask %s of the refused request %s cannot be withdrawn: %v", r.Ask, r.ID, err) + r.Error += fmt.Sprintf("; its ask %s could not be withdrawn: %v", r.Ask, err) + } +} diff --git a/modules/nats/module.json b/modules/nats/module.json index 75e59564f..57b75d50d 100644 --- a/modules/nats/module.json +++ b/modules/nats/module.json @@ -1,6 +1,7 @@ { "module": "nats", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-delivery/modules/mesh-grants/busgrants": "0.1" }, @@ -91,6 +92,12 @@ "description": "How many days a snapshot the keeper took before a drop or recreate, and its record, are kept (design 47 G §681, A-112). The keeper reads it at its start from its settings file; the tool nats_snapshots reads it as its configuration.", "minimum": 1, "default": 90 + }, + "twin-current-hours": { + "type": "number", + "description": "How many hours since a module's durable's twin last delivered it is current (design 47 H2, H-A-472): nats_consumer_remove removes a module's durable with no pulls waiting only while its twin has pulls waiting and a delivery within these hours. The grants part's manifest names the same setting for its orphaned durables. The tool reads it as its configuration at each call.", + "minimum": 1, + "default": 24 } }, "streams": [ @@ -164,6 +171,7 @@ "nats_streams", "nats_backlog", "nats_consumer", + "nats_consumers", "nats_stream_messages", "nats_buckets", "nats_users", diff --git a/modules/netcheck/module.json b/modules/netcheck/module.json index bb9b92f93..ba762203c 100644 --- a/modules/netcheck/module.json +++ b/modules/netcheck/module.json @@ -1,6 +1,7 @@ { "module": "netcheck", "version": "0.1", + "class": "leaf", "emits": [ "tunnel.endpoint-changed", "tunnel.handshake-stale", diff --git a/modules/networkmanager/module.json b/modules/networkmanager/module.json index 89d4ecc40..3433f40ba 100644 --- a/modules/networkmanager/module.json +++ b/modules/networkmanager/module.json @@ -1,6 +1,7 @@ { "module": "networkmanager", "version": "0.1", + "class": "core", "upgrade": { "policy": "record", "why": "the machine's network: a build that breaks it can cut the machine off from the bus, and then neither the gate's rollback nor a push reaches it (hq ADR 0236)" diff --git a/modules/nextcloud-client/cmd/nextcloud-client-tools/manifest_test.go b/modules/nextcloud-client/cmd/nextcloud-client-tools/manifest_test.go index 08b67b72b..2a064343e 100644 --- a/modules/nextcloud-client/cmd/nextcloud-client-tools/manifest_test.go +++ b/modules/nextcloud-client/cmd/nextcloud-client-tools/manifest_test.go @@ -1,52 +1,29 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // nextcloud-client's shape (novox/hq ADR 0208, ADR 0210, ADR 0182): one official package, no seat, // the X display on its own machine, no start of its own (the client's own autostart entry is the one // start), no file of the client's, and the Go bundle serving exactly the listed nextcloud_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Contributions []any `json:"contributions"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestItInstallsTheClientAndNothingElse(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestItInstallsTheClientAndNothingElse(t *testing.T) { - m, _ := readManifest(t) if m.Module != "nextcloud-client" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) || !reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) { t.Fatalf("%+v", m) @@ -54,13 +31,22 @@ func TestItInstallsTheClientAndNothingElse(t *testing.T) { if len(m.Resources) != 1 || m.Resources[0]["type"] != "package" || m.Resources[0]["package"] != packageFor { t.Fatalf("resources: %v", m.Resources) } - if m.Claims != nil || m.Seats != nil || m.Environment != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil { t.Fatal("it holds no seat and sets no environment") } } func TestItAddsNoSecondStartAndOwnsNoneOfTheClientsFiles(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) // The client writes its own XDG autostart entry, which the session's dex runs: an xinitrc slot // or a window-manager exec would start it twice. if m.Shell != nil || m.Contributions != nil { @@ -74,7 +60,16 @@ func TestItAddsNoSecondStartAndOwnsNoneOfTheClientsFiles(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -95,8 +90,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/nextcloud-client-tools" || b["binary"] != "nextcloud-client-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/nextcloud-client-tools" || b.Binary != "nextcloud-client-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) diff --git a/modules/nextcloud-client/module.json b/modules/nextcloud-client/module.json index 9b6c1c0c5..5b603e465 100644 --- a/modules/nextcloud-client/module.json +++ b/modules/nextcloud-client/module.json @@ -1,6 +1,7 @@ { "module": "nextcloud-client", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/nextcloud/module.json b/modules/nextcloud/module.json index 4560c106a..c4efbe8a4 100644 --- a/modules/nextcloud/module.json +++ b/modules/nextcloud/module.json @@ -1,6 +1,7 @@ { "module": "nextcloud", "version": "0.1", + "class": "leaf", "slug": "ncloud", "requires": [ "postgres-database", diff --git a/modules/nfs-server/cmd/nfs-server/reconcile_test.go b/modules/nfs-server/cmd/nfs-server/reconcile_test.go index d6be1ada7..94194c704 100644 --- a/modules/nfs-server/cmd/nfs-server/reconcile_test.go +++ b/modules/nfs-server/cmd/nfs-server/reconcile_test.go @@ -21,7 +21,7 @@ func countExportfs(ran []string) int { // and the kernel still exported the refused folder while the module said it was healthy. A failed reload // is tried again on the next pass, and while the kernel exports anything of the module's that the file no // longer carries, the module is unhealthy and says what. -func TestARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs(t *testing.T) { +func testARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs(t *testing.T) { f := newFake(t) f.mountinfo("/", "/srv/pool") f.dir("/srv/pool") @@ -72,7 +72,7 @@ func TestARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs(t *test // that never happened — is reconciled: the first pass always reloads, a later pass reloads when the kernel // exports one of the module's folders to a client the file no longer has, and the module is unhealthy // while it cannot. -func TestAWithdrawnGrantIsTakenFromTheKernel(t *testing.T) { +func testAWithdrawnGrantIsTakenFromTheKernel(t *testing.T) { f := newFake(t) f.mountinfo("/", "/srv/library") f.dir("/srv/library") @@ -122,7 +122,7 @@ func TestAWithdrawnGrantIsTakenFromTheKernel(t *testing.T) { // The review of #142: SIGTERM in the middle of a pass on a plain restart (the config is still there) ends // the pass, and the exports stay: the export file is unchanged and the kernel's table keeps the share. -func TestSIGTERMDuringAPassOnARestartLeavesTheExports(t *testing.T) { +func testSIGTERMDuringAPassOnARestartLeavesTheExports(t *testing.T) { f := newFake(t) f.mountinfo("/", "/srv/library") f.dir("/srv/library") @@ -173,7 +173,7 @@ func TestSIGTERMDuringAPassOnARestartLeavesTheExports(t *testing.T) { // unassignment then stops it with the config still there. The node-engine disables a process's unit before // it stops it (`systemctl disable --now`), and a restart or a shutdown leaves it enabled, so a process // whose own unit is disabled when it is stopped is being taken away, whatever the config says. -func TestAProcessWhoseUnitIsDisabledAtStopCleansUpWithTheConfigStillThere(t *testing.T) { +func testAProcessWhoseUnitIsDisabledAtStopCleansUpWithTheConfigStillThere(t *testing.T) { f := newFake(t) f.mountinfo("/", "/srv/library") f.dir("/srv/library") @@ -199,3 +199,20 @@ func TestAProcessWhoseUnitIsDisabledAtStopCleansUpWithTheConfigStillThere(t *tes t.Errorf("the kernel still exports the library after an unassignment with the config in place: %q", f.read(Etab)) } } + +// TestARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs", testARefusalWhoseReloadFailedIsReloadedAgainAndIsUnhealthyUntilItIs}, + {"TestAWithdrawnGrantIsTakenFromTheKernel", testAWithdrawnGrantIsTakenFromTheKernel}, + {"TestSIGTERMDuringAPassOnARestartLeavesTheExports", testSIGTERMDuringAPassOnARestartLeavesTheExports}, + {"TestAProcessWhoseUnitIsDisabledAtStopCleansUpWithTheConfigStillThere", testAProcessWhoseUnitIsDisabledAtStopCleansUpWithTheConfigStillThere}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/nfs-server/module.json b/modules/nfs-server/module.json index 1bb18465f..b3f027d18 100644 --- a/modules/nfs-server/module.json +++ b/modules/nfs-server/module.json @@ -1,6 +1,7 @@ { "module": "nfs-server", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings": "0.1" }, @@ -216,7 +217,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/nftables/allowances.ts b/modules/nftables/allowances.ts new file mode 100644 index 000000000..69826a2c6 --- /dev/null +++ b/modules/nftables/allowances.ts @@ -0,0 +1,468 @@ +// The operator's allowances (ADR 0683; design 33 control-verbs): a port opened by hand on this machine, beside the +// ports derived from the modules' listens. An allowance is this module's own state on the bus, one key per protocol, +// port and interface (allow..[.]), kept one bucket per machine under its node's keys +// (.allow.…, H-A-317), so a holder reads and writes its own node's only; the node-engine asks `allowed` at every compose of a +// converged node's filter and renders it into the inet mesh table's input chain (design 08 control-verbs), so this +// code writes no rule. Every change is said as the seat's event allowances-changed, which the node-engine hears to +// compose the filter again; at its until an allowance is removed by a timer this module keeps per key from watching +// its own state, said and journalled, so no expired entry is kept or answered. + +import { isIP } from "node:net"; +import type { ConvergedAnswer } from "@novox/mesh-contracts-node-engine"; +import { + allowancesByNodeAllowProtocolPortInterfaceKey, allowancesByNodeAllowProtocolPortKey, + parseAllowancesByNodeAllowProtocolPortInterfaceKey, parseAllowancesByNodeAllowProtocolPortKey, states, + type Allowance, type AllowanceValue, type AllowancesChanged, type Kept, +} from "@novox/mesh-connectivity-contracts-node-packet-filter"; + +// The seat's names, key forms and value forms are its generated package's (design 33 control-verbs §2, §7, §12): this +// module writes no copy of them. +export type { Allowance, AllowanceValue, AllowancesChanged, Kept }; + +/** The state the allowances are kept in, as the seat's definition names it (§7). */ +export const STATE = states.allowances; + +/** The most allowances one node keeps when the setting allowances-max says none (§3, H-A-314 (5)). */ +export const MOST = 100; + +/** How long the holder waits for the node-engine's converged (§10; a value, H-A-330). */ +export const CONVERGED_BOUND_MS = 10_000; + +/** The caller of a call the runtime named no caller for (the SDK's callers.UNPROVEN). */ +export const UNPROVEN = "unproven"; + +type Protocol = AllowanceValue["protocol"]; + +/** The node's convergence state as the node-engine seat's converged answers it (§10, H-A-316, H-A-321, H-A-325). */ +export type Convergence = ConvergedAnswer; + +/** One act by hand, as the seat mesh-hand-acts' hand-act takes it (ADR 0565 §10): the SDK's views.HandAct. */ +export interface HandAct { + what: string; + why: string; + cause: string; + verb: string; +} + +/** What the holder asks beside its state: the node's convergence, the hand-act log and its setting allowances-max. */ +export interface Asks { + converged: () => Promise; + handAct: (act: HandAct) => Promise; + most: () => Promise; + /** The mesh's table as loaded (`nft list table inet mesh`). */ + meshTable: () => Promise; +} + +/** What the allowances need of the module's state: the SDK's `state()` serves it, keys from a watch of the node's own. */ +export interface Store { + get(key: string): Promise<{ value: AllowanceValue } | null>; + put(key: string, value: AllowanceValue): Promise; + delete(key: string): Promise; + keys(): Promise; +} + +/** One change of the state as its watch hands it over: the SDK's `StateChange`. */ +export interface Watched { + key: string; + op: "put" | "delete"; + value?: AllowanceValue; +} + +/** Says the event. */ +export type Say = (body: AllowancesChanged) => Promise; + +/** Runs `fire` after `ms` milliseconds, answering how to cancel it: `setTimeout` on the machine, a fake in tests. */ +export type Schedule = (ms: number, fire: () => void) => () => void; + +/** The longest one timer waits (Node's setTimeout holds 2^31-1 ms); a later until is waited for in steps. */ +export const LONGEST_WAIT_MS = 2 ** 31 - 1; + +export const timers: Schedule = (ms, fire) => { + const t = setTimeout(fire, ms); + return () => clearTimeout(t); +}; + +/** The state's key of an allowance on node, in the seat's key forms (§7, H-A-317): .allow.., and + * . when it names one. */ +function stateKeyOf(node: string, protocol: Protocol, port: number, iface?: string): string { + return iface + ? allowancesByNodeAllowProtocolPortInterfaceKey(node, protocol, String(port), iface) + : allowancesByNodeAllowProtocolPortKey(node, protocol, String(port)); +} + +/** An allowance's key in every answer, the event and the rule's comment: its state's key without the node (§7). */ +export function keyOf(protocol: Protocol, port: number, iface?: string): string { + return stateKeyOf("", protocol, port, iface).slice(1); +} + +const IFACE = /^[A-Za-z0-9_.-]{1,15}$/; + +function refuse(argument: string, why: string): never { + throw new Error(`${argument}: ${why}; nothing is written`); +} + +function only(args: Record, known: string[]): void { + for (const k of Object.keys(args)) { + if (!known.includes(k)) refuse(k, `not an argument of this verb (${known.join(", ") || "none"})`); + } +} + +function portOf(v: unknown): number { + if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 65535) { + refuse("port", `${JSON.stringify(v)} is not an integer from 1 to 65535`); + } + return v; +} + +function protocolOf(v: unknown): Protocol { + if (v === undefined) return "tcp"; + if (v === "tcp" || v === "udp") return v; + refuse("protocol", `${JSON.stringify(v)} is neither tcp (the default) nor udp`); +} + +function interfacesOf(v: unknown): (string | undefined)[] { + if (v === undefined) return [undefined]; + if (!Array.isArray(v)) refuse("interfaces", "a list of interface names"); + if (v.length === 0) return [undefined]; + for (const i of v) { + if (typeof i !== "string" || !IFACE.test(i)) { + refuse("interfaces", `${JSON.stringify(i)} is not 1 to 15 letters, digits, _ . or -`); + } + } + return [...new Set(v as string[])]; +} + +function sourceOf(v: unknown): string | undefined { + if (v === undefined) return undefined; + const s = typeof v === "string" ? v : ""; + const [addr, bits, more] = s.split("/"); + const family = isIP(addr); + const max = family === 4 ? 32 : 128; + if (family === 0 || more !== undefined || (bits !== undefined && !(/^\d+$/.test(bits) && Number(bits) <= max))) { + refuse("source", `${JSON.stringify(v)} is not one IPv4 or IPv6 CIDR`); + } + return s; +} + +function untilOf(v: unknown, now: Date): string | undefined { + if (v === undefined) return undefined; + const s = typeof v === "string" ? v : ""; + const t = Date.parse(s); + // A full RFC 3339 time, seconds included: the node-engine reads it with Go's time.RFC3339, which refuses a time + // without them, and would withhold every later compose of the filter (§2). + if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(s) || Number.isNaN(t)) { + refuse("until", `${JSON.stringify(v)} is not an RFC 3339 time with seconds, such as 2026-11-22T08:00:00Z`); + } + if (t <= now.getTime()) refuse("until", `${s} is not in the future`); + return s; +} + +function whyOf(v: unknown): string { + if (typeof v !== "string" || v.length < 1 || v.length > 500) refuse("why", "required, 1 to 500 characters"); + return v; +} + +function answered(key: string, value: AllowanceValue): Allowance { + return { key, ...value }; +} + +export class Allowances { + private readonly pending = new Map void>(); + private readonly store: Store; + private readonly node: string; + private readonly say: Say; + private readonly now: () => Date; + private readonly schedule: Schedule; + private readonly journal: (line: string) => void; + private readonly asks: Asks; + /** The last answer of converged; undefined while none answered. */ + private convergence: Convergence | undefined; + /** The expiries running now (track). */ + private readonly expiring = new Set>(); + + constructor( + store: Store, + node: string, + say: Say, + asks: Asks, + now: () => Date = () => new Date(), + schedule: Schedule = timers, + journal: (line: string) => void = (line) => console.log(`[nftables] ${line}`), + ) { + this.store = store; + this.node = node; + this.say = say; + this.asks = asks; + this.now = now; + this.schedule = schedule; + this.journal = journal; + } + + /** The state's key of an allowance's key: under this node's (H-A-317). */ + private stored(key: string): string { + return `${this.node}.${key}`; + } + + /** The allowance's key of a state's key of this node, or undefined for another node's or another form. */ + private own(stateKey: string): string | undefined { + const parts = parseAllowancesByNodeAllowProtocolPortInterfaceKey(stateKey) ?? parseAllowancesByNodeAllowProtocolPortKey(stateKey); + return parts?.node === this.node ? stateKey.slice(this.node.length + 1) : undefined; + } + + /** Ask converged, bound 10 s, keeping its answer; refused, naming why, when it does not answer (§10). */ + private async askConverged(verb: string): Promise { + let stop: () => void = () => {}; + const late = new Promise((_, no) => { + stop = this.schedule(CONVERGED_BOUND_MS, () => no(new Error(`no answer within ${CONVERGED_BOUND_MS / 1000} s`))); + }); + try { + const c = await Promise.race([this.asks.converged(), late]); + if (c?.state !== "adopted" && c?.state !== "converged") throw new Error(`it answered no convergence state (${JSON.stringify(c)})`); + this.convergence = c; + return c; + } catch (err) { + throw new Error(`${verb}: refused: the node-engine's converged did not answer (${err instanceof Error ? err.message : String(err)}), ` + + "and the holder never assumes the node converged; nothing is written"); + } finally { + stop(); + } + } + + private refuseAdopted(verb: string, c: Convergence): void { + if (c.state !== "adopted") return; + const about = [c.found ? `the found firewall ${c.found}` : "", c.since ? `since ${c.since}` : ""].filter(Boolean).join(", "); + throw new Error(`${verb}: refused: this node is adopted${about ? ` (${about})` : ""}, and the mesh speaks the found firewall's terms: ` + + "no allowance is kept on an adopted node; nothing is written"); + } + + /** The caller as the runtime proved it; an unproven one is refused (§3, H-A-315 (3)). */ + private proven(verb: string, by: string): void { + if (!by || by === UNPROVEN) throw new Error(`${verb}: refused: the request carries no caller the tool runner proved; nothing is written`); + } + + /** Every allowance kept for this node, by its key, sorted. */ + private async ownKeys(): Promise { + return (await this.store.keys()).map((k) => this.own(k)).filter((k): k is string => k !== undefined).sort(); + } + + /** Said once each time the holder starts serving the seat, with every allowance (§8): converged asked first, every + * key past its until removed first (§11). */ + async started(): Promise { + try { + await this.askConverged("start"); + } catch (err) { + this.journal(`${err instanceof Error ? err.message : String(err)}; allowed asks it again`); + } + // Every expiry the watch handed over ends before started is said (§11). + await Promise.all([...this.expiring]); + const allowances = await this.kept(); + await this.say({ node: this.node, change: "started", allowances: this.convergence?.state === "adopted" ? [] : allowances, at: this.now().toISOString() }); + } + + /** One change of the module's own state, from its watch: a key with an until gets its timer, a removed key loses it. */ + async watched(change: Watched): Promise { + const key = this.own(change.key); + if (key === undefined) return; + this.pending.get(key)?.(); + this.pending.delete(key); + if (change.op !== "put" || !change.value?.until) return; + this.arm(key, change.value.until); + } + + private arm(key: string, until: string): void { + const left = Date.parse(until) - this.now().getTime(); + if (left <= 0) { + this.track(this.expire(key, until)); + return; + } + const step = Math.min(left, LONGEST_WAIT_MS); + this.pending.set(key, this.schedule(step, () => { + this.pending.delete(key); + if (step < left) this.arm(key, until); + else this.track(this.expire(key, until)); + })); + } + + /** An expiry the watch or a timer started, kept until it ends so a start waits for it (§11). */ + private track(expiring: Promise): void { + this.expiring.add(expiring); + expiring.finally(() => this.expiring.delete(expiring)).catch(() => {}); + } + + /** Remove a key at its until, when it still holds that until (a later allow replaced it otherwise) (§4). */ + async expire(key: string, until: string): Promise { + try { + const entry = await this.store.get(this.stored(key)); + if (!entry || entry.value.until !== until || Date.parse(until) > this.now().getTime()) return false; + await this.store.delete(this.stored(key)); + const a = answered(key, entry.value); + await this.say({ node: this.node, change: "expired", allowances: [a], at: this.now().toISOString() }); + this.journal(`the allowance ${key} (${a.protocol} ${a.port}${a.interface ? ` on ${a.interface}` : ""}${a.source ? ` from ${a.source}` : ""}, ` + + `set by ${a.by} at ${a.at}: ${a.why}) expired at ${until} and is removed`); + return true; + } catch (err) { + this.journal(`the allowance ${key} expired at ${until} and could not be removed: ${err instanceof Error ? err.message : String(err)}`); + return false; + } + } + + /** Open a port (§2): one key per named interface, or the default set's one key; a key there already is replaced + * whole and answered. */ + async allow(args: Record, by: string): Promise<{ allowances: Kept[]; said: boolean }> { + this.proven("allow", by); + only(args, ["port", "protocol", "interfaces", "source", "until", "why"]); + const convergence = await this.askConverged("allow"); + this.refuseAdopted("allow", convergence); + // The outward links as the node-engine classifies them for its render, from the converged answer of this call; the + // loaded table's shape is never read to tell one from the tunnel (§4, H-A-325). + const outward = new Set(convergence.outward); + const now = this.now(); + const port = portOf(args.port); + const protocol = protocolOf(args.protocol); + const interfaces = interfacesOf(args.interfaces); + const source = sourceOf(args.source); + const until = untilOf(args.until, now); + const why = whyOf(args.why); + if (!source && privateOnly(await this.asks.meshTable(), protocol, port)) { + refuse("port", `${protocol} ${port} is admitted by a derived rule of the loaded mesh table from given sources only (its scope private-network or ` + + "local-network, such as the store's port or the broker's management port); an allowance from any source would widen it: give a source"); + } + const most = await this.asks.most(); + const kept = await this.ownKeys(); + const after = new Set([...kept, ...interfaces.map((i) => keyOf(protocol, port, i))]).size; + if (after > most) refuse("port", `${after} allowances would be kept on this node, more than allowances-max ${most}`); + const at = now.toISOString(); + const keys = interfaces.map((i) => keyOf(protocol, port, i)); + await this.recorded({ what: `allowed ${keys.join(", ")} on ${this.node}${source ? ` from ${source}` : ""}${until ? ` until ${until}` : ""}`, + why: `${why} (${by})`, cause: "allowance-set", verb: "allow" }); + const out: Kept[] = []; + for (const iface of interfaces) { + const key = keyOf(protocol, port, iface); + const value: AllowanceValue = { + port, protocol, + ...(iface ? { interface: iface } : {}), + ...(source ? { source } : {}), + ...(until ? { until } : {}), + why, by, at, + }; + const before = await this.store.get(this.stored(key)); + await this.store.put(this.stored(key), value); + out.push({ + ...answered(key, value), + ...(iface && outward.has(iface) ? { outward: iface } : {}), + ...(before ? { replaced: answered(key, before.value) } : {}), + }); + } + await this.say({ node: this.node, change: "allowed", allowances: out.map(({ replaced: _, outward: __, ...a }) => a), by, why, at }); + return { allowances: out, said: true }; + } + + /** Take back allowances (§3): every key named is deleted, or, when one does not exist, it is refused by name and + * none is deleted. */ + async disallow(args: Record, by: string): Promise<{ allowances: Allowance[]; said: boolean }> { + this.proven("disallow", by); + only(args, ["port", "protocol", "interfaces", "why"]); + this.refuseAdopted("disallow", await this.askConverged("disallow")); + const port = portOf(args.port); + const protocol = protocolOf(args.protocol); + const interfaces = interfacesOf(args.interfaces); + const why = whyOf(args.why); + const found: Allowance[] = []; + for (const iface of interfaces) { + const key = keyOf(protocol, port, iface); + const entry = await this.store.get(this.stored(key)); + if (!entry) throw new Error(`no allowance ${key} is kept on this node; nothing is deleted`); + found.push(answered(key, entry.value)); + } + await this.recorded({ what: `disallowed ${found.map((a) => a.key).join(", ")} on ${this.node}`, why: `${why} (${by})`, cause: "allowance-taken-back", verb: "disallow" }); + for (const a of found) await this.store.delete(this.stored(a.key)); + await this.say({ node: this.node, change: "disallowed", allowances: found, by, why, at: this.now().toISOString() }); + return { allowances: found, said: true }; + } + + /** Written in the hand-act log before the state is written; not written, the call is refused (§4, ADR 0565 §10). */ + private async recorded(act: HandAct): Promise { + try { + await this.asks.handAct(act); + } catch (err) { + throw new Error(`${act.verb}: the hand act was not recorded, so nothing is written: ${err instanceof Error ? err.message : String(err)}`); + } + } + + /** Every allowance kept for this node only, sorted by key (§6); none on an adopted node, and refused while converged + * has never answered and does not answer now (H-A-318). One whose until passed before its timer fired is removed, + * said and left out, so none answered has expired. */ + async allowed(args: Record = {}): Promise<{ allowances: Allowance[] }> { + only(args, []); + const c = this.convergence ?? (await this.askConverged("allowed")); + if (c.state === "adopted") return { allowances: [] }; + return { allowances: await this.kept() }; + } + + /** This node's allowances, every one past its until removed first (§11). */ + private async kept(): Promise { + const now = this.now().getTime(); + const allowances: Allowance[] = []; + for (const key of await this.ownKeys()) { + const entry = await this.store.get(this.stored(key)); + if (!entry) continue; + if (entry.value.until && Date.parse(entry.value.until) <= now) { + await this.expire(key, entry.value.until); + continue; + } + allowances.push(answered(key, entry.value)); + } + return allowances; + } +} + +/** A seat verb held until the holder's start ends (§8, §11): the watch has handed every key over, every expiry it + * started has ended and started is said, so no verb answers before started; a start that failed refuses it with + * the start's error. */ +export function held(start: Promise, run: (...args: A) => Promise): (...args: A) => Promise { + return async (...args) => { + await start; + return run(...args); + }; +} + +/** Each allowance marked loaded only when a rule of the mesh's table carries its comment `allowance ` with + * an equal at, and every such comment whose key is not kept: loaded, not kept (§7, H-A-315 (5)). */ +export function markLoaded(allowances: Allowance[], meshTable: string): { + allowances: (Allowance & { loaded: boolean })[]; + loadedNotKept: { key: string; at: string }[]; +} { + const comments = [...meshTable.matchAll(/comment "allowance (\S+) (\S+)"/g)].map((m) => ({ key: m[1], at: m[2] })); + const kept = new Set(allowances.map((a) => a.key)); + const seen = new Set(); + const loadedNotKept = comments.filter((c) => !kept.has(c.key) && !seen.has(c.key) && seen.add(c.key)); + return { + allowances: allowances.map((a) => ({ ...a, loaded: comments.some((c) => c.key === a.key && c.at === a.at) })), + loadedNotKept, + }; +} + +/** The scopes the node-engine's render writes on a derived accept rule (design 47 H2 §813 (4), H-A-357). */ +export type Scope = "any" | "private-network" | "local-network"; + +/** + * The scopes the loaded mesh table's derived accept rules give `protocol` `port`, read from each rule's one comment + * `derived / scope ` (design 47 H2 §813 (4), + * H-A-357), the module list cut with a count past 128 bytes (`derived a,b,+4 tcp/443 scope any`, H-A-384 (1)); never + * from the rule's shape. A port is one port or a range `lo-hi`. + */ +export function portScopes(meshTable: string, protocol: Protocol, port: number): Scope[] { + const out: Scope[] = []; + for (const m of meshTable.matchAll(/comment "derived \S+ (tcp|udp)\/(\d+)(?:-(\d+))? scope (any|private-network|local-network)"/g)) { + const lo = Number(m[2]), hi = m[3] === undefined ? lo : Number(m[3]); + if (m[1] === protocol && lo <= port && port <= hi) out.push(m[4] as Scope); + } + return out; +} + +/** Whether a derived rule admits `protocol` `port` from given sources only (the private network or the local network) + * and none from any source: its scope read from the rules' comments (§813 (4), H-A-315 (7), H-A-319). */ +export function privateOnly(meshTable: string, protocol: Protocol, port: number): boolean { + const scopes = portScopes(meshTable, protocol, port); + return scopes.length > 0 && !scopes.includes("any"); +} diff --git a/modules/nftables/module.json b/modules/nftables/module.json index 6c6634d86..f4b31b727 100644 --- a/modules/nftables/module.json +++ b/modules/nftables/module.json @@ -1,6 +1,7 @@ { "module": "nftables", "version": "0.1", + "class": "core", "upgrade": { "policy": "record", "why": "the machine's packet filter: a build that breaks it can cut the machine off from the bus, and then neither the gate's rollback nor a push reaches it (hq ADR 0236)" @@ -15,10 +16,28 @@ "serves": [ "rules", "reload", - "remove" + "remove", + "allow", + "disallow", + "allowed" ] } ], + "requires": [ + { + "name": "allowances", + "storage": "key-value", + "template": "state", + "options": { + "history": 1, + "per-machine": true + } + } + ], + "invokes": [ + "seat:node-engine.converged", + "seat:mesh-hand-acts.hand-act" + ], "filtering": { "into": "/etc/nftables.conf" }, @@ -71,6 +90,15 @@ "tools": [ "firewall_rules" ], + "config": { + "allowances-max": { + "type": "number", + "description": "The most allowances this machine keeps, which allow refuses past (design 33 control-verbs §3): it keeps the rendered chain readable and allowed in one answer.", + "trusted": false, + "runtime": true, + "default": 100 + } + }, "build": { "artifacts": [ { diff --git a/modules/nftables/package.json b/modules/nftables/package.json index 6342c07b6..38cc540ba 100644 --- a/modules/nftables/package.json +++ b/modules/nftables/package.json @@ -1,15 +1,17 @@ { "name": "@novox/module-nftables", "version": "0.1.0", - "description": "nftables — loads the mesh's packet filter and holds the node-packet-filter seat: its verbs rules, reload and remove (novox/hq ADR 0045, ADR 0170).", + "description": "nftables — loads the mesh's packet filter and holds the node-packet-filter seat: its verbs rules, reload, remove, allow, disallow and allowed (novox/hq ADR 0045, ADR 0170; design 47 H-A-304).", "type": "module", "private": true, "scripts": { - "build": "tsc client.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist", + "build": "tsc client.ts allowances.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist", "test": "node --test --experimental-strip-types 'test/*.test.ts'" }, "dependencies": { - "@novox/mesh-sdk": "^0.1.1" + "@novox/mesh-sdk": "^0.1.1", + "@novox/mesh-connectivity-contracts-node-packet-filter": "^0.1.0", + "@novox/mesh-contracts-node-engine": "^0.1.0" }, "devDependencies": { "@types/node": "^22.0.0", diff --git a/modules/nftables/test/allowances.test.ts b/modules/nftables/test/allowances.test.ts new file mode 100644 index 000000000..7bd8d219c --- /dev/null +++ b/modules/nftables/test/allowances.test.ts @@ -0,0 +1,357 @@ +// The operator's allowances against a state in memory (ADR 0683; design 33 control-verbs §14; design 47 H-A-315, +// H-A-317, H-A-318, H-A-319). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { + Allowances, CONVERGED_BOUND_MS, LONGEST_WAIT_MS, MOST, STATE, held, markLoaded, privateOnly, + type AllowanceValue as Value, type AllowancesChanged as Changed, type Convergence, type HandAct, type Schedule, type Store, +} from "../allowances.ts"; + +interface Timer { ms: number; fire: () => void; cancelled: boolean } + +// The loaded mesh table: the store's port from the private network only, 80 from anywhere and 8443 from both; each derived +// accept rule carries the one comment the node-engine's render writes, `derived / scope ` +// (47 H2 §813 (4), H-A-357), its module list cut with a count past 128 bytes (H-A-384 (1)). +const TABLE = 'table inet mesh {\n\tchain input {\n\t\ttype filter hook input priority filter; policy drop;\n' + + '\t\tip saddr { 10.77.0.1, 10.77.0.2 } tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"\n' + + '\t\tip6 saddr { fd77::1 } tcp dport 5432 accept comment "derived postgres tcp/5432 scope private-network"\n' + + '\t\ttcp dport 80 accept comment "derived route-proxy tcp/80 scope any"\n' + + '\t\tip saddr { 10.77.0.1 } tcp dport 8443 accept comment "derived a,b,+4 tcp/8443 scope private-network"\n' + + '\t\ttcp dport 8443 accept comment "derived c tcp/8443 scope any"\n' + + '\t\tip saddr { 192.168.1.0/24 } tcp dport 9500-9600 accept comment "derived nats tcp/9500-9600 scope local-network"\n' + + '\t\ttcp dport 7000 accept comment "derived x,+2 tcp/7000 scope private-network"\n' + + '\t\tip saddr { 10.77.0.1 } tcp dport 7100 accept\n\t}\n}\n'; + +// gate, when given, holds every delete until it opens, and every get waits a turn of the event loop: a slow store. +function fake(at = "2026-11-21T20:00:00Z", node = "shanks", kept = new Map(), gate?: Promise) { + const said: Changed[] = []; + const journal: string[] = []; + const timers: Timer[] = []; + const clock = { now: new Date(at) }; + const schedule: Schedule = (ms, fire) => { + const t = { ms, fire, cancelled: false }; + timers.push(t); + return () => { t.cancelled = true; }; + }; + const store: Store = { + get: async (k) => { + if (gate) await new Promise((r) => setImmediate(r)); + return kept.has(k) ? { value: kept.get(k)! } : null; + }, + put: async (k, v) => { kept.set(k, v); return kept.size; }, + delete: async (k) => { await gate; kept.delete(k); }, + keys: async () => [...kept.keys()], + }; + const acts: HandAct[] = []; + const asks = { + convergence: { state: "converged", since: "2026-11-01T00:00:00Z" } as Convergence | "silent", + asked: 0, + most: MOST, + table: TABLE, + }; + const a = new Allowances(store, node, async (b) => { said.push(b); }, { + converged: () => { + asks.asked++; + return asks.convergence === "silent" ? new Promise(() => {}) : Promise.resolve(asks.convergence); + }, + handAct: async (act) => { acts.push(act); }, + most: async () => asks.most, + meshTable: async () => asks.table, + }, () => clock.now, schedule, (l) => journal.push(l)); + return { a, kept, said, clock, timers, journal, acts, asks }; +} + +/** The state's key of an allowance's key on shanks (H-A-317). */ +const k = (key: string) => `shanks.${key}`; + +const settle = () => new Promise((r) => setImmediate(r)); + +test("allow keeps one key per interface, and with none the default set's key, which names no interface", async () => { + const cases: { name: string; args: Record; keys: string[] }[] = [ + { name: "defaults", args: { port: 8000, why: "the operator's dev server" }, keys: ["allow.tcp.8000"] }, + { name: "two interfaces", args: { port: 5353, protocol: "udp", interfaces: ["enp6s0", "wlan0"], source: "192.168.1.0/24", why: "w" }, + keys: ["allow.udp.5353.enp6s0", "allow.udp.5353.wlan0"] }, + { name: "an interface with a dot", args: { port: 1, interfaces: ["enp6s0.10"], why: "w" }, keys: ["allow.tcp.1.enp6s0.10"] }, + ]; + for (const c of cases) { + const { a, kept, said } = fake(); + const got = await a.allow(c.args, "lead@shanks"); + assert.deepEqual(got.allowances.map((x) => x.key), c.keys, c.name); + assert.equal(got.said, true, c.name); + assert.deepEqual([...kept.keys()].sort(), c.keys.map(k), c.name); + assert.deepEqual(said.map((b) => [b.change, b.node, b.by, b.why, b.allowances.map((x) => x.key)]), + [["allowed", "shanks", "lead@shanks", c.args.why, c.keys]], c.name); + for (const v of kept.values()) { + assert.equal(v.by, "lead@shanks", c.name); + assert.equal(v.at, "2026-11-21T20:00:00.000Z", c.name); + assert.equal(v.source, c.args.source, c.name); + if (!c.args.interfaces) assert.equal("interface" in v, false, "the private network's interface is never in the defaults"); + } + } +}); + +test("allow naming an outward link answers it as outward, as converged lists them; another interface and the default set do not (H-A-325)", async () => { + const { a, asks, said } = fake(); + asks.convergence = { state: "converged", since: "2026-11-01T00:00:00Z", tunnel: "mesh0", outward: ["eth1"] }; + const named = await a.allow({ port: 8000, interfaces: ["eth1", "enp6s0"], why: "w" }, "lead@shanks"); + assert.deepEqual(named.allowances.map((x) => [x.key, x.outward]), [["allow.tcp.8000.eth1", "eth1"], ["allow.tcp.8000.enp6s0", undefined]]); + assert.equal("outward" in named.allowances[1], false, "an interface that is no outward link answers without the field"); + const none = await a.allow({ port: 8001, why: "w" }, "lead@shanks"); + assert.equal("outward" in none.allowances[0], false, "the default set opens no outward link"); + assert.equal(said.flatMap((b) => b.allowances).some((x) => "outward" in x), false, "the event's allowances carry no outward"); +}); + +test("allow and disallow refuse what is not an allowance, writing nothing", async () => { + const bad: [string, Record, RegExp][] = [ + ["port 0", { port: 0, why: "w" }, /port: /], + ["port 65536", { port: 65536, why: "w" }, /port: /], + ["port 80a", { port: "80a", why: "w" }, /port: /], + ["protocol icmp", { port: 80, protocol: "icmp", why: "w" }, /protocol: /], + ["interface", { port: 80, interfaces: ["a b"], why: "w" }, /interfaces: /], + ["interface too long", { port: 80, interfaces: ["abcdefghijklmnop"], why: "w" }, /interfaces: /], + ["source", { port: 80, source: "10.0.0.0/33", why: "w" }, /source: /], + ["until in the past", { port: 80, until: "2026-11-21T19:00:00Z", why: "w" }, /until: .*not in the future/], + ["until not a time", { port: 80, until: "tomorrow", why: "w" }, /until: /], + ["until without seconds", { port: 80, until: "2026-11-22T08:00Z", why: "w" }, /until: .* with seconds/], + ["empty why", { port: 80, why: "" }, /why: /], + ["long why", { port: 80, why: "x".repeat(501) }, /why: /], + ["unknown argument", { port: 80, why: "w", comment: "x" }, /comment: not an argument/], + ["the store's port with no source", { port: 5432, why: "w" }, /port: tcp 5432 is admitted .* from given sources only/], + ]; + for (const [name, args, want] of bad) { + const { a, kept, said, acts } = fake(); + await assert.rejects(a.allow(args, "x"), want, name); + assert.equal(kept.size, 0, name); + assert.equal(said.length, 0, name); + assert.equal(acts.length, 0, name); + } + const { a, kept } = fake(); + await assert.rejects(a.allow({ port: 80, why: "w" }, "unproven"), /allow: refused: the request carries no caller the tool runner proved/); + await assert.rejects(a.disallow({ port: 80, why: "w" }, "unproven"), /disallow: refused: the request carries no caller/); + await a.allow({ port: 5432, source: "192.168.1.0/24", why: "the store from the home network" }, "x"); + assert.deepEqual([...kept.keys()], [k("allow.tcp.5432")]); + await assert.rejects(a.disallow({ port: 80, why: "w", source: "10.0.0.1" }, "x"), /source: not an argument/); + await assert.rejects(a.disallow({ port: 80 }, "x"), /why: /); + await assert.rejects(a.allowed({ port: 80 }), /port: not an argument/); +}); + +test("a 101st allowance is refused at the default allowances-max; a replacement at the bound is not", async () => { + const { a, kept } = fake(); + for (let p = 1; p <= MOST; p++) await a.allow({ port: p, why: "w" }, "x"); + await assert.rejects(a.allow({ port: 1000, why: "w" }, "x"), /101 allowances would be kept on this node, more than allowances-max 100/); + assert.equal(kept.size, MOST); + await a.allow({ port: 1, why: "again" }, "x"); + assert.equal(kept.get(k("allow.tcp.1"))!.why, "again"); +}); + +test("an allowance kept on one node is absent from another node's allowed, and counts not toward its bound", async () => { + const shared = new Map(); + const shanks = fake(undefined, "shanks", shared); + const ace = fake(undefined, "ace", shared); + ace.asks.most = 1; + await shanks.a.allow({ port: 8000, why: "w" }, "x"); + assert.deepEqual((await ace.a.allowed()).allowances, []); + await ace.a.allow({ port: 9000, why: "w" }, "x"); + assert.deepEqual([...shared.keys()].sort(), ["ace.allow.tcp.9000", "shanks.allow.tcp.8000"]); + assert.deepEqual((await shanks.a.allowed()).allowances.map((x) => x.key), ["allow.tcp.8000"]); + await assert.rejects(ace.a.disallow({ port: 8000, why: "w" }, "x"), /no allowance allow\.tcp\.8000 /); +}); + +test("on an adopted node allow and disallow are refused naming the adoption and allowed answers none; a silent converged refuses both", async () => { + const { a, kept, asks, timers, said } = fake(); + await a.allow({ port: 8000, why: "w" }, "x"); + asks.convergence = { state: "adopted", since: "2026-11-20T10:00:00Z", found: "ufw" }; + await assert.rejects(a.allow({ port: 9000, why: "w" }, "x"), /allow: refused: this node is adopted \(the found firewall ufw, since 2026-11-20T10:00:00Z\)/); + await assert.rejects(a.disallow({ port: 8000, why: "w" }, "x"), /disallow: refused: this node is adopted/); + assert.deepEqual((await a.allowed()).allowances, []); + assert.deepEqual([...kept.keys()], [k("allow.tcp.8000")]); + asks.convergence = "silent"; + const pending = a.allow({ port: 9000, why: "w" }, "x"); + const bound = timers.at(-1)!; + assert.equal(bound.ms, CONVERGED_BOUND_MS); + bound.fire(); + await assert.rejects(pending, /allow: refused: the node-engine's converged did not answer \(no answer within 10 s\)/); + const gone = a.disallow({ port: 8000, why: "w" }, "x"); + timers.at(-1)!.fire(); + await assert.rejects(gone, /disallow: refused: the node-engine's converged did not answer/); + assert.equal(said.length, 1); +}); + +test("allowed asks converged again while none answered, and refuses when it does not answer (H-A-318)", async () => { + const { a, asks, timers, said, journal } = fake(); + asks.convergence = "silent"; + const start = a.started(); + timers.at(-1)!.fire(); + await start; + assert.match(journal.join("\n"), /start: refused: the node-engine's converged did not answer/); + assert.equal(said.at(-1)!.change, "started"); + const asked = asks.asked; + const pending = a.allowed(); + timers.at(-1)!.fire(); + await assert.rejects(pending, /allowed: refused: the node-engine's converged did not answer/); + assert.equal(asks.asked, asked + 1); + asks.convergence = { state: "converged" }; + assert.deepEqual((await a.allowed()).allowances, []); + await a.allowed(); + assert.equal(asks.asked, asked + 2, "an answer held is not asked again"); +}); + +test("privateOnly: a port a derived rule's comment scopes to the private or the local network, none to any", () => { + assert.equal(privateOnly(TABLE, "tcp", 5432), true); + assert.equal(privateOnly(TABLE, "tcp", 9550), true, "a range, local-network"); + // 47 H2 §813 (4): the scope is read from the rule's comment, never from its shape. + assert.equal(privateOnly(TABLE, "tcp", 7000), true, "a comment cut with a count says private-network, whatever the shape"); + assert.equal(privateOnly(TABLE, "tcp", 7100), false, "a rule with a source match and no derived comment names no scope"); + assert.equal(privateOnly(TABLE, "tcp", 80), false); + assert.equal(privateOnly(TABLE, "tcp", 8443), false, "accepted from anywhere too"); + assert.equal(privateOnly(TABLE, "udp", 5432), false); + assert.equal(privateOnly(TABLE, "tcp", 8000), false, "no derived rule"); +}); + +test("allow then disallow writes the key, then deletes it, saying allowed and disallowed, with two hand-act log lines", async () => { + const { a, kept, said, acts } = fake(); + const got = await a.allow({ port: 8000, interfaces: ["enp6s0"], why: "open" }, "x"); + assert.equal(got.said, true); + assert.deepEqual((await a.allowed()).allowances.map((x) => x.key), ["allow.tcp.8000.enp6s0"]); + const gone = await a.disallow({ port: 8000, interfaces: ["enp6s0"], why: "done" }, "y"); + assert.deepEqual(gone.allowances.map((x) => x.key), ["allow.tcp.8000.enp6s0"]); + assert.equal(gone.said, true); + assert.equal(kept.size, 0); + assert.deepEqual(said.map((b) => [b.change, b.by, b.why]), [["allowed", "x", "open"], ["disallowed", "y", "done"]]); + assert.deepEqual(acts, [ + { what: "allowed allow.tcp.8000.enp6s0 on shanks", why: "open (x)", cause: "allowance-set", verb: "allow" }, + { what: "disallowed allow.tcp.8000.enp6s0 on shanks", why: "done (y)", cause: "allowance-taken-back", verb: "disallow" }, + ]); +}); + +test("disallow is all or nothing: a key not kept is refused by name and none is deleted", async () => { + const { a, kept, said } = fake(); + await a.allow({ port: 8000, interfaces: ["enp6s0"], why: "w" }, "x"); + await assert.rejects(a.disallow({ port: 8000, interfaces: ["enp6s0", "wlan0"], why: "w" }, "x"), /no allowance allow\.tcp\.8000\.wlan0/); + assert.deepEqual([...kept.keys()], [k("allow.tcp.8000.enp6s0")]); + // no interfaces names the default set's key, never one of an interface + await assert.rejects(a.disallow({ port: 8000, why: "w" }, "x"), /no allowance allow\.tcp\.8000 /); + assert.equal(said.length, 1); +}); + +test("a second allow of one key replaces it whole and answers what it replaced; the source is no part of the key", async () => { + const { a, kept } = fake(); + await a.allow({ port: 8000, source: "192.168.1.0/24", until: "2026-11-22T00:00:00Z", why: "first" }, "x"); + const got = await a.allow({ port: 8000, source: "10.0.0.5", why: "second" }, "y"); + assert.deepEqual(got.allowances.map((x) => [x.key, x.source, x.replaced?.source, x.replaced?.why]), + [["allow.tcp.8000", "10.0.0.5", "192.168.1.0/24", "first"]]); + assert.deepEqual([...kept.entries()].map(([key, v]) => [key, v.source, v.by, v.until]), [[k("allow.tcp.8000"), "10.0.0.5", "y", undefined]]); +}); + +test("at its until an allowance is deleted by its timer, says expired, is journalled, and allowed answers without it", async () => { + const { a, kept, said, clock, timers, journal } = fake(); + await a.allow({ port: 8000, until: "2026-11-21T21:00:00Z", why: "for an hour" }, "x"); + await a.allow({ port: 9000, why: "w" }, "x"); + await a.watched({ key: k("allow.tcp.8000"), op: "put", value: kept.get(k("allow.tcp.8000"))! }); + const live = timers.filter((t) => !t.cancelled); + assert.equal(live.length, 1, "one expiry timer; every converged bound is cancelled once answered"); + assert.equal(live[0].ms, 3600_000); + clock.now = new Date("2026-11-21T21:00:00Z"); + live[0].fire(); + await settle(); + assert.deepEqual([...kept.keys()], [k("allow.tcp.9000")]); + assert.deepEqual([said.at(-1)!.change, said.at(-1)!.allowances.map((x) => x.key)], ["expired", ["allow.tcp.8000"]]); + assert.match(journal.join("\n"), /the allowance allow\.tcp\.8000 .*for an hour\) expired at 2026-11-21T21:00:00Z and is removed/); + assert.deepEqual((await a.allowed()).allowances.map((x) => x.key), ["allow.tcp.9000"]); +}); + +test("the expiry timers follow the state: a delete cancels, a far until waits in steps, a stale timer removes nothing", async () => { + const { a, kept, clock, timers } = fake(); + const v: Value = { port: 1, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00Z", until: "2026-11-21T22:00:00Z" }; + await a.watched({ key: k("allow.tcp.1"), op: "put", value: v }); + await a.watched({ key: k("allow.tcp.1"), op: "delete" }); + assert.equal(timers.at(-1)!.cancelled, true); + const armed = timers.length; + await a.watched({ key: "ace.allow.tcp.1", op: "put", value: v }); + assert.equal(timers.length, armed, "another node's key arms no timer"); + await a.watched({ key: k("allow.tcp.2"), op: "put", value: { ...v, until: "2027-06-01T00:00:00Z" } }); + assert.equal(timers.at(-1)!.ms, LONGEST_WAIT_MS); + await a.allow({ port: 9000, until: "2026-11-21T21:30:00Z", why: "w" }, "x"); + await a.allow({ port: 9000, until: "2026-11-21T23:00:00Z", why: "w" }, "x"); + clock.now = new Date("2026-11-21T21:30:00Z"); + assert.equal(await a.expire("allow.tcp.9000", "2026-11-21T21:30:00Z"), false); + assert.ok(kept.has(k("allow.tcp.9000"))); + // at a start, a key already past its until is removed at once + clock.now = new Date("2026-11-22T00:00:00Z"); + await a.watched({ key: k("allow.tcp.9000"), op: "put", value: kept.get(k("allow.tcp.9000"))! }); + await settle(); + assert.ok(!kept.has(k("allow.tcp.9000"))); +}); + +test("at a start every expired allowance is removed before started is said (H-A-312 (2))", async () => { + const { a, kept, said, clock } = fake(); + await a.allow({ port: 8000, until: "2026-11-21T21:00:00Z", why: "w" }, "x"); + await a.allow({ port: 9000, why: "w" }, "x"); + clock.now = new Date("2026-11-21T22:00:00Z"); + await a.started(); + assert.deepEqual([...kept.keys()], [k("allow.tcp.9000")]); + assert.deepEqual(said.slice(-2).map((b) => [b.change, b.allowances.map((x) => x.key)]), + [["expired", ["allow.tcp.8000"]], ["started", ["allow.tcp.9000"]]]); + + // §11, §14: a key past its until that the watch hands over while the start runs, through a store whose get and delete + // wait: the start waits for that expiry, so it is removed and said once, and started after it. + let open!: () => void; + const waits = new Promise((r) => { open = r; }); + const slow = fake("2026-11-21T22:00:00Z", "shanks", new Map(), waits); + const past: Value = { port: 7000, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00Z", until: "2026-11-21T21:00:00Z" }; + slow.kept.set(k("allow.tcp.7000"), past); + await slow.a.watched({ key: k("allow.tcp.7000"), op: "put", value: past }); + const start = slow.a.started(); + for (let i = 0; i < 10; i++) await settle(); // the start runs as far as it goes while the expiry's delete waits + open(); + await start; + assert.deepEqual(slow.said.map((b) => [b.change, b.allowances.map((x) => x.key)]), + [["expired", ["allow.tcp.7000"]], ["started", []]]); +}); + +test("started is said before the first allowed: the verbs are held until the start ends, a failed start refuses them", async () => { + const { a, asks, said, timers } = fake(); + asks.convergence = "silent"; + const start = a.started(); + let answered = false; + const first = held(start, () => a.allowed())().then((r) => { answered = true; return r; }); + await settle(); + assert.equal(answered, false, "allowed answered while the start still waits on converged"); + assert.equal(said.length, 0); + asks.convergence = { state: "converged", tunnel: "mesh0", outward: [] }; + timers.find((t) => t.ms === CONVERGED_BOUND_MS && !t.cancelled)!.fire(); + await first; + assert.deepEqual(said.map((b) => b.change), ["started"], "started was said before allowed answered"); + const failed = Promise.reject(new Error("the allowances did not start: no bus")); + failed.catch(() => {}); + await assert.rejects(held(failed, () => a.allowed())(), /did not start: no bus/); +}); + +test("a start says started with every allowance", async () => { + const { a, said } = fake(); + await a.allow({ port: 8000, why: "w" }, "x"); + await a.started(); + assert.deepEqual([said.at(-1)!.change, said.at(-1)!.node, said.at(-1)!.allowances.map((x) => x.key)], ["started", "shanks", ["allow.tcp.8000"]]); +}); + +test("rules marks an allowance loaded only on a comment with an equal at, and lists a comment with no kept key as loaded, not kept", () => { + const table = 'table inet mesh {\n\tchain input {\n' + + '\t\tiifname != "mesh0" tcp dport 8000 accept comment "allowance allow.tcp.8000 2026-11-21T20:00:00.000Z"\n' + + '\t\tiifname != "mesh0" tcp dport 8001 accept comment "allowance allow.tcp.8001 2026-11-21T19:00:00.000Z"\n' + + '\t\tiifname != "mesh0" tcp dport 7000 accept comment "allowance allow.tcp.7000 2026-11-20T08:00:00.000Z"\n\t}\n}\n'; + const base: Value = { port: 8000, protocol: "tcp", why: "w", by: "x", at: "2026-11-21T20:00:00.000Z" }; + const got = markLoaded([{ key: "allow.tcp.8000", ...base }, { key: "allow.tcp.8001", ...base, port: 8001 }, { key: "allow.tcp.9000", ...base, port: 9000 }], table); + assert.deepEqual(got.allowances.map((x) => [x.key, x.loaded]), [["allow.tcp.8000", true], ["allow.tcp.8001", false], ["allow.tcp.9000", false]]); + assert.deepEqual(got.loadedNotKept, [{ key: "allow.tcp.7000", at: "2026-11-20T08:00:00.000Z" }]); +}); + +test("the manifest serves the six verbs, requires the state per machine, invokes converged and the hand-act log, and sets allowances-max", () => { + const m = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8")); + assert.deepEqual(m.claims[0].serves, ["rules", "reload", "remove", "allow", "disallow", "allowed"]); + assert.deepEqual(m.requires, [{ name: STATE, storage: "key-value", template: "state", options: { history: 1, "per-machine": true } }]); + assert.deepEqual(m.invokes, ["seat:node-engine.converged", "seat:mesh-hand-acts.hand-act"]); + assert.equal(m.emits, undefined, "the claim says the seat's event (H-A-317)"); + assert.equal(m.config["allowances-max"].default, MOST); + assert.equal(m.config["allowances-max"].runtime, true, "the holder's code reads it itself; no file places it (H-A-430 (4))"); +}); diff --git a/modules/nftables/tools/index.ts b/modules/nftables/tools/index.ts index 4f115383e..ba26ccb38 100644 --- a/modules/nftables/tools/index.ts +++ b/modules/nftables/tools/index.ts @@ -1,35 +1,102 @@ -// The packet filter's tools: the node-packet-filter seat's three verbs — what the machine enforces, -// reload the mesh's own, remove one thing the mesh did not write — and the module's own reading of -// the mesh's table (novox/hq ADR 0045, ADR 0168, ADR 0170). +// The packet filter's tools: the node-packet-filter seat's six verbs — what the machine enforces, reload the +// mesh's own, remove one thing the mesh did not write, and the operator's allowances (allow, disallow, allowed) — +// and the module's own reading of the mesh's table (novox/hq ADR 0045, ADR 0168, ADR 0170, ADR 0683; design 33 +// control-verbs). import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools"; +import { callerOf } from "@novox/mesh-sdk/callers"; +import { broker } from "@novox/mesh-sdk/messaging"; +import { config, seatPublish } from "@novox/mesh-sdk/runtime"; +import { keeps, state } from "@novox/mesh-sdk/state"; +import { + allowancesChangedSubject, seat as packetFilter, verbs, + type AllowInput, type AllowedInput, type DisallowInput, +} from "@novox/mesh-connectivity-contracts-node-packet-filter"; +import { seat as nodeEngine, verbs as nodeEngineVerbs } from "@novox/mesh-contracts-node-engine"; import { FirewallClient } from "../client.js"; +import { Allowances, MOST, STATE, held, markLoaded, type AllowanceValue, type Convergence, type Store } from "../allowances.js"; -export function getSeatVerbs(firewall: FirewallClient): ToolDefinition[] { +const port = { type: "integer", description: "the port, 1-65535" }; +const protocol = { type: "string", description: "tcp (the default) or udp" }; +const interfaces = { + type: "array", + items: { type: "string" }, + description: "the input interfaces, each 1-15 letters, digits, _ . - (optional; none: every input interface that is neither the private network's tunnel nor an outward link, so an outward link is opened only when named)", +}; +const why = { type: "string", description: "why, in words the operator reads (1-500 characters)" }; + +// The seat's verbs, held until the holder's start ends (§8, §11): started is said before any answers. The inputs' types +// name exactly the arguments of the seat's generated inputs; the holder validates every value itself. +export function getSeatVerbs(firewall: FirewallClient, allowances: Allowances, start: Promise = Promise.resolve()): ToolDefinition[] { + const allowed = held(start, () => allowances.allowed()); return [ { - name: "rules", + name: verbs.rules, description: - "The packet filter as this machine enforces it now: the nftables ruleset and, where the tool exists, the legacy filter's listings. Narrowed to one table or chain when asked.", + "The packet filter as this machine enforces it now: the nftables ruleset and, where the tool exists, the legacy filter's listings. Narrowed to one table or chain when asked. " + + "Beside it every allowance, marked loaded only when a rule of the mesh's table carries its comment allowance with an equal at, " + + "and every loaded allowance comment whose key is not kept, listed as loaded, not kept.", input: { table: { type: "string", description: "one nftables table, as `family name` (optional)" }, chain: { type: "string", description: "one chain of that table (optional)" }, }, - run: async (args) => firewall.rules(args.table ? String(args.table) : undefined, args.chain ? String(args.chain) : undefined), + run: async (args) => { + const table = args.table ? String(args.table) : undefined; + const seen = await firewall.rules(table, args.chain ? String(args.chain) : undefined); + // The mark reads the mesh's own table whole, whatever the listing was narrowed to. + const mesh = !table && !args.chain ? seen.nftables : await firewall.ruleset(); + const marked = markLoaded((await allowed()).allowances, mesh); + return { ...seen, allowances: marked.allowances, "loaded-not-kept": marked.loadedNotKept }; + }, }, { - name: "reload", + name: verbs.reload, description: "Load the mesh's own filter again from the file the mesh writes, and answer with the mesh's table as loaded.", input: {}, run: async () => firewall.reload(), }, { - name: "remove", + name: verbs.remove, description: "Remove one rule set the mesh did not write, named exactly as `node show` lists it: `chain X (iptables-legacy)` or `table ip6 filter, chain DOCKER-USER`. " + "Refuses the mesh's tables, the runtime's own chains, a built-in chain and an active found firewall's chains. An operator's act, by name, never a flush.", input: { where: { type: "string", description: "the rule set, as `node show` lists it" } }, run: async (args) => firewall.remove(String(args.where ?? "")), }, + { + name: verbs.allow, + description: + "Open a port by hand on this machine, beside the ports derived from the modules' listens: one allowance per protocol, port and interface, " + + "kept as this module's state and rendered by the node-engine into the inet mesh table's input chain at its next compose of the filter. " + + "Who set it is the caller the bus proved. A key that exists is replaced whole and answered. Written in the hand-act log. " + + "Refuses, naming the argument and writing nothing, an unproven caller, an adopted node or a converged that does not answer, a bad port, protocol, interface, source or until, " + + "an empty or longer why, an unknown argument, a port the loaded mesh table admits from given sources only unless a source is given, " + + "and more allowances on the node than the setting allowances-max (default 100). Whether the loaded chain carries it is read with rules.", + input: { + port, + protocol, + interfaces, + source: { type: "string", description: "one IPv4 or IPv6 CIDR it is opened to (optional; none: any)" }, + until: { type: "string", description: "when it expires, an RFC 3339 time with seconds in the future (optional)" }, + why, + } satisfies Record, + run: held(start, async (args: Readonly>) => allowances.allow({ ...args }, callerOf(args))), + }, + { + name: verbs.disallow, + description: + "Take back allowances: the keys the protocol, port and interfaces name (none: the default set's key) are deleted, or, when one does not exist, " + + "it is refused by name and none is deleted. Written in the hand-act log. Refuses as allow does an unproven caller, an adopted node and a converged that does not answer.", + input: { port, protocol, interfaces, why } satisfies Record, + run: held(start, async (args: Readonly>) => allowances.disallow({ ...args }, callerOf(args))), + }, + { + name: verbs.allowed, + description: + "Every allowance kept for this machine only, with its key, port, protocol, interface, source, until, why, by and at; none on an adopted node. " + + "An allowance is removed at its until, so none answered has expired.", + input: {} satisfies Record, + run: held(start, async (args: Readonly>) => allowances.allowed({ ...args })), + }, ]; } @@ -45,7 +112,61 @@ export function getFirewallTools(firewall: FirewallClient): ToolDefinition[] { } const firewall = FirewallClient.onThisMachine(); +// The allowances are this module's own state, announced as kept (ADR 0495), one bucket per machine whose keys carry +// the node, so this holder watches and lists its own node's keys only (H-A-317); every change is said as the seat's +// event allowances-changed of this node; watching its own state gives every key with an until its timer, at every +// start too; and a start asks the node-engine's converged and says started, so a node-engine that refused a compose +// for want of an answer composes again. +const node = process.env.MESH_NODE ?? ""; +const kept = state(STATE); +const own = new Set(); +// The node's keys are known once the watch handed every current value over; a start that failed refuses every listing. +let watched!: { done: () => void; failed: (err: unknown) => void }; +const watching = new Promise((done, failed) => { watched = { done, failed }; }); +watching.catch(() => {}); +const store: Store = { + get: (key) => kept.get(key), + put: (key, value) => kept.put(key, value), + delete: (key) => kept.delete(key), + keys: async () => { + await watching; + return [...own]; + }, +}; +const allowances = new Allowances(store, node, (body) => seatPublish(allowancesChangedSubject(node), body), { + converged: async () => (await broker().request(`seat:${nodeEngine}.${nodeEngineVerbs.converged}@${node}`, {})), + handAct: async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }, + most: async () => { + const v = await config("allowances-max"); + if (v === undefined || v === null || v === "") return MOST; + const n = Number(v); + if (!Number.isInteger(n) || n < 1) throw new Error(`the setting allowances-max is ${JSON.stringify(v)}, not a whole number of allowances`); + return n; + }, + meshTable: () => firewall.ruleset(), +}); +const start = (async () => { + // A node-engine package older than the verb converged names none: refused here, loudly, never asked as + // seat:node-engine.undefined (H-A-312). + if (!nodeEngineVerbs.converged) { + throw new Error("the node-engine seat's package names no verb converged (a package older than design 33 control-verbs §10)"); + } + await keeps([{ name: STATE }]); + await kept.watch(async (change) => { + if (change.op === "put") own.add(change.key); + else own.delete(change.key); + await allowances.watched(change); + }, { key: `${node}.**` }); + watched.done(); + await allowances.started(); +})().catch((err) => { + const failed = new Error(`the allowances did not start: ${err}`); + watched.failed(failed); + console.error(`[nftables] the allowances did not start (no expiry timers, no started said): ${err}`); + throw failed; +}); +start.catch(() => {}); // The seat's verbs under the seat's name: the runtime serves them on the seat's subjects where this // module holds it (ADR 0159, 0160). The module's own under its own. -registerModuleTools("node-packet-filter", () => getSeatVerbs(firewall)); +registerModuleTools(packetFilter, () => getSeatVerbs(firewall, allowances, start)); registerModuleTools("nftables", () => getFirewallTools(firewall)); diff --git a/modules/nftables/tsconfig.json b/modules/nftables/tsconfig.json index 91d5b91c5..1829ad694 100644 --- a/modules/nftables/tsconfig.json +++ b/modules/nftables/tsconfig.json @@ -10,6 +10,7 @@ }, "include": [ "client.ts", + "allowances.ts", "tools/index.ts" ] -} \ No newline at end of file +} diff --git a/modules/nm-applet/cmd/nm-applet-tools/manifest_test.go b/modules/nm-applet/cmd/nm-applet-tools/manifest_test.go index 3d301f579..467bb572d 100644 --- a/modules/nm-applet/cmd/nm-applet-tools/manifest_test.go +++ b/modules/nm-applet/cmd/nm-applet-tools/manifest_test.go @@ -1,12 +1,13 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // nm-applet's shape (novox/hq ADR 0208, ADR 0210): the applet's one official package, no seat, the X @@ -14,44 +15,17 @@ import ( // nothing of the networkmanager module's (its package, its configuration, its service), and the Go // bundle serving exactly the listed nm_applet_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Contributions []struct { - Seat string `json:"seat"` - Kind string `json:"kind"` - Content string `json:"content"` - } `json:"contributions"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestTheToolsAgreeWithTheManifest(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -72,8 +46,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/nm-applet-tools" || b["binary"] != "nm-applet-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/nm-applet-tools" || b.Binary != "nm-applet-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) @@ -85,7 +59,16 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { } func TestItInstallsTheAppletAndNothingOfNetworkManager(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) if m.Module != "nm-applet" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) || !reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) { t.Fatalf("%+v", m) @@ -93,7 +76,7 @@ func TestItInstallsTheAppletAndNothingOfNetworkManager(t *testing.T) { if len(m.Resources) != 1 || m.Resources[0]["type"] != "package" || m.Resources[0]["package"] != packageFor { t.Fatalf("resources: %v", m.Resources) } - if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { t.Fatal("no seat, no environment, and no second start") } for _, never := range []string{"\"networkmanager\"", "nm-connection-editor", "libnma", "/etc/NetworkManager", "autostart", "service"} { diff --git a/modules/nm-applet/module.json b/modules/nm-applet/module.json index 7552731c7..22f916059 100644 --- a/modules/nm-applet/module.json +++ b/modules/nm-applet/module.json @@ -1,6 +1,7 @@ { "module": "nm-applet", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/node-env/module.json b/modules/node-env/module.json index 83437459e..db48bb5f4 100644 --- a/modules/node-env/module.json +++ b/modules/node-env/module.json @@ -1,6 +1,7 @@ { "module": "node-env", "version": "0.1", + "class": "core", "moved": true, "claims": [ { diff --git a/modules/nodejs/module.json b/modules/nodejs/module.json index d34a6d884..0762ab3ac 100644 --- a/modules/nodejs/module.json +++ b/modules/nodejs/module.json @@ -1,6 +1,7 @@ { "module": "nodejs", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/nodered/module.json b/modules/nodered/module.json index a633c7c0a..672625046 100644 --- a/modules/nodered/module.json +++ b/modules/nodered/module.json @@ -1,6 +1,7 @@ { "module": "nodered", "version": "0.1", + "class": "leaf", "emits": [ "flows.deployed" ], diff --git a/modules/ollama/module.json b/modules/ollama/module.json index d22f5f721..690f62adc 100644 --- a/modules/ollama/module.json +++ b/modules/ollama/module.json @@ -1,6 +1,7 @@ { "module": "ollama", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/only-office/module.json b/modules/only-office/module.json index e54ee8b06..98f530cf5 100644 --- a/modules/only-office/module.json +++ b/modules/only-office/module.json @@ -1,6 +1,7 @@ { "module": "only-office", "version": "0.1", + "class": "core", "slug": "office", "provides": [ { diff --git a/modules/openai-consumer/module.json b/modules/openai-consumer/module.json index 1a6d7408b..20d633cfa 100644 --- a/modules/openai-consumer/module.json +++ b/modules/openai-consumer/module.json @@ -1,6 +1,7 @@ { "module": "openai-consumer", "version": "0.1", + "class": "leaf", "slug": "openai", "capabilities": [ "container-runtime" diff --git a/modules/openrazer/cmd/openrazer-tools/manifest_test.go b/modules/openrazer/cmd/openrazer-tools/manifest_test.go index 97f683557..012909034 100644 --- a/modules/openrazer/cmd/openrazer-tools/manifest_test.go +++ b/modules/openrazer/cmd/openrazer-tools/manifest_test.go @@ -1,12 +1,13 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // openrazer's shape (novox/hq ADR 0207, ADR 0208, ADR 0210): the three official packages of the @@ -14,44 +15,17 @@ import ( // its own (D-Bus activation through the package's unit is the one start), nothing of the tray's (the // polychromatic module's), and the Go bundle serving exactly the listed openrazer_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Contributions []struct { - Seat string `json:"seat"` - Kind string `json:"kind"` - Content string `json:"content"` - } `json:"contributions"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestTheToolsAgreeWithTheManifest(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -72,8 +46,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/openrazer-tools" || b["binary"] != "openrazer-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/openrazer-tools" || b.Binary != "openrazer-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) @@ -85,7 +59,16 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { } func TestItInstallsTheStackAndStartsNothing(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) if m.Module != "openrazer" || m.Requires != nil || !reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) { t.Fatalf("%+v", m) } @@ -114,7 +97,7 @@ func TestItInstallsTheStackAndStartsNothing(t *testing.T) { if len(accounts) != 1 || !reflect.DeepEqual(accounts[0], want) { t.Fatalf("the account: %v, want %v", accounts, want) } - if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil { t.Fatal("it holds no seat, sets no environment and adds no start") } // The tray is polychromatic's, from outside the official repositories; the kernel headers DKMS diff --git a/modules/openrazer/module.json b/modules/openrazer/module.json index 7337e9e17..6e30f9513 100644 --- a/modules/openrazer/module.json +++ b/modules/openrazer/module.json @@ -1,6 +1,7 @@ { "module": "openrazer", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/pacman/cmd/pacman-tools/aftercheck_test.go b/modules/pacman/cmd/pacman-tools/aftercheck_test.go index 5410f8bb6..9b4d80f3d 100644 --- a/modules/pacman/cmd/pacman-tools/aftercheck_test.go +++ b/modules/pacman/cmd/pacman-tools/aftercheck_test.go @@ -74,7 +74,7 @@ func checkUpgrades(t *testing.T, m *Machine) *Upgrades { return &Upgrades{Node: "node-a", Machine: m, Runs: runs} } -func TestTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade(t *testing.T) { +func testTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade(t *testing.T) { u := checkUpgrades(t, checkMachine("", "7.2.8-arch1-2")) c := u.AfterCheck(checkedRun(StepStarted, StepFinished), &Record{}) if strings.Join(c.Pacnew, " ") != "/etc/pacman.d/mirrorlist.pacnew" || strings.Join(c.Pacsave, " ") != "/etc/lemurs/config.toml.pacsave" { @@ -88,7 +88,7 @@ func TestTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrad } } -func TestNewsThatCannotBeReadIsSaidNotShownAsNone(t *testing.T) { +func testNewsThatCannotBeReadIsSaidNotShownAsNone(t *testing.T) { u := checkUpgrades(t, checkMachine("", "7.2.8-arch1-2")) fetch = func(string) ([]byte, error) { return nil, errors.New("no route to host") } c := u.AfterCheck(checkedRun(StepStarted, StepFinished), &Record{}) @@ -97,7 +97,7 @@ func TestNewsThatCannotBeReadIsSaidNotShownAsNone(t *testing.T) { } } -func TestAUnitNewlyFailedFailsTheCheckAndOneFailedBeforeDoesNot(t *testing.T) { +func testAUnitNewlyFailedFailsTheCheckAndOneFailedBeforeDoesNot(t *testing.T) { u := checkUpgrades(t, checkMachine("backup.service loaded failed failed The backup\nweb.service loaded failed failed The web\n", "7.2.8-arch1-2")) c := u.AfterCheck(checkedRun(StepStarted, StepFinished), &Record{FailedUnits: []string{"backup.service"}}) if strings.Join(c.NewlyFailed, " ") != "web.service" || c.Passed { @@ -105,7 +105,7 @@ func TestAUnitNewlyFailedFailsTheCheckAndOneFailedBeforeDoesNot(t *testing.T) { } } -func TestARestartIsNeededWhenTheRunningKernelIsNoLongerTheInstalledOne(t *testing.T) { +func testARestartIsNeededWhenTheRunningKernelIsNoLongerTheInstalledOne(t *testing.T) { u := checkUpgrades(t, checkMachine("", "7.2.9-arch1-1")) c := u.AfterCheck(checkedRun(StepStarted, StepFinished), &Record{}) if !c.RestartNeeded || c.InstalledKernel != "7.2.9-arch1-1" || !c.Passed { @@ -113,9 +113,27 @@ func TestARestartIsNeededWhenTheRunningKernelIsNoLongerTheInstalledOne(t *testin } } -func TestTheCheckPassesOnlyWhenTheTransactionSucceeded(t *testing.T) { +func testTheCheckPassesOnlyWhenTheTransactionSucceeded(t *testing.T) { u := checkUpgrades(t, checkMachine("", "7.2.8-arch1-2")) if c := u.AfterCheck(checkedRun(StepStarted, StepFailed), &Record{}); c.Passed { t.Errorf("%+v", c) } } + +// TestTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade", testTheCheckNamesTheFilesTheTransactionLeftAndTheNewsSinceThePreviousUpgrade}, + {"TestNewsThatCannotBeReadIsSaidNotShownAsNone", testNewsThatCannotBeReadIsSaidNotShownAsNone}, + {"TestAUnitNewlyFailedFailsTheCheckAndOneFailedBeforeDoesNot", testAUnitNewlyFailedFailsTheCheckAndOneFailedBeforeDoesNot}, + {"TestARestartIsNeededWhenTheRunningKernelIsNoLongerTheInstalledOne", testARestartIsNeededWhenTheRunningKernelIsNoLongerTheInstalledOne}, + {"TestTheCheckPassesOnlyWhenTheTransactionSucceeded", testTheCheckPassesOnlyWhenTheTransactionSucceeded}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/dkms_test.go b/modules/pacman/cmd/pacman-tools/dkms_test.go index 1c3961381..ca3124570 100644 --- a/modules/pacman/cmd/pacman-tools/dkms_test.go +++ b/modules/pacman/cmd/pacman-tools/dkms_test.go @@ -9,7 +9,7 @@ import ( "testing" ) -func TestTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs(t *testing.T) { +func testTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs(t *testing.T) { for _, c := range [][4]string{ {"7.2.8.arch1-2", "7.2.8-arch1-2", "7.3.1.arch1-1", "7.3.1-arch1-1"}, {"6.18.54-2", "6.18.54-2-lts", "6.18.60-1", "6.18.60-1-lts"}, @@ -72,7 +72,7 @@ func gateUpgrades(t *testing.T, m *Machine, linuxTo string, reachable bool) *Upg const zfsStatus = "zfs/2.4.4, 7.2.8-arch1-2, x86_64: installed\nzfs/2.4.4, 6.18.54-2-lts, x86_64: installed\n" -func TestAKernelPastAModulesLinuxMaximumIsHeldWithItsHeaders(t *testing.T) { +func testAKernelPastAModulesLinuxMaximumIsHeldWithItsHeaders(t *testing.T) { u := gateUpgrades(t, gateMachine(t, zfsStatus, capturedZFSSource(t)), "7.3.1.arch1-1", true) held, ignore, why := u.Gate() if why != "" { @@ -86,14 +86,14 @@ func TestAKernelPastAModulesLinuxMaximumIsHeldWithItsHeaders(t *testing.T) { } } -func TestAKernelWithinTheBoundIsNotHeld(t *testing.T) { +func testAKernelWithinTheBoundIsNotHeld(t *testing.T) { u := gateUpgrades(t, gateMachine(t, zfsStatus, capturedZFSSource(t)), "7.2.9.arch1-1", true) if held, ignore, why := u.Gate(); why != "" || len(held) != 0 || len(ignore) != 0 { t.Errorf("%+v %v %q", held, ignore, why) } } -func TestABuildExclusivePatternHoldsTheKernelsItDoesNotMatch(t *testing.T) { +func testABuildExclusivePatternHoldsTheKernelsItDoesNotMatch(t *testing.T) { src := map[string]string{"/usr/src/made-up-driver-1.0/dkms.conf": "PACKAGE_NAME=\"made-up-driver\"\nBUILD_EXCLUSIVE_KERNEL=\"^(6\\.|7\\.[0-2]\\.)\"\n"} u := gateUpgrades(t, gateMachine(t, "made-up-driver/1.0, 7.2.8-arch1-2, x86_64: installed\n", src), "7.3.1.arch1-1", true) held, ignore, why := u.Gate() @@ -103,7 +103,7 @@ func TestABuildExclusivePatternHoldsTheKernelsItDoesNotMatch(t *testing.T) { } } -func TestNoRunWhenWhatTheUpgradeWouldChangeIsNotKnown(t *testing.T) { +func testNoRunWhenWhatTheUpgradeWouldChangeIsNotKnown(t *testing.T) { u := gateUpgrades(t, gateMachine(t, zfsStatus, capturedZFSSource(t)), "7.3.1.arch1-1", false) if _, _, why := u.Gate(); !strings.Contains(why, "could not reach its mirrors") { t.Errorf("unreachable: %q", why) @@ -113,3 +113,21 @@ func TestNoRunWhenWhatTheUpgradeWouldChangeIsNotKnown(t *testing.T) { t.Errorf("no updates key: %q", why) } } + +// TestTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs", testTheNewKernelsReleaseIsDerivedAsTheInstalledOnesIs}, + {"TestAKernelPastAModulesLinuxMaximumIsHeldWithItsHeaders", testAKernelPastAModulesLinuxMaximumIsHeldWithItsHeaders}, + {"TestAKernelWithinTheBoundIsNotHeld", testAKernelWithinTheBoundIsNotHeld}, + {"TestABuildExclusivePatternHoldsTheKernelsItDoesNotMatch", testABuildExclusivePatternHoldsTheKernelsItDoesNotMatch}, + {"TestNoRunWhenWhatTheUpgradeWouldChangeIsNotKnown", testNoRunWhenWhatTheUpgradeWouldChangeIsNotKnown}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/keeper_manifest_test.go b/modules/pacman/cmd/pacman-tools/keeper_manifest_test.go index 658c1e7da..ffa783519 100644 --- a/modules/pacman/cmd/pacman-tools/keeper_manifest_test.go +++ b/modules/pacman/cmd/pacman-tools/keeper_manifest_test.go @@ -14,6 +14,8 @@ import ( "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // rawManifest is the manifest as written, every field kept. @@ -40,8 +42,16 @@ func strs(v any) []string { return out } -func TestTheWeeklyTimerAndItsServiceAreGone(t *testing.T) { - m := manifest(t) +func testTheWeeklyTimerAndItsServiceAreGone(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for _, r := range m.Resources { id, _ := r["id"].(string) path, _ := r["path"].(string) @@ -58,13 +68,21 @@ func TestTheWeeklyTimerAndItsServiceAreGone(t *testing.T) { } } -func TestTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn(t *testing.T) { - m := manifest(t) - user := m.resource(t, "keeper-account") +func testTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + user := resourceOf(t, m, "keeper-account") if user["type"] != "user" || user["name"] != "pacman-keeper" || user["shell"] != "/usr/bin/nologin" { t.Fatalf("the keeper's account: %v", user) } - k := m.resource(t, "keeper") + k := resourceOf(t, m, "keeper") if k["type"] != "process" || k["name"] != "pacman-keeper" || k["artifact"] != "tools" || strings.Join(strs(k["run"]), " ") != "./"+binaryName+" keeper" { t.Fatalf("the keeper: %v", k) @@ -82,7 +100,7 @@ func TestTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn(t *testing if broker["path"] != env[EnvBroker] || broker["owner"] != "pacman-keeper" || len(secrets) != 1 { t.Errorf("the bus account is the keeper's own secret, owned by its account: %v", secrets) } - state := m.resource(t, "state") + state := resourceOf(t, m, "state") if state["type"] != "directory" || state["place"] != "mesh" || state["unknown"] == nil { t.Errorf("the state directory: %v", state) } @@ -95,9 +113,18 @@ func TestTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn(t *testing } } -func TestTheKeeperDeclaresTheModulesStatesAndEvents(t *testing.T) { +func testTheKeeperDeclaresTheModulesStatesAndEvents(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } raw := rawManifest(t) - k := manifest(t).resource(t, "keeper") + k := resourceOf(t, m, "keeper") bus, _ := k["bus"].(map[string]any) var events []string for _, e := range Events { @@ -120,9 +147,9 @@ func TestTheKeeperDeclaresTheModulesStatesAndEvents(t *testing.T) { t.Errorf("the keeper reads its asks' answers and the module uses the operator's channel: %v %v", bus["asks"], raw["uses"]) } // The tools read round-start-minutes from the keeper's config file. - for _, a := range manifest(t).Build.Artifacts { - if env, _ := a["env"].(map[string]any); a["name"] == "tools" && env[EnvConfig] != "${dir:state}/keeper.json" { - t.Errorf("the tools bundle is not named the keeper's config file: %v", a["env"]) + for _, a := range m.Build.Artifacts { + if a.Name == "tools" && a.Env[EnvConfig] != "${dir:state}/keeper.json" { + t.Errorf("the tools bundle is not named the keeper's config file: %v", a.Env) } } if got := strs(raw["state"]); !reflect.DeepEqual(got, States) { @@ -152,7 +179,7 @@ func configValue(t *testing.T, key string) map[string]any { return v } -func TestTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt(t *testing.T) { +func testTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt(t *testing.T) { order := configValue(t, "upgrade-order") if order["type"] != "list" || order["trusted"] != true || order["predefined"] != "upgrade-order" || !reflect.DeepEqual(order["default"], []any{}) || order["required"] != nil { @@ -168,15 +195,23 @@ func TestTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt(t *testing.T) if len(config) != 3 { t.Errorf("config: %v", config) } - m := manifest(t) - f := m.resource(t, "keeper-config") + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + f := resourceOf(t, m, "keeper-config") if f["type"] != "file" || f["path"] != "${dir:state}/keeper.json" || f["merge"] != "json" || f["trusted"] != true || f["mode"] != "0644" { t.Fatalf("the keeper's config file: %v", f) } - if got := strs(f["takes-config"]); strings.Join(got, " ") != "upgrade-order record-days round-start-minutes" { + if got := strs(f[catalogue.TakesSettingsField]); strings.Join(got, " ") != "upgrade-order record-days round-start-minutes" { t.Errorf("the file takes every config value: %v", got) } - if got := strs(m.resource(t, "keeper")["restart-on"]); strings.Join(got, " ") != "keeper-config" { + if got := strs(resourceOf(t, m, "keeper")["restart-on"]); strings.Join(got, " ") != "keeper-config" { t.Errorf("a changed config file restarts the keeper, which reads it at its start: %v", got) } // The template is the file a node starts with: the defaults, read as the keeper reads them. @@ -191,7 +226,7 @@ func TestTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt(t *testing.T) } } -func TestUpgradeOrderIsATrustedListOfTheMesh(t *testing.T) { +func testUpgradeOrderIsATrustedListOfTheMesh(t *testing.T) { raw, err := os.ReadFile(filepath.Join(moduleDir, "..", "..", "predefined.json")) if err != nil { t.Fatal(err) @@ -216,7 +251,7 @@ func TestUpgradeOrderIsATrustedListOfTheMesh(t *testing.T) { // never place "." or a placement by default: for this module both resolve under /var/lib/pacman, the package manager's // own database directory (issue 1841: the node-engine used it as found and reported it unhealthy, and wrote keeper.json // into it). What the keeper and its root helper keep there is still named through ${dir:state}. -func TestTheStateDirectoryIsOutsideThePackageManagersOwn(t *testing.T) { +func testTheStateDirectoryIsOutsideThePackageManagersOwn(t *testing.T) { m := rawManifest(t) resources, _ := m["resources"].([]any) var state map[string]any @@ -245,3 +280,22 @@ func TestTheStateDirectoryIsOutsideThePackageManagersOwn(t *testing.T) { } } } + +// TestTheWeeklyTimerAndItsServiceAreGone runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestTheWeeklyTimerAndItsServiceAreGone(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestTheWeeklyTimerAndItsServiceAreGone", testTheWeeklyTimerAndItsServiceAreGone}, + {"TestTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn", testTheKeeperIsAProcessUnderItsOwnAccountWithABusAccountOfItsOwn}, + {"TestTheKeeperDeclaresTheModulesStatesAndEvents", testTheKeeperDeclaresTheModulesStatesAndEvents}, + {"TestTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt", testTheConfigValuesLandInTheKeepersConfigFileWhichRestartsIt}, + {"TestUpgradeOrderIsATrustedListOfTheMesh", testUpgradeOrderIsATrustedListOfTheMesh}, + {"TestTheStateDirectoryIsOutsideThePackageManagersOwn", testTheStateDirectoryIsOutsideThePackageManagersOwn}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/keeper_test.go b/modules/pacman/cmd/pacman-tools/keeper_test.go index 21ddf0946..beb9826d2 100644 --- a/modules/pacman/cmd/pacman-tools/keeper_test.go +++ b/modules/pacman/cmd/pacman-tools/keeper_test.go @@ -342,7 +342,7 @@ func installedOf(t *testing.T, s *fakeStore, key string) InstalledValue { // 1840/AC1: at the start every package is written with its version, its reason and its repository or foreign, // and written again only when it differs from the key. -func TestAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey(t *testing.T) { +func testAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} db.set("glibc 2.42-1\nlinux 6.17.1-1\nyay 12.0-1\nzsh 5.9-1\n", "linux\nyay\nzsh\n") k, states, ev, _, _ := newTestKeeper(db) @@ -375,7 +375,7 @@ func TestAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey(t *tes // 1840/AC2: a transaction that adds, removes and changes packages is one package.changed naming the node and // exactly those; one that changes nothing writes and emits nothing; a lock held again waits for its release. -func TestAReleasedLockSaysExactlyWhatTheTransactionChangedOnce(t *testing.T) { +func testAReleasedLockSaysExactlyWhatTheTransactionChangedOnce(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} db.set("glibc 2.42-1\nlinux 6.17.1-1\nzsh 5.9-1\n", "linux\nzsh\n") k, states, ev, clock, _ := newTestKeeper(db) @@ -440,7 +440,7 @@ func bigDB(n int) string { // 1840/AC3: a value over the bus's cap is not written: the key keeps its last value and `.not-current` // holds the size and since when, written once; the next write that fits deletes it. -func TestAValueOverTheCapKeepsTheLastAndMarksTheNodeNotCurrent(t *testing.T) { +func testAValueOverTheCapKeepsTheLastAndMarksTheNodeNotCurrent(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} db.set("glibc 2.42-1\n", "") k, states, ev, clock, _ := newTestKeeper(db) @@ -483,7 +483,7 @@ func TestAValueOverTheCapKeepsTheLastAndMarksTheNodeNotCurrent(t *testing.T) { } // The mark goes too when the node's packages come back to what the key holds: the key is current again. -func TestTheMarkGoesWhenThePackagesComeBackToTheKey(t *testing.T) { +func testTheMarkGoesWhenThePackagesComeBackToTheKey(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} db.set("glibc 2.42-1\n", "") k, states, _, _, _ := newTestKeeper(db) @@ -501,7 +501,7 @@ func TestTheMarkGoesWhenThePackagesComeBackToTheKey(t *testing.T) { // The loop: a released lock is read, a hook runs after it with what it changed, a watched state's change reaches // its hook, and a wake comes at the time it asked. -func TestTheLoopRunsTheHooksOnItsOneGoroutine(t *testing.T) { +func testTheLoopRunsTheHooksOnItsOneGoroutine(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} db.set("glibc 2.42-1\n", "") k, states, _, clock, w := newTestKeeper(db) @@ -567,7 +567,7 @@ func waitFor(t *testing.T, mu *sync.Mutex, seen *[]string, want string) { } // The watch ending ends the keeper, loudly. -func TestTheKeeperStopsWhenTheWatchEnds(t *testing.T) { +func testTheKeeperStopsWhenTheWatchEnds(t *testing.T) { db := &pacmanDB{sl: syncDBs, checkup: Ran{Status: 2}} k, _, _, _, w := newTestKeeper(db) close(w.c) @@ -578,7 +578,7 @@ func TestTheKeeperStopsWhenTheWatchEnds(t *testing.T) { // The machine's watch: the lock deleted and the mirror list written or moved in are each a signal; anything else // in those directories is none. -func TestTheWatchSeesTheLockReleasedAndTheMirrorListRewritten(t *testing.T) { +func testTheWatchSeesTheLockReleasedAndTheMirrorListRewritten(t *testing.T) { lockDir, mirrorDir := t.TempDir(), t.TempDir() w, err := WatchMachine(lockDir, LockName, mirrorDir, MirrorName) if err != nil { @@ -628,3 +628,23 @@ func TestTheWatchSeesTheLockReleasedAndTheMirrorListRewritten(t *testing.T) { } } } + +// TestAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey", testAtItsStartTheKeeperWritesEveryPackageOnlyWhenItDiffersFromTheKey}, + {"TestAReleasedLockSaysExactlyWhatTheTransactionChangedOnce", testAReleasedLockSaysExactlyWhatTheTransactionChangedOnce}, + {"TestAValueOverTheCapKeepsTheLastAndMarksTheNodeNotCurrent", testAValueOverTheCapKeepsTheLastAndMarksTheNodeNotCurrent}, + {"TestTheMarkGoesWhenThePackagesComeBackToTheKey", testTheMarkGoesWhenThePackagesComeBackToTheKey}, + {"TestTheLoopRunsTheHooksOnItsOneGoroutine", testTheLoopRunsTheHooksOnItsOneGoroutine}, + {"TestTheKeeperStopsWhenTheWatchEnds", testTheKeeperStopsWhenTheWatchEnds}, + {"TestTheWatchSeesTheLockReleasedAndTheMirrorListRewritten", testTheWatchSeesTheLockReleasedAndTheMirrorListRewritten}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/manifest_test.go b/modules/pacman/cmd/pacman-tools/manifest_test.go index 45cd3f68e..17d667db3 100644 --- a/modules/pacman/cmd/pacman-tools/manifest_test.go +++ b/modules/pacman/cmd/pacman-tools/manifest_test.go @@ -12,30 +12,49 @@ import ( "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -func TestItHoldsThePackageManagerSeatAndDeclaresItsPackage(t *testing.T) { - m := manifest(t) - if len(m.Claims) != 1 || m.Claims[0]["name"] != "node-package-manager" || m.Claims[0]["scope"] != "node" || m.Claims[0]["serves"] != nil { +func testItHoldsThePackageManagerSeatAndDeclaresItsPackage(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if len(m.Claims) != 1 || m.Claims[0].Name != "node-package-manager" || m.Claims[0].Scope != "node" || m.Claims[0].Serves != nil { t.Fatalf("claims: %v", m.Claims) } for id, pkg := range map[string]string{"package": "pacman", "contrib": "pacman-contrib", "reflector": "reflector"} { - if r := m.resource(t, id); r["package"] != pkg || r["absent"] != nil { + if r := resourceOf(t, m, id); r["package"] != pkg || r["absent"] != nil { t.Errorf("%s: %v", id, r) } } // ADR 0585 §3: reflector's weekly timer is declared stopped and disabled, the mesh's list ranked in the round instead. for id, unit := range map[string][3]string{"mirror-refresh": {"reflector.timer", "stopped", "disabled"}, "cache-cleaning": {"paccache.timer", "running", "enabled"}} { - r := m.resource(t, id) + r := resourceOf(t, m, id) if r["unit"] != unit[0] || r["state"] != unit[1] || r["boot"] != unit[2] { t.Errorf("%s: %v", id, r) } } } -func TestPacmanConfIsWholeTheUnionOfRepositoriesAndTheImprovedOptions(t *testing.T) { - f := manifest(t).resource(t, "config") +func testPacmanConfIsWholeTheUnionOfRepositoriesAndTheImprovedOptions(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + f := resourceOf(t, m, "config") content := templateText(t, f) if f["path"] != "/etc/pacman.conf" || f["into"] != nil || !strings.HasPrefix(content, MeshHeader) { t.Fatalf("%v", f) @@ -79,8 +98,17 @@ func TestPacmanConfIsWholeTheUnionOfRepositoriesAndTheImprovedOptions(t *testing // Every repository of the shipped file reads the mirror list reflector writes, and the file pacman-conf proves reads // nothing of the machine: the unit level runs shut off (novox/hq ADR 0448), where /etc/pacman.d is not there // (issue 1891). -func TestTheProvenConfReadsNothingOfTheMachine(t *testing.T) { - content := templateText(t, manifest(t).resource(t, "config")) +func testTheProvenConfReadsNothingOfTheMachine(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + content := templateText(t, resourceOf(t, m, "config")) if n := strings.Count(content, "Include = "+Mirrorlist+"\n"); n != 3 || strings.Count(content, "Include") != n { t.Fatalf("every repository reads %s, and nothing else is included: %d of 3\n%s", Mirrorlist, n, content) } @@ -105,8 +133,17 @@ func provenConf(t *testing.T, content, dir string) string { return strings.ReplaceAll(content, "Include = "+Mirrorlist, "Include = "+list) } -func TestReflectorRanksWithTheModulesOptionsAndSavesNoList(t *testing.T) { - content := templateText(t, manifest(t).resource(t, "mirrors")) +func testReflectorRanksWithTheModulesOptionsAndSavesNoList(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + content := templateText(t, resourceOf(t, m, "mirrors")) opts := map[string]string{} for _, l := range strings.Split(content, "\n") { if l == "" || strings.HasPrefix(l, "#") { @@ -119,14 +156,23 @@ func TestReflectorRanksWithTheModulesOptionsAndSavesNoList(t *testing.T) { if _, saves := opts["--save"]; saves || opts["--protocol"] != "https" || opts["--latest"] != "20" || opts["--sort"] != "rate" || opts["--country"] == "" { t.Fatalf("%v", opts) } - if manifest(t).resource(t, "mirrors")["path"] != ReflectorConf { + if resourceOf(t, m, "mirrors")["path"] != ReflectorConf { t.Fatal("reflector reads its options from " + ReflectorConf) } } -func TestTheReflectorPackageIsDeclaredBeforeTheFileItShips(t *testing.T) { +func testTheReflectorPackageIsDeclaredBeforeTheFileItShips(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } order := map[string]int{} - for i, r := range manifest(t).Resources { + for i, r := range m.Resources { order[r["id"].(string)] = i } if order["reflector"] > order["mirrors"] || order["contrib"] > order["cache-cleaning"] || order["reflector"] > order["mirror-refresh"] { @@ -136,12 +182,41 @@ func TestTheReflectorPackageIsDeclaredBeforeTheFileItShips(t *testing.T) { // TestThePackageManagersConfigIsDeclaredBeforeItsPackage holds design 42 zfs-owns-zfs §1 and A-26: the // apply stops at the first failure, and the package fails while its config file is missing. -func TestThePackageManagersConfigIsDeclaredBeforeItsPackage(t *testing.T) { +func testThePackageManagersConfigIsDeclaredBeforeItsPackage(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } order := map[string]int{} - for i, r := range manifest(t).Resources { + for i, r := range m.Resources { order[r["id"].(string)] = i } if order["config"] >= order["package"] { t.Fatalf("the config file comes before the package: %v", order) } } + +// TestItHoldsThePackageManagerSeatAndDeclaresItsPackage runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it; the case that +// skips where pacman-conf is not installed runs last, so its skip ends no other case. +func TestItHoldsThePackageManagerSeatAndDeclaresItsPackage(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestItHoldsThePackageManagerSeatAndDeclaresItsPackage", testItHoldsThePackageManagerSeatAndDeclaresItsPackage}, + {"TestTheProvenConfReadsNothingOfTheMachine", testTheProvenConfReadsNothingOfTheMachine}, + {"TestReflectorRanksWithTheModulesOptionsAndSavesNoList", testReflectorRanksWithTheModulesOptionsAndSavesNoList}, + {"TestTheReflectorPackageIsDeclaredBeforeTheFileItShips", testTheReflectorPackageIsDeclaredBeforeTheFileItShips}, + {"TestThePackageManagersConfigIsDeclaredBeforeItsPackage", testThePackageManagersConfigIsDeclaredBeforeItsPackage}, + {"TestPacmanConfIsWholeTheUnionOfRepositoriesAndTheImprovedOptions", testPacmanConfIsWholeTheUnionOfRepositoriesAndTheImprovedOptions}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/pacman_test.go b/modules/pacman/cmd/pacman-tools/pacman_test.go index f980d2b5e..a93360bca 100644 --- a/modules/pacman/cmd/pacman-tools/pacman_test.go +++ b/modules/pacman/cmd/pacman-tools/pacman_test.go @@ -16,7 +16,7 @@ core/base-devel 1-2 (base-devel) Basic tools to build Arch Linux packages ` -func TestSearchReadsHeaderAndDescriptionAndWhatIsInstalled(t *testing.T) { +func testSearchReadsHeaderAndDescriptionAndWhatIsInstalled(t *testing.T) { f := ParseSearch(searchOut) if len(f) != 3 { t.Fatalf("%+v", f) @@ -32,7 +32,7 @@ func TestSearchReadsHeaderAndDescriptionAndWhatIsInstalled(t *testing.T) { } } -func TestASearchThatFindsNothingIsEmptyAndAFailureIsAnError(t *testing.T) { +func testASearchThatFindsNothingIsEmptyAndAFailureIsAnError(t *testing.T) { m := machine(fake(func(c call) Ran { return Ran{Status: 1} }, nil), 1000) r, err := m.Search("nothing", 50) if err != nil || r["count"] != 0 { @@ -54,7 +54,7 @@ Install Reason : Explicitly installed ` -func TestInfoReadsListsAsListsAndFallsBackToTheRepositories(t *testing.T) { +func testInfoReadsListsAsListsAndFallsBackToTheRepositories(t *testing.T) { p := ParseInfo(infoOut) if len(p) != 1 { t.Fatalf("%v", p) @@ -79,7 +79,7 @@ func TestInfoReadsListsAsListsAndFallsBackToTheRepositories(t *testing.T) { } } -func TestReadInstalledSaysWhyAndWhichRepositoryOrForeign(t *testing.T) { +func testReadInstalledSaysWhyAndWhichRepositoryOrForeign(t *testing.T) { m := machine(byLine(map[string]Ran{ "pacman -Q": {Stdout: "zsh 5.9-1\nglibc 2.42-1\nyay 12.0-1\n"}, "pacman -Qeq": {Stdout: "yay\nzsh\n"}, @@ -95,7 +95,7 @@ func TestReadInstalledSaysWhyAndWhichRepositoryOrForeign(t *testing.T) { } } -func TestOwnsAnswersNoOwnerAsAnAnswer(t *testing.T) { +func testOwnsAnswersNoOwnerAsAnAnswer(t *testing.T) { m := machine(byLine(map[string]Ran{ "pacman -Qo -- /usr/bin/zsh": {Stdout: "/usr/bin/zsh is owned by zsh 5.9.2-1\n"}, "pacman -Qo -- /etc/hostname": {Status: 1, Stderr: "error: No package owns /etc/hostname\n"}, @@ -115,7 +115,7 @@ func TestOwnsAnswersNoOwnerAsAnAnswer(t *testing.T) { } } -func TestUpdateListReadsCheckupdatesAndItsNothingToDo(t *testing.T) { +func testUpdateListReadsCheckupdatesAndItsNothingToDo(t *testing.T) { m := machine(byLine(map[string]Ran{"checkupdates": {Stdout: "zsh 5.9-1 -> 5.9-2\nlinux 6.1-1 -> 6.2-1\n"}}, nil), 1000) r, err := m.UpdateList() if err != nil || len(r) != 2 || r[0] != (VersionChange{"linux", "6.1-1", "6.2-1"}) { @@ -136,7 +136,7 @@ func lockless(m *Machine) *Machine { return m } -func TestAnUpgradesUnitIsReadBack(t *testing.T) { +func testAnUpgradesUnitIsReadBack(t *testing.T) { unit := "mesh-pacman-upgrade-1791115200" m := machine(byLine(map[string]Ran{ "systemctl show " + unit + " --no-pager --property=LoadState --property=ActiveState --property=SubState --property=Result --property=ExecMainStatus": {Stdout: "LoadState=loaded\nActiveState=failed\nSubState=failed\nResult=exit-code\nExecMainStatus=1\n"}, @@ -165,7 +165,7 @@ func orphanMachine(calls *[]call) *Machine { }, calls), 1000)) } -func TestRemovingOrphansTakesOnlyOrphansNamedOrAll(t *testing.T) { +func testRemovingOrphansTakesOnlyOrphansNamedOrAll(t *testing.T) { var calls []call m := orphanMachine(&calls) if _, err := m.RemoveOrphans(nil, false); err == nil || !strings.Contains(err.Error(), "name the orphans") { @@ -193,7 +193,7 @@ func TestRemovingOrphansTakesOnlyOrphansNamedOrAll(t *testing.T) { } } -func TestCacheSaysWhatCleaningWouldFreeAndCleansThroughSudo(t *testing.T) { +func testCacheSaysWhatCleaningWouldFreeAndCleansThroughSudo(t *testing.T) { var calls []call m := machine(fake(func(c call) Ran { switch c.String() { @@ -227,7 +227,7 @@ const pacmanLog = `[2026-09-24T17:47:36+0200] [PACMAN] starting full system upgr [2022-01-01 10:00] [ALPM] installed old (1-1) ` -func TestHistoryReadsTheLogSinceADayAndTheLastFullUpgrade(t *testing.T) { +func testHistoryReadsTheLogSinceADayAndTheLastFullUpgrade(t *testing.T) { m := machine(nil, 1000) m.ReadFile = func(p string) ([]byte, error) { return []byte(pacmanLog), nil } r, err := m.History("2026-09-01", "", "", 10) @@ -263,7 +263,7 @@ const feed = ` Old newshttps://example.org/news/b/oldMon, 01 Jun 2026 09:00:00 +0000 ` -func TestNewsSinceTheLastUpgrade(t *testing.T) { +func testNewsSinceTheLastUpgrade(t *testing.T) { items, err := ParseNews([]byte(feed), time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)) if err != nil || len(items) != 1 || items[0].Title != "Manual intervention needed" || items[0].Summary != "Do this first ." { t.Fatalf("%+v %v", items, err) @@ -314,7 +314,7 @@ var rankedAt = time.Date(2026, 11, 1, 15, 0, 0, 0, time.UTC) // and never its --save; a ranking that fails or keeps none is no list. pacman_mirrors answers the shared list, its // ranker and age and whether this node's file matches it (the file as found when not); with refresh it asks this node's // keeper to rank again, refused while a round runs, naming it. -func TestTheMeshsMirrorListIsRankedFreshAndAnsweredWithThisNodesFile(t *testing.T) { +func testTheMeshsMirrorListIsRankedFreshAndAnsweredWithThisNodesFile(t *testing.T) { conf := "# comment\n--save /etc/pacman.d/mirrorlist\n--country Belgium,Netherlands\n--sort rate\n" if o := strings.Join(ReflectorOptions(conf), " "); o != "--country Belgium,Netherlands --sort rate" { t.Errorf("the options are %q", o) @@ -381,7 +381,7 @@ func TestTheMeshsMirrorListIsRankedFreshAndAnsweredWithThisNodesFile(t *testing. } } -func TestConfigIsReadAsPacmanConfResolvesIt(t *testing.T) { +func testConfigIsReadAsPacmanConfResolvesIt(t *testing.T) { c := ParseConf("[options]\nHoldPkg = pacman\nHoldPkg = glibc\nCheckSpace\nParallelDownloads = 5\n[core]\nUsage = All\nServer = https://a/core\nServer = https://b/core\n[extra]\nServer = https://a/extra\n") if len(c.Options["HoldPkg"]) != 2 || c.Options["ParallelDownloads"][0] != "5" || len(c.Repositories) != 2 || c.Repositories[0].Servers != 2 || c.Repositories[0].FirstServer != "https://a/core" { t.Fatalf("%+v", c) @@ -430,3 +430,29 @@ func checkFreshest(t *testing.T) { t.Errorf("unknown syncs not detected: %+v", r) } } + +// TestSearchReadsHeaderAndDescriptionAndWhatIsInstalled runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestSearchReadsHeaderAndDescriptionAndWhatIsInstalled(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestSearchReadsHeaderAndDescriptionAndWhatIsInstalled", testSearchReadsHeaderAndDescriptionAndWhatIsInstalled}, + {"TestASearchThatFindsNothingIsEmptyAndAFailureIsAnError", testASearchThatFindsNothingIsEmptyAndAFailureIsAnError}, + {"TestInfoReadsListsAsListsAndFallsBackToTheRepositories", testInfoReadsListsAsListsAndFallsBackToTheRepositories}, + {"TestReadInstalledSaysWhyAndWhichRepositoryOrForeign", testReadInstalledSaysWhyAndWhichRepositoryOrForeign}, + {"TestOwnsAnswersNoOwnerAsAnAnswer", testOwnsAnswersNoOwnerAsAnAnswer}, + {"TestUpdateListReadsCheckupdatesAndItsNothingToDo", testUpdateListReadsCheckupdatesAndItsNothingToDo}, + {"TestAnUpgradesUnitIsReadBack", testAnUpgradesUnitIsReadBack}, + {"TestRemovingOrphansTakesOnlyOrphansNamedOrAll", testRemovingOrphansTakesOnlyOrphansNamedOrAll}, + {"TestCacheSaysWhatCleaningWouldFreeAndCleansThroughSudo", testCacheSaysWhatCleaningWouldFreeAndCleansThroughSudo}, + {"TestHistoryReadsTheLogSinceADayAndTheLastFullUpgrade", testHistoryReadsTheLogSinceADayAndTheLastFullUpgrade}, + {"TestNewsSinceTheLastUpgrade", testNewsSinceTheLastUpgrade}, + {"TestTheMeshsMirrorListIsRankedFreshAndAnsweredWithThisNodesFile", testTheMeshsMirrorListIsRankedFreshAndAnsweredWithThisNodesFile}, + {"TestConfigIsReadAsPacmanConfResolvesIt", testConfigIsReadAsPacmanConfResolvesIt}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/rollback_test.go b/modules/pacman/cmd/pacman-tools/rollback_test.go index ff7ac532d..54bdf82fd 100644 --- a/modules/pacman/cmd/pacman-tools/rollback_test.go +++ b/modules/pacman/cmd/pacman-tools/rollback_test.go @@ -45,7 +45,7 @@ func rollbackStates(t *testing.T) (*fakeStates, *Machine, *[]call) { return states, m, &calls } -func TestThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign(t *testing.T) { +func testThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign(t *testing.T) { _, m, calls := rollbackStates(t) p, err := PlanRollback(m, m.States(StateInstalled), m.States(StateRecords), "node-a", rollbackRecord.Run, false, true) if err != nil { @@ -79,7 +79,7 @@ func TestThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign(t } } -func TestAnotherNodesPlanReadsNoCacheAndTakesUnknownArchitecturesFromTheDatedRepository(t *testing.T) { +func testAnotherNodesPlanReadsNoCacheAndTakesUnknownArchitecturesFromTheDatedRepository(t *testing.T) { _, m, calls := rollbackStates(t) m.Node = "node-b" r, err := m.Rollback("node-a", rollbackRecord.Run, false, false) @@ -97,7 +97,7 @@ func TestAnotherNodesPlanReadsNoCacheAndTakesUnknownArchitecturesFromTheDatedRep } } -func TestNoPlanFromPackagesNotCurrentOrWithoutARecord(t *testing.T) { +func testNoPlanFromPackagesNotCurrentOrWithoutARecord(t *testing.T) { states, m, _ := rollbackStates(t) if _, err := m.Rollback("node-a", "20250101T000000Z", false, false); err == nil || !strings.Contains(err.Error(), "no record") { t.Errorf("no record: %v", err) @@ -108,7 +108,7 @@ func TestNoPlanFromPackagesNotCurrentOrWithoutARecord(t *testing.T) { } } -func TestApplyWritesAnAskForTheNodesKeeper(t *testing.T) { +func testApplyWritesAnAskForTheNodesKeeper(t *testing.T) { _, m, _ := rollbackStates(t) asks := newBucket() saved := upgradeState @@ -125,7 +125,7 @@ func TestApplyWritesAnAskForTheNodesKeeper(t *testing.T) { } } -func TestAnAskedRollbackIsOneTransactionWithItsEventsAndTheCheck(t *testing.T) { +func testAnAskedRollbackIsOneTransactionWithItsEventsAndTheCheck(t *testing.T) { k := newKeeperBed(t) k.records.Put(NodeKey("node-a", rollbackRecord.Run), rollbackRecord) k.installed.Put("node-a", rollbackNow) @@ -193,3 +193,21 @@ func (k *keeperBed) takeAsk(t *testing.T, a Ask) error { raw, _ := json.Marshal(a) return k.u.TakeAsk(stdio.StateChange{State: StateAsks, Key: key, Op: "put", Value: raw, Revision: rev}) } + +// TestThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign", testThePlanSaysEachPackageNowToTheRecordWithItsSourceTheAddedAndNoForeign}, + {"TestAnotherNodesPlanReadsNoCacheAndTakesUnknownArchitecturesFromTheDatedRepository", testAnotherNodesPlanReadsNoCacheAndTakesUnknownArchitecturesFromTheDatedRepository}, + {"TestNoPlanFromPackagesNotCurrentOrWithoutARecord", testNoPlanFromPackagesNotCurrentOrWithoutARecord}, + {"TestApplyWritesAnAskForTheNodesKeeper", testApplyWritesAnAskForTheNodesKeeper}, + {"TestAnAskedRollbackIsOneTransactionWithItsEventsAndTheCheck", testAnAskedRollbackIsOneTransactionWithItsEventsAndTheCheck}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/root_test.go b/modules/pacman/cmd/pacman-tools/root_test.go index c5303f7e6..04bbf9d0b 100644 --- a/modules/pacman/cmd/pacman-tools/root_test.go +++ b/modules/pacman/cmd/pacman-tools/root_test.go @@ -15,7 +15,10 @@ import ( "path/filepath" "reflect" "strings" + "sync/atomic" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // rootBed is a helper over a recording runner, a stand-in process table and a plan directory of its own. @@ -64,13 +67,16 @@ func (s stubProc) Readlink(name string) (string, error) { const aRun = "20261024T040000Z" -// testSocket is a socket in the abstract namespace, named for the test: a path under a test's temporary -// directory can pass the 108 bytes a socket's path may hold. +// testSocket is a socket in the abstract namespace, named for the test and numbered per call, as one test runs +// several cases whose listeners live until its end: a path under a test's temporary directory can pass the 108 +// bytes a socket's path may hold. func testSocket(t *testing.T) string { - return fmt.Sprintf("@pacman-root-test-%d-%s", os.Getpid(), t.Name()) + return fmt.Sprintf("@pacman-root-test-%d-%s-%d", os.Getpid(), t.Name(), sockets.Add(1)) } -func TestTheRootHelperStartsAnUpgradeAsTheRunsUnit(t *testing.T) { +var sockets atomic.Int64 + +func testTheRootHelperStartsAnUpgradeAsTheRunsUnit(t *testing.T) { b := newRootBed(t) a := b.h.Handle(RootRequest{Verb: VerbTransaction, Kind: RunUpgrade, Run: aRun, Ignore: []string{"linux", "linux-headers"}}) if a.Error != "" { @@ -83,7 +89,7 @@ func TestTheRootHelperStartsAnUpgradeAsTheRunsUnit(t *testing.T) { } } -func TestTheRootHelperStartsARollbackWithThePlanInTheRequest(t *testing.T) { +func testTheRootHelperStartsARollbackWithThePlanInTheRequest(t *testing.T) { b := newRootBed(t) plan := []RollbackItem{ {Name: "bash", From: "5.3.20-1", To: "5.3.15-1", Source: SourceCache, Location: CacheDir + "/bash-5.3.15-1-x86_64.pkg.tar.zst"}, @@ -115,7 +121,7 @@ func TestTheRootHelperStartsARollbackWithThePlanInTheRequest(t *testing.T) { } // And (ADR 0585 §3) the verb mirrorlist writes the mirror list file whole from the servers it is sent, running nothing. -func TestTheRootHelperReadsTheReplacedFilesMappings(t *testing.T) { +func testTheRootHelperReadsTheReplacedFilesMappings(t *testing.T) { b := newRootBed(t) servers := []string{"https://a.example/$repo/os/$arch", "https://b.example/archlinux/$repo/os/$arch"} if a := b.h.Handle(RootRequest{Verb: VerbMirrorlist, Servers: servers}); a.Error != "" { @@ -131,7 +137,7 @@ func TestTheRootHelperReadsTheReplacedFilesMappings(t *testing.T) { } } -func TestTheRootHelperReadsATransactionUnitsJournal(t *testing.T) { +func testTheRootHelperReadsATransactionUnitsJournal(t *testing.T) { b := newRootBed(t) unit := TransactionUnit(RunUpgrade, aRun) a := b.h.Handle(RootRequest{Verb: VerbJournal, Unit: unit, Lines: 40}) @@ -144,7 +150,7 @@ func TestTheRootHelperReadsATransactionUnitsJournal(t *testing.T) { } } -func TestTheRootHelperRefusesEverythingOffItsList(t *testing.T) { +func testTheRootHelperRefusesEverythingOffItsList(t *testing.T) { good := RollbackItem{Name: "bash", From: "5.3.20-1", To: "5.3.15-1", Source: SourceCache, Location: CacheDir + "/bash-5.3.15-1-x86_64.pkg.tar.zst"} with := func(f func(*RollbackItem)) []RollbackItem { i := good; f(&i); return []RollbackItem{i} } cases := map[string]RootRequest{ @@ -211,14 +217,14 @@ func serveOnce(t *testing.T, peer int, req RootRequest) (RootAnswer, error) { return rootClient{Socket: sock}.ask(req) } -func TestTheRootHelperAnswersTheKeepersAccountOverItsSocket(t *testing.T) { +func testTheRootHelperAnswersTheKeepersAccountOverItsSocket(t *testing.T) { a, err := serveOnce(t, os.Getuid(), RootRequest{Verb: VerbMaps}) if err != nil || a.Error != "" || len(a.Mapped) != 1 { t.Fatalf("the keeper's own account was answered %+v, %v", a, err) } } -func TestTheRootHelperRefusesAnyOtherAccount(t *testing.T) { +func testTheRootHelperRefusesAnyOtherAccount(t *testing.T) { a, err := serveOnce(t, os.Getuid()+1, RootRequest{Verb: VerbMaps}) if err == nil && a.Error == "" { t.Fatalf("another account was answered: %+v", a) @@ -228,7 +234,7 @@ func TestTheRootHelperRefusesAnyOtherAccount(t *testing.T) { } } -func TestTheClientCarriesTheRootActsAndSaysARefusal(t *testing.T) { +func testTheClientCarriesTheRootActsAndSaysARefusal(t *testing.T) { b := newRootBed(t) b.h.Peer = os.Getuid() sock := testSocket(t) @@ -254,9 +260,17 @@ func TestTheClientCarriesTheRootActsAndSaysARefusal(t *testing.T) { } } -func TestTheRootHelperIsRootWithNoBusAndNoSudoRule(t *testing.T) { - m := manifest(t) - r := m.resource(t, "root-helper") +func testTheRootHelperIsRootWithNoBusAndNoSudoRule(t *testing.T) { + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + r := resourceOf(t, m, "root-helper") if r["type"] != "process" || r["name"] != "pacman-root" || r["artifact"] != "tools" || strings.Join(strs(r["run"]), " ") != "./"+binaryName+" root" { t.Fatalf("the root helper: %v", r) @@ -271,7 +285,7 @@ func TestTheRootHelperIsRootWithNoBusAndNoSudoRule(t *testing.T) { if env[EnvRootSocket] != RootSocketPath || env[EnvRootPeer] != "pacman-keeper" { t.Errorf("the root helper's environment names its socket and the keeper's account: %v", env) } - k := m.resource(t, "keeper") + k := resourceOf(t, m, "keeper") kenv, _ := k["env"].(map[string]any) if kenv[EnvRootSocket] != RootSocketPath { t.Errorf("the keeper is told the helper's socket: %v", kenv) @@ -283,7 +297,7 @@ func TestTheRootHelperIsRootWithNoBusAndNoSudoRule(t *testing.T) { } } -func TestTheRollbackUnitInstallsThePlanThenRemovesWhatWasAskedInOrder(t *testing.T) { +func testTheRollbackUnitInstallsThePlanThenRemovesWhatWasAskedInOrder(t *testing.T) { dir := t.TempDir() plan := []RollbackItem{ {Name: "bash", To: "5.3.15-1", Source: SourceCache, Location: CacheDir + "/bash-5.3.15-1-x86_64.pkg.tar.zst"}, @@ -314,7 +328,7 @@ func TestTheRollbackUnitInstallsThePlanThenRemovesWhatWasAskedInOrder(t *testing } } -func TestTheRollbackUnitChangesNothingWhenAPackageIsNotFound(t *testing.T) { +func testTheRollbackUnitChangesNothingWhenAPackageIsNotFound(t *testing.T) { file := filepath.Join(t.TempDir(), aRun+".json") raw, _ := json.Marshal([]RollbackItem{{Name: "zlib", To: "1.3.1-2", Source: SourceRepository, Location: ArchiveURL + "/repos/2026/10/04/core/os/$arch"}}) _ = os.WriteFile(file, raw, 0o600) @@ -324,3 +338,27 @@ func TestTheRollbackUnitChangesNothingWhenAPackageIsNotFound(t *testing.T) { t.Fatalf("exit %d, ran %q: a package the archive does not hold fails the unit before any change", code, ran) } } + +// TestTheRootHelperStartsAnUpgradeAsTheRunsUnit runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestTheRootHelperStartsAnUpgradeAsTheRunsUnit(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestTheRootHelperStartsAnUpgradeAsTheRunsUnit", testTheRootHelperStartsAnUpgradeAsTheRunsUnit}, + {"TestTheRootHelperStartsARollbackWithThePlanInTheRequest", testTheRootHelperStartsARollbackWithThePlanInTheRequest}, + {"TestTheRootHelperReadsTheReplacedFilesMappings", testTheRootHelperReadsTheReplacedFilesMappings}, + {"TestTheRootHelperReadsATransactionUnitsJournal", testTheRootHelperReadsATransactionUnitsJournal}, + {"TestTheRootHelperRefusesEverythingOffItsList", testTheRootHelperRefusesEverythingOffItsList}, + {"TestTheRootHelperAnswersTheKeepersAccountOverItsSocket", testTheRootHelperAnswersTheKeepersAccountOverItsSocket}, + {"TestTheRootHelperRefusesAnyOtherAccount", testTheRootHelperRefusesAnyOtherAccount}, + {"TestTheClientCarriesTheRootActsAndSaysARefusal", testTheClientCarriesTheRootActsAndSaysARefusal}, + {"TestTheRootHelperIsRootWithNoBusAndNoSudoRule", testTheRootHelperIsRootWithNoBusAndNoSudoRule}, + {"TestTheRollbackUnitInstallsThePlanThenRemovesWhatWasAskedInOrder", testTheRollbackUnitInstallsThePlanThenRemovesWhatWasAskedInOrder}, + {"TestTheRollbackUnitChangesNothingWhenAPackageIsNotFound", testTheRollbackUnitChangesNothingWhenAPackageIsNotFound}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/rounds_test.go b/modules/pacman/cmd/pacman-tools/rounds_test.go index 65463f51b..5a9545e67 100644 --- a/modules/pacman/cmd/pacman-tools/rounds_test.go +++ b/modules/pacman/cmd/pacman-tools/rounds_test.go @@ -85,7 +85,7 @@ func (b *roundBed) state(t *testing.T) map[string]NodeInRound { return out } -func TestTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn(t *testing.T) { +func testTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn(t *testing.T) { if o := RoundOpening(time.Date(2026, 10, 22, 15, 0, 0, 0, time.UTC)); !o.Equal(time.Date(2026, 10, 24, 4, 0, 0, 0, time.UTC)) { t.Fatalf("the opening of the week of Thursday 22 October: %s", o) } @@ -144,7 +144,7 @@ func TestTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn(t *test } } -func TestNoOrderNoRound(t *testing.T) { +func testNoOrderNoRound(t *testing.T) { b := newRoundBed(t) b.now = time.Date(2026, 10, 24, 5, 0, 0, 0, time.UTC) if next := b.step(t, "node-a"); !next.IsZero() { @@ -155,7 +155,7 @@ func TestNoOrderNoRound(t *testing.T) { } } -func TestANodeOffAtItsTurnRunsAtItsNextStartAndAStalledTurnIsSaid(t *testing.T) { +func testANodeOffAtItsTurnRunsAtItsNextStartAndAStalledTurnIsSaid(t *testing.T) { b := newRoundBed(t, "node-a", "node-b", "node-c") b.now = time.Date(2026, 10, 24, 4, 0, 0, 0, time.UTC) b.step(t, "node-a") @@ -183,7 +183,7 @@ func warrant(a oc.Ask, option string, level string, at time.Time) json.RawMessag return raw } -func TestOnlyTheOperatorsApprovePassesANodeAndAPassNeedsAReason(t *testing.T) { +func testOnlyTheOperatorsApprovePassesANodeAndAPassNeedsAReason(t *testing.T) { b := newRoundBed(t, "node-a", "node-b", "node-c") b.now = time.Date(2026, 10, 24, 4, 0, 0, 0, time.UTC) b.step(t, "node-a") @@ -254,7 +254,7 @@ func TestOnlyTheOperatorsApprovePassesANodeAndAPassNeedsAReason(t *testing.T) { } } -func TestAPassTheOperatorKeepsWaitingPassesNothing(t *testing.T) { +func testAPassTheOperatorKeepsWaitingPassesNothing(t *testing.T) { b := newRoundBed(t, "node-a", "node-b") b.now = time.Date(2026, 10, 24, 4, 0, 0, 0, time.UTC) b.step(t, "node-a") // node-a runs and never ends @@ -287,7 +287,7 @@ func TestAPassTheOperatorKeepsWaitingPassesNothing(t *testing.T) { } } -func TestPacmanRoundReadsTheRounds(t *testing.T) { +func testPacmanRoundReadsTheRounds(t *testing.T) { b := newRoundBed(t, "node-a", "node-b") b.now = time.Date(2026, 10, 24, 4, 0, 0, 0, time.UTC) b.step(t, "node-a") @@ -304,3 +304,22 @@ func TestPacmanRoundReadsTheRounds(t *testing.T) { t.Error("a round that is not there") } } + +// TestTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn", testTheRoundOpensSaturdayAtFourAndThePassedCheckGivesTheNextItsTurn}, + {"TestNoOrderNoRound", testNoOrderNoRound}, + {"TestANodeOffAtItsTurnRunsAtItsNextStartAndAStalledTurnIsSaid", testANodeOffAtItsTurnRunsAtItsNextStartAndAStalledTurnIsSaid}, + {"TestOnlyTheOperatorsApprovePassesANodeAndAPassNeedsAReason", testOnlyTheOperatorsApprovePassesANodeAndAPassNeedsAReason}, + {"TestAPassTheOperatorKeepsWaitingPassesNothing", testAPassTheOperatorKeepsWaitingPassesNothing}, + {"TestPacmanRoundReadsTheRounds", testPacmanRoundReadsTheRounds}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/runs_test.go b/modules/pacman/cmd/pacman-tools/runs_test.go index d339b695f..98352a4e5 100644 --- a/modules/pacman/cmd/pacman-tools/runs_test.go +++ b/modules/pacman/cmd/pacman-tools/runs_test.go @@ -24,7 +24,7 @@ func capturedLog(t *testing.T) string { // The captured log holds three full upgrades among other commands: one that ended before any transaction, one // whose transaction completed, and a later one that upgraded one package. -func TestEveryFullUpgradeOfTheLogIsARunReadFromIt(t *testing.T) { +func testEveryFullUpgradeOfTheLogIsARunReadFromIt(t *testing.T) { runs := PastUpgrades("node-a", capturedLog(t)) if len(runs) != 3 { t.Fatalf("%d runs, want the three full upgrades and none of the other commands: %+v", len(runs), runs) @@ -61,7 +61,7 @@ func TestEveryFullUpgradeOfTheLogIsARunReadFromIt(t *testing.T) { } } -func TestATransactionWithoutAnEndOrThatFailedIsAFailedRun(t *testing.T) { +func testATransactionWithoutAnEndOrThatFailedIsAFailedRun(t *testing.T) { log := "[2026-10-10T04:00:00+0000] [PACMAN] Running 'pacman -Syu --noconfirm'\n" + "[2026-10-10T04:00:01+0000] [PACMAN] starting full system upgrade\n" + "[2026-10-10T04:00:05+0000] [ALPM] transaction started\n" + @@ -82,7 +82,7 @@ func TestATransactionWithoutAnEndOrThatFailedIsAFailedRun(t *testing.T) { } } -func TestTheLogIsReadIntoRunsOnceAndASecondStartReadsNothing(t *testing.T) { +func testTheLogIsReadIntoRunsOnceAndASecondStartReadsNothing(t *testing.T) { m := machine(nil, 1000) reads := 0 log := capturedLog(t) @@ -116,7 +116,7 @@ func TestTheLogIsReadIntoRunsOnceAndASecondStartReadsNothing(t *testing.T) { // A run's key is created at its first step and then only updated from the revision its writer holds: a step // is written once, and a run another writer changed meanwhile is refused, never overwritten. -func TestAStepIsWrittenOnceAndAnotherWritersChangeIsNeverOverwritten(t *testing.T) { +func testAStepIsWrittenOnceAndAnotherWritersChangeIsNeverOverwritten(t *testing.T) { runs := newBucket() u := &Upgrades{Node: "node-a", Runs: runs} r := &openRun{Run: Run{Node: "node-a", Run: "20261024T040000Z", Kind: RunUpgrade, From: FromAsk}} @@ -142,7 +142,7 @@ func TestAStepIsWrittenOnceAndAnotherWritersChangeIsNeverOverwritten(t *testing. } } -func TestPacmanUpgradesAnswersAllOneNodeDaysAndOneRun(t *testing.T) { +func testPacmanUpgradesAnswersAllOneNodeDaysAndOneRun(t *testing.T) { runs := newBucket() put := func(node, id string, steps ...Step) { r := Run{Node: node, Run: id, Kind: RunUpgrade, From: FromRound, Round: "2026-W43", Steps: steps} @@ -194,7 +194,7 @@ func TestPacmanUpgradesAnswersAllOneNodeDaysAndOneRun(t *testing.T) { } } -func TestTheUpgradesToolReadsTheRunsState(t *testing.T) { +func testTheUpgradesToolReadsTheRunsState(t *testing.T) { runs := newBucket() saved := upgradeState upgradeState = func(name string) Bucket { @@ -215,3 +215,22 @@ func TestTheUpgradesToolReadsTheRunsState(t *testing.T) { } t.Fatal("no pacman_upgrades") } + +// TestEveryFullUpgradeOfTheLogIsARunReadFromIt runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestEveryFullUpgradeOfTheLogIsARunReadFromIt(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestEveryFullUpgradeOfTheLogIsARunReadFromIt", testEveryFullUpgradeOfTheLogIsARunReadFromIt}, + {"TestATransactionWithoutAnEndOrThatFailedIsAFailedRun", testATransactionWithoutAnEndOrThatFailedIsAFailedRun}, + {"TestTheLogIsReadIntoRunsOnceAndASecondStartReadsNothing", testTheLogIsReadIntoRunsOnceAndASecondStartReadsNothing}, + {"TestAStepIsWrittenOnceAndAnotherWritersChangeIsNeverOverwritten", testAStepIsWrittenOnceAndAnotherWritersChangeIsNeverOverwritten}, + {"TestPacmanUpgradesAnswersAllOneNodeDaysAndOneRun", testPacmanUpgradesAnswersAllOneNodeDaysAndOneRun}, + {"TestTheUpgradesToolReadsTheRunsState", testTheUpgradesToolReadsTheRunsState}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/shape_test.go b/modules/pacman/cmd/pacman-tools/shape_test.go index 33643d519..b8f18de73 100644 --- a/modules/pacman/cmd/pacman-tools/shape_test.go +++ b/modules/pacman/cmd/pacman-tools/shape_test.go @@ -1,39 +1,15 @@ package main import ( - "encoding/json" "os" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) type resource map[string]any -type manifestShape struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Claims []map[string]any `json:"claims"` - Tools []string `json:"tools"` - Resources []resource `json:"resources"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func manifest(t *testing.T) manifestShape { - t.Helper() - raw, err := os.ReadFile("../../module.json") - if err != nil { - t.Fatal(err) - } - var m manifestShape - if err := json.Unmarshal(raw, &m); err != nil { - t.Fatal(err) - } - return m -} - -func (m manifestShape) resource(t *testing.T, id string) resource { +func resourceOf(t *testing.T, m catalogue.Manifest, id string) resource { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -47,7 +23,15 @@ func (m manifestShape) resource(t *testing.T, id string) resource { // TestToolsAreTheManifests holds the served tools and the manifest's list to one another, and the // bundle to the shape the builder compiles and the runtime loads. func TestToolsAreTheManifests(t *testing.T) { - m := manifest(t) + manifestJSON, err := os.ReadFile("../../module.json") + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } names := map[string]bool{} for _, tool := range tools(machine(nil, 1000)) { if names[tool.Name] { @@ -64,17 +48,17 @@ func TestToolsAreTheManifests(t *testing.T) { if len(names) != 0 { t.Errorf("served and not listed: %v", names) } - var tools map[string]any + var tools *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["name"] == "tools" { - tools = a + if a.Name == "tools" { + tools = &a } } - if tools == nil || tools["kind"] != "bundle" || tools["language"] != "go" || tools["system"] != "arch" || - tools["from"] != "cmd/"+binaryName || tools["binary"] != binaryName { + if tools == nil || tools.Kind != "bundle" || tools.Language != "go" || tools.System != "arch" || + tools.From != "cmd/"+binaryName || tools.Binary != binaryName { t.Fatalf("the tools artifact: %v", tools) } - if loads, _ := tools["loads"].([]any); len(loads) != 1 || loads[0] != binaryName { - t.Fatalf("loads: %v", tools["loads"]) + if len(tools.Loads) != 1 || tools.Loads[0] != binaryName { + t.Fatalf("loads: %v", tools.Loads) } } diff --git a/modules/pacman/cmd/pacman-tools/transaction_test.go b/modules/pacman/cmd/pacman-tools/transaction_test.go index 1ea5466a2..18306804f 100644 --- a/modules/pacman/cmd/pacman-tools/transaction_test.go +++ b/modules/pacman/cmd/pacman-tools/transaction_test.go @@ -180,7 +180,7 @@ func steps(r Run) string { return strings.Join(s, " ") } -func TestAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep(t *testing.T) { +func testAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep(t *testing.T) { k := newKeeperBed(t) key, err := k.ask(t, "node-a", ActUpgrade) if err != nil { @@ -238,7 +238,7 @@ func TestAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep(t *testing.T) { } } -func TestAFailedTransactionIsWrittenWithItsExitAndLastErrorAndChecked(t *testing.T) { +func testAFailedTransactionIsWrittenWithItsExitAndLastErrorAndChecked(t *testing.T) { k := newKeeperBed(t) if _, err := k.ask(t, "node-a", ActUpgrade); err != nil { t.Fatal(err) @@ -259,7 +259,7 @@ func TestAFailedTransactionIsWrittenWithItsExitAndLastErrorAndChecked(t *testing } } -func TestATransactionThatCannotStartFailsAndIsChecked(t *testing.T) { +func testATransactionThatCannotStartFailsAndIsChecked(t *testing.T) { k := newKeeperBed(t) k.root.fail = errors.New("the root helper's socket is not there") if _, err := k.ask(t, "node-a", ActUpgrade); err != nil { @@ -271,7 +271,7 @@ func TestATransactionThatCannotStartFailsAndIsChecked(t *testing.T) { } } -func TestAnAskIsTakenByItsNodesKeeperAlone(t *testing.T) { +func testAnAskIsTakenByItsNodesKeeperAlone(t *testing.T) { k := newKeeperBed(t) key, err := k.ask(t, "node-b", ActUpgrade) if err != nil { @@ -288,7 +288,7 @@ func TestAnAskIsTakenByItsNodesKeeperAlone(t *testing.T) { } } -func TestAnAskARunAlreadyNamesIsDeletedAndNotRunAgain(t *testing.T) { +func testAnAskARunAlreadyNamesIsDeletedAndNotRunAgain(t *testing.T) { k := newKeeperBed(t) done := Run{Node: "node-a", Run: "20261004T115900Z", Kind: RunUpgrade, From: FromAsk, Ask: RunID(k.now) + "-abc123", Steps: []Step{{Step: StepRefused, At: k.now, Why: "x"}}} @@ -307,7 +307,7 @@ func TestAnAskARunAlreadyNamesIsDeletedAndNotRunAgain(t *testing.T) { } } -func TestARunDoesNotStartWhileTheDatabaseIsLockedOrAnotherRunGoesOn(t *testing.T) { +func testARunDoesNotStartWhileTheDatabaseIsLockedOrAnotherRunGoesOn(t *testing.T) { k := newKeeperBed(t) k.locked = true if _, err := k.ask(t, "node-a", ActUpgrade); err != nil { @@ -336,7 +336,7 @@ func TestARunDoesNotStartWhileTheDatabaseIsLockedOrAnotherRunGoesOn(t *testing.T } } -func TestAKeeperStartedAgainFollowsItsRunToItsEnd(t *testing.T) { +func testAKeeperStartedAgainFollowsItsRunToItsEnd(t *testing.T) { k := newKeeperBed(t) if _, err := k.ask(t, "node-a", ActUpgrade); err != nil { t.Fatal(err) @@ -357,7 +357,7 @@ func TestAKeeperStartedAgainFollowsItsRunToItsEnd(t *testing.T) { } } -func TestAKeeperStartedAgainTakesUpARunStoppedBetweenItsSteps(t *testing.T) { +func testAKeeperStartedAgainTakesUpARunStoppedBetweenItsSteps(t *testing.T) { // Stopped after the gate, before the transaction started: nothing started, so the run is refused. k := newKeeperBed(t) stopped := Run{Node: "node-a", Run: "20261004T115900Z", Kind: RunUpgrade, From: FromAsk, @@ -401,7 +401,7 @@ func TestAKeeperStartedAgainTakesUpARunStoppedBetweenItsSteps(t *testing.T) { } } -func TestPacmanUpgradeWritesAnAskForTheNodeAndStartsNothing(t *testing.T) { +func testPacmanUpgradeWritesAnAskForTheNodeAndStartsNothing(t *testing.T) { asks := newBucket() savedState, savedNode, savedFetch := upgradeState, thisNode, fetch upgradeState = func(name string) Bucket { @@ -445,3 +445,25 @@ func TestPacmanUpgradeWritesAnAskForTheNodeAndStartsNothing(t *testing.T) { } t.Fatal("no pacman_upgrade") } + +// TestAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep", testAnAskedUpgradeIsARunWrittenAndEmittedAtEachStep}, + {"TestAFailedTransactionIsWrittenWithItsExitAndLastErrorAndChecked", testAFailedTransactionIsWrittenWithItsExitAndLastErrorAndChecked}, + {"TestATransactionThatCannotStartFailsAndIsChecked", testATransactionThatCannotStartFailsAndIsChecked}, + {"TestAnAskIsTakenByItsNodesKeeperAlone", testAnAskIsTakenByItsNodesKeeperAlone}, + {"TestAnAskARunAlreadyNamesIsDeletedAndNotRunAgain", testAnAskARunAlreadyNamesIsDeletedAndNotRunAgain}, + {"TestARunDoesNotStartWhileTheDatabaseIsLockedOrAnotherRunGoesOn", testARunDoesNotStartWhileTheDatabaseIsLockedOrAnotherRunGoesOn}, + {"TestAKeeperStartedAgainFollowsItsRunToItsEnd", testAKeeperStartedAgainFollowsItsRunToItsEnd}, + {"TestAKeeperStartedAgainTakesUpARunStoppedBetweenItsSteps", testAKeeperStartedAgainTakesUpARunStoppedBetweenItsSteps}, + {"TestPacmanUpgradeWritesAnAskForTheNodeAndStartsNothing", testPacmanUpgradeWritesAnAskForTheNodeAndStartsNothing}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/upgrade_health_test.go b/modules/pacman/cmd/pacman-tools/upgrade_health_test.go index 866902368..884e60e93 100644 --- a/modules/pacman/cmd/pacman-tools/upgrade_health_test.go +++ b/modules/pacman/cmd/pacman-tools/upgrade_health_test.go @@ -32,14 +32,14 @@ func passedRun(node string, at time.Time) Run { {Step: StepFinished, At: at.Add(5 * time.Minute)}, {Step: StepCheckedAfter, At: at.Add(6 * time.Minute), Check: &Check{Passed: true}}}} } -func TestWithNoOrderEveryNodesHealthSaysWhy(t *testing.T) { +func testWithNoOrderEveryNodesHealthSaysWhy(t *testing.T) { m, _ := healthBed(t, nil) if h := m.UpgradeHealth(); h.Healthy || !strings.Contains(h.Why, "upgrade-order") { t.Fatalf("%+v", h) } } -func TestANodeWithNoRunYetIsHealthy(t *testing.T) { +func testANodeWithNoRunYetIsHealthy(t *testing.T) { m, _ := healthBed(t, []string{"node-a", "node-b"}) if h := m.UpgradeHealth(); !h.Healthy { t.Fatalf("%+v", h) @@ -48,7 +48,7 @@ func TestANodeWithNoRunYetIsHealthy(t *testing.T) { // issue 1579: a run that failed is unhealthy until a later run passes, whenever the node woke; a run read from // the log is history and judges nothing. -func TestTheLatestRunJudgesTheNodeNotAUnitsAge(t *testing.T) { +func testTheLatestRunJudgesTheNodeNotAUnitsAge(t *testing.T) { m, states := healthBed(t, []string{"node-a", "node-b"}) exit := 1 failedAt := healthNow.Add(-7 * 24 * time.Hour) @@ -68,7 +68,7 @@ func TestTheLatestRunJudgesTheNodeNotAUnitsAge(t *testing.T) { } } -func TestAFailedCheckIsUnhealthy(t *testing.T) { +func testAFailedCheckIsUnhealthy(t *testing.T) { m, states := healthBed(t, []string{"node-b"}) r := passedRun("node-b", healthNow.Add(-time.Hour)) r.Steps[len(r.Steps)-1].Check = &Check{Passed: false, Unbuilt: []DKMSBuild{{Module: "made-up-dkms", Version: "1.0", Kernel: "7.3.1-arch1-1"}}} @@ -78,7 +78,7 @@ func TestAFailedCheckIsUnhealthy(t *testing.T) { } } -func TestARunPastTheLimitIsHungAndOneWithinItIsHealthy(t *testing.T) { +func testARunPastTheLimitIsHungAndOneWithinItIsHealthy(t *testing.T) { m, states := healthBed(t, []string{"node-b"}) started := healthNow.Add(-3 * time.Hour) putRun(states, Run{Node: "node-b", Run: RunID(started), Kind: RunUpgrade, From: FromAsk, Steps: []Step{{Step: StepRecorded, At: started}, {Step: StepStarted, At: started, Unit: TransactionUnit(RunUpgrade, RunID(started))}}}) @@ -94,7 +94,7 @@ func TestARunPastTheLimitIsHungAndOneWithinItIsHealthy(t *testing.T) { } // 1841/AC4: a held kernel keeps the health unhealthy, naming it, until a later run upgrades it. -func TestAHeldKernelIsSaidUntilARunUpgradesIt(t *testing.T) { +func testAHeldKernelIsSaidUntilARunUpgradesIt(t *testing.T) { m, states := healthBed(t, []string{"node-b"}) r := passedRun("node-b", healthNow.Add(-2*time.Hour)) r.Steps[1].Held = []HeldKernel{{Package: "linux", Version: "7.3.1.arch1-1", Module: "zfs", Bound: "Linux-Maximum 7.2"}} @@ -111,7 +111,7 @@ func TestAHeldKernelIsSaidUntilARunUpgradesIt(t *testing.T) { // 1841/AC7: a turn not started within round-start-minutes makes the waiting node's health name the node it // waits for and since when; the stalled node's own health says it too. -func TestAStalledRoundIsSaidByTheNodesWaitingOnIt(t *testing.T) { +func testAStalledRoundIsSaidByTheNodesWaitingOnIt(t *testing.T) { order := []string{"node-a", "node-b", "node-c"} m, states := healthBed(t, order) round := RoundID(healthNow) @@ -131,7 +131,7 @@ func TestAStalledRoundIsSaidByTheNodesWaitingOnIt(t *testing.T) { } } -func TestARoundStoppedByAFailureIsSaidByTheNodesWaitingOnIt(t *testing.T) { +func testARoundStoppedByAFailureIsSaidByTheNodesWaitingOnIt(t *testing.T) { order := []string{"node-a", "node-b"} m, states := healthBed(t, order) round := RoundID(healthNow) @@ -145,3 +145,24 @@ func TestARoundStoppedByAFailureIsSaidByTheNodesWaitingOnIt(t *testing.T) { t.Fatalf("%+v", h) } } + +// TestWithNoOrderEveryNodesHealthSaysWhy runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestWithNoOrderEveryNodesHealthSaysWhy(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestWithNoOrderEveryNodesHealthSaysWhy", testWithNoOrderEveryNodesHealthSaysWhy}, + {"TestANodeWithNoRunYetIsHealthy", testANodeWithNoRunYetIsHealthy}, + {"TestTheLatestRunJudgesTheNodeNotAUnitsAge", testTheLatestRunJudgesTheNodeNotAUnitsAge}, + {"TestAFailedCheckIsUnhealthy", testAFailedCheckIsUnhealthy}, + {"TestARunPastTheLimitIsHungAndOneWithinItIsHealthy", testARunPastTheLimitIsHungAndOneWithinItIsHealthy}, + {"TestAHeldKernelIsSaidUntilARunUpgradesIt", testAHeldKernelIsSaidUntilARunUpgradesIt}, + {"TestAStalledRoundIsSaidByTheNodesWaitingOnIt", testAStalledRoundIsSaidByTheNodesWaitingOnIt}, + {"TestARoundStoppedByAFailureIsSaidByTheNodesWaitingOnIt", testARoundStoppedByAFailureIsSaidByTheNodesWaitingOnIt}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/cmd/pacman-tools/view_test.go b/modules/pacman/cmd/pacman-tools/view_test.go index 82c1f3a55..7b6dc1853 100644 --- a/modules/pacman/cmd/pacman-tools/view_test.go +++ b/modules/pacman/cmd/pacman-tools/view_test.go @@ -42,7 +42,7 @@ func viewStates(t *testing.T) (*fakeStates, *Machine) { return states, m } -func TestOnePackageOnEveryNodeWithWhoDeclaresIt(t *testing.T) { +func testOnePackageOnEveryNodeWithWhoDeclaresIt(t *testing.T) { _, m := viewStates(t) r, err := m.Packages("zsh", 500) if err != nil { @@ -99,7 +99,7 @@ func TestOnePackageOnEveryNodeWithWhoDeclaresIt(t *testing.T) { } } -func TestTheViewSaysWhatDiffersWhatIsOnSomeNodesWhatNoModuleDeclaresAndTheForeignApart(t *testing.T) { +func testTheViewSaysWhatDiffersWhatIsOnSomeNodesWhatNoModuleDeclaresAndTheForeignApart(t *testing.T) { _, m := viewStates(t) r, err := m.Packages("", 500) if err != nil { @@ -135,7 +135,7 @@ func TestTheViewSaysWhatDiffersWhatIsOnSomeNodesWhatNoModuleDeclaresAndTheForeig } } -func TestInstalledAndForeignAnswerFromTheBus(t *testing.T) { +func testInstalledAndForeignAnswerFromTheBus(t *testing.T) { _, m := viewStates(t) r, err := m.InstalledFrom("", "", "", false, 10) if err != nil || r["node"] != "node-a" || r["count"] != 4 || r["current"] != true { @@ -161,7 +161,7 @@ func TestInstalledAndForeignAnswerFromTheBus(t *testing.T) { } } -func TestUpdatesAnswerEveryNodeAndWhenItsListLastChanged(t *testing.T) { +func testUpdatesAnswerEveryNodeAndWhenItsListLastChanged(t *testing.T) { states, m := viewStates(t) up := states.store(StateUpdates) up.now = func() time.Time { return t0.Add(-2 * time.Hour) } @@ -183,7 +183,7 @@ func TestUpdatesAnswerEveryNodeAndWhenItsListLastChanged(t *testing.T) { } } -func TestANodeArgumentIsOneKeyToken(t *testing.T) { +func testANodeArgumentIsOneKeyToken(t *testing.T) { for _, bad := range []string{"node-a.not-current", "node-a.*", "a b"} { if _, err := nodeOf(map[string]any{"node": bad}); err == nil { t.Errorf("%q was taken as a node", bad) @@ -200,3 +200,21 @@ type failingReader struct{ err error } func (f failingReader) Get(string) (*stdio.StateEntry, error) { return nil, f.err } func (f failingReader) Keys() ([]string, error) { return nil, f.err } func (f failingReader) History(string) ([]stdio.StateRevision, error) { return nil, f.err } + +// TestOnePackageOnEveryNodeWithWhoDeclaresIt runs this file's cases in order as one test, each a row: the check counts every top-level test against the +// module's budget of 50 (design 47 H2 §819). A failing case is named by the line logged before it. +func TestOnePackageOnEveryNodeWithWhoDeclaresIt(t *testing.T) { + for _, c := range []struct { + name string + run func(*testing.T) + }{ + {"TestOnePackageOnEveryNodeWithWhoDeclaresIt", testOnePackageOnEveryNodeWithWhoDeclaresIt}, + {"TestTheViewSaysWhatDiffersWhatIsOnSomeNodesWhatNoModuleDeclaresAndTheForeignApart", testTheViewSaysWhatDiffersWhatIsOnSomeNodesWhatNoModuleDeclaresAndTheForeignApart}, + {"TestInstalledAndForeignAnswerFromTheBus", testInstalledAndForeignAnswerFromTheBus}, + {"TestUpdatesAnswerEveryNodeAndWhenItsListLastChanged", testUpdatesAnswerEveryNodeAndWhenItsListLastChanged}, + {"TestANodeArgumentIsOneKeyToken", testANodeArgumentIsOneKeyToken}, + } { + t.Logf("case %s", c.name) + c.run(t) + } +} diff --git a/modules/pacman/module.json b/modules/pacman/module.json index fff50da70..580aaaa54 100644 --- a/modules/pacman/module.json +++ b/modules/pacman/module.json @@ -1,6 +1,7 @@ { "module": "pacman", "version": "0.1", + "class": "core", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/photos-eef/module.json b/modules/photos-eef/module.json index 3bb9940f3..6f9989e33 100644 --- a/modules/photos-eef/module.json +++ b/modules/photos-eef/module.json @@ -1,6 +1,7 @@ { "module": "photos-eef", "version": "0.1", + "class": "leaf", "slug": "eef", "capabilities": [ "container-runtime" diff --git a/modules/photos-filip/module.json b/modules/photos-filip/module.json index 8287b4a1f..c526f3818 100644 --- a/modules/photos-filip/module.json +++ b/modules/photos-filip/module.json @@ -1,6 +1,7 @@ { "module": "photos-filip", "version": "0.1", + "class": "leaf", "slug": "filip", "capabilities": [ "container-runtime" diff --git a/modules/picom/cmd/picom-tools/manifest_helpers_test.go b/modules/picom/cmd/picom-tools/manifest_helpers_test.go index a652d238c..ba6b7a333 100644 --- a/modules/picom/cmd/picom-tools/manifest_helpers_test.go +++ b/modules/picom/cmd/picom-tools/manifest_helpers_test.go @@ -1,81 +1,15 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Config map[string]config `json:"config"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -// config is one config value as the definition declares it (novox/hq ADR 0348 §4). -type config struct { - Type string `json:"type"` - Description string `json:"description"` - Enum []any `json:"enum"` - Minimum *float64 `json:"minimum"` - Maximum *float64 `json:"maximum"` - Pattern string `json:"pattern"` - Trusted bool `json:"trusted"` - Predefined string `json:"predefined"` - Default any `json:"default"` - Required bool `json:"required"` - Runtime bool `json:"runtime"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -86,7 +20,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -102,9 +36,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -124,7 +58,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -133,10 +67,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -146,9 +80,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -161,7 +95,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -203,14 +137,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } diff --git a/modules/picom/cmd/picom-tools/manifest_test.go b/modules/picom/cmd/picom-tools/manifest_test.go index 5c6a397dd..98f7b1b31 100644 --- a/modules/picom/cmd/picom-tools/manifest_test.go +++ b/modules/picom/cmd/picom-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // picom's shape (novox/hq ADR 0208): it claims node-compositor and serves no verb of it, requires the @@ -11,34 +15,58 @@ import ( // XDG autostart entry, never by the window manager or the session's start as well. func TestItClaimsTheCompositorSeatAndRequiresTheXDisplay(t *testing.T) { - m := readManifest(t) - if m.Module != "picom" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-compositor", Scope: "node"}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "picom" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-compositor", Scope: "node"}}) { t.Fatalf("claims: %+v", m.Claims) } if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("requires: %v", m.Requires) } - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"picom", "xorg-xprop"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"picom", "xorg-xprop"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestItOwnsItsConfigurationAsWrittenInTheModule(t *testing.T) { - m := readManifest(t) - m.fromTemplate(t, "configuration", "files/picom.conf") - if p := m.resource(t, "configuration")["path"]; p != "${machine:account-home}/.config/picom/picom.conf" { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + fromTemplate(t, m, "configuration", "files/picom.conf") + if p := resource(t, m, "configuration")["path"]; p != "${machine:account-home}/.config/picom/picom.conf" { t.Fatalf("path: %v", p) } - if d := m.resource(t, "configuration-dir"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/picom" { + if d := resource(t, m, "configuration-dir"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/picom" { t.Fatalf("the directory: %v", d) } } func TestThePackagesAutostartEntryIsItsOnlyStart(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } // picom's package ships /etc/xdg/autostart/picom.desktop, which the session's dex runs. A second // start from here would be a second compositor, refused by the first. if m.Shell != nil { @@ -55,7 +83,15 @@ func TestThePackagesAutostartEntryIsItsOnlyStart(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } @@ -66,14 +102,22 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { // (novox/hq ADR 0348 §4): the backend a string of picom's backends, damage tracking a boolean, both trusted // as the file is. func TestTheBackendAndDamageTrackingAreConfigValuesWithTodaysDefaults(t *testing.T) { - m := readManifest(t) - b, d := m.Config["backend"], m.Config["use-damage"] + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + b, d := m.Settings["backend"], m.Settings["use-damage"] if b.Type != "string" || b.Default != "glx" || b.Description == "" || !b.Trusted || len(b.Enum) == 0 || d.Type != "boolean" || d.Default != true || d.Description == "" || !d.Trusted { - t.Fatalf("config: %+v", m.Config) + t.Fatalf("config: %+v", m.Settings) } - r := m.resource(t, "configuration") - c := m.text(t, "configuration") + r := resource(t, m, "configuration") + c := templateText(t, m, "configuration") for _, want := range []string{`backend = "${config:backend}";`, "use-damage = ${config:use-damage};"} { if !strings.Contains(c, want) { t.Errorf("the file asks for %q", want) @@ -98,5 +142,14 @@ func withDefaults(c string) string { // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/picom/module.json b/modules/picom/module.json index 31d53c43e..bc61080d1 100644 --- a/modules/picom/module.json +++ b/modules/picom/module.json @@ -1,6 +1,7 @@ { "module": "picom", "version": "0.1", + "class": "core", "capabilities": [ "package-manager" ], diff --git a/modules/polychromatic/cmd/polychromatic-tools/manifest_test.go b/modules/polychromatic/cmd/polychromatic-tools/manifest_test.go index aef16b5ba..da624adb4 100644 --- a/modules/polychromatic/cmd/polychromatic-tools/manifest_test.go +++ b/modules/polychromatic/cmd/polychromatic-tools/manifest_test.go @@ -1,13 +1,14 @@ package main import ( - "encoding/json" "os" "os/exec" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // polychromatic's shape (novox/hq ADR 0205, ADR 0208, ADR 0212): no package (the tray is outside the @@ -15,46 +16,17 @@ import ( // window manager's configuration that is the tray's one start, nothing of the openrazer module's, and // the Go bundle serving exactly the listed polychromatic_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Moved bool `json:"moved"` - Contributions []any `json:"contributions"` - Items []struct { - Collection string `json:"collection"` - Name string `json:"name"` - Template string `json:"template"` - } `json:"items"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestTheToolsAgreeWithTheManifest(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -75,8 +47,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/polychromatic-tools" || b["binary"] != "polychromatic-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/polychromatic-tools" || b.Binary != "polychromatic-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) @@ -88,11 +60,20 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { } func TestItDeclaresNoPackageAndContributesTheTraysOneStart(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) if m.Module != "polychromatic" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("%+v", m) } - if m.Resources != nil || m.Capabilities != nil || m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil { + if m.Resources != nil || m.Capabilities != nil || m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil { t.Fatal("no package (outside the official repositories), no seat, no environment, no xinitrc start") } var code []string @@ -118,7 +99,15 @@ func TestTheContributionParsesInI3(t *testing.T) { if err != nil { t.Skip("no i3 here to check with") } - m, _ := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } path := filepath.Join(t.TempDir(), "config") os.WriteFile(path, []byte("set $mod Mod4\n"+displayLines(t, m)), 0o644) if out, err := exec.Command(i3, "-C", "-c", path).CombinedOutput(); err != nil || strings.Contains(string(out), "ERROR") { @@ -128,7 +117,7 @@ func TestTheContributionParsesInI3(t *testing.T) { // displayLines is the module's lines for the window manager: the text of the template of its one item of the // collection contribution:node-display-session:config (design 57 L3, issue 848). -func displayLines(t *testing.T, m manifest) string { +func displayLines(t *testing.T, m catalogue.Manifest) string { t.Helper() if !m.Moved || len(m.Contributions) != 0 || len(m.Items) != 1 || m.Items[0].Collection != "contribution:node-display-session:config" { diff --git a/modules/polychromatic/module.json b/modules/polychromatic/module.json index b02d2a30f..8930b1469 100644 --- a/modules/polychromatic/module.json +++ b/modules/polychromatic/module.json @@ -1,6 +1,7 @@ { "module": "polychromatic", "version": "0.1", + "class": "leaf", "moved": true, "requires": [ "x11-display" diff --git a/modules/postgres/module.json b/modules/postgres/module.json index c441d7181..e41fab60c 100644 --- a/modules/postgres/module.json +++ b/modules/postgres/module.json @@ -1,6 +1,7 @@ { "module": "postgres", "version": "0.1", + "class": "core", "moved": true, "upgrade": { "policy": "record", diff --git a/modules/power/module.json b/modules/power/module.json index cf5b061bc..e4b54f8f4 100644 --- a/modules/power/module.json +++ b/modules/power/module.json @@ -1,6 +1,7 @@ { "module": "power", "version": "0.1", + "class": "core", "moved": true, "templates": "templates", "capabilities": [ diff --git a/modules/powerlevel10k/module.json b/modules/powerlevel10k/module.json index 72c4e0243..d719efb31 100644 --- a/modules/powerlevel10k/module.json +++ b/modules/powerlevel10k/module.json @@ -1,6 +1,7 @@ { "module": "powerlevel10k", "version": "0.1", + "class": "leaf", "moved": true, "resources": [ { diff --git a/modules/records/module.json b/modules/records/module.json index 3e23fe06d..a41fe6961 100644 --- a/modules/records/module.json +++ b/modules/records/module.json @@ -1,6 +1,7 @@ { "module": "records", "version": "0.1", + "class": "leaf", "slug": "records", "requires": [ "git" diff --git a/modules/redis/module.json b/modules/redis/module.json index 4a7c95998..357accec8 100644 --- a/modules/redis/module.json +++ b/modules/redis/module.json @@ -1,6 +1,7 @@ { "module": "redis", "version": "0.1", + "class": "leaf", "provides": [ { "name": "redis-cache", diff --git a/modules/restic/module.json b/modules/restic/module.json index 313d3e7de..1a006be0e 100644 --- a/modules/restic/module.json +++ b/modules/restic/module.json @@ -1,6 +1,7 @@ { "module": "restic", "version": "0.1", + "class": "core", "packages": { "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings": "0.1" }, @@ -261,7 +262,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ] diff --git a/modules/rofi/cmd/rofi-tools/manifest_helpers_test.go b/modules/rofi/cmd/rofi-tools/manifest_helpers_test.go index dff8ee962..6ed0e52eb 100644 --- a/modules/rofi/cmd/rofi-tools/manifest_helpers_test.go +++ b/modules/rofi/cmd/rofi-tools/manifest_helpers_test.go @@ -1,69 +1,15 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Moved bool `json:"moved"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - // Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here. - Items []item `json:"items"` - Contributions []any `json:"contributions"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -74,7 +20,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -90,9 +36,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -112,7 +58,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -121,10 +67,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -134,9 +80,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -149,7 +95,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -191,14 +137,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } @@ -223,7 +169,7 @@ const displaySession = "contribution:node-display-session:config" // i3Lines is what the module contributes to the window manager: the text of its item of the collection // contribution:node-display-session:config (design 57 L3, issue 848). -func (m manifest) i3Lines() string { +func i3Lines(m catalogue.Manifest) string { var out string for _, it := range m.Items { if it.Collection == displaySession { @@ -239,7 +185,7 @@ func (m manifest) i3Lines() string { // i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no // old-form contribution to node-display-session is left. -func (m manifest) i3LinesAreSource(t *testing.T, source string) { +func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) { t.Helper() if len(m.Contributions) != 0 { t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession) @@ -253,14 +199,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) { if len(templates) != 1 || templates[0] != source { t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source) } - if m.i3Lines() == "" { + if i3Lines(m) == "" { t.Fatalf("the template %s holds no line", source) } } - -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} diff --git a/modules/rofi/cmd/rofi-tools/manifest_test.go b/modules/rofi/cmd/rofi-tools/manifest_test.go index 36f12ec37..00cb25ade 100644 --- a/modules/rofi/cmd/rofi-tools/manifest_test.go +++ b/modules/rofi/cmd/rofi-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // rofi's shape (novox/hq ADR 0208, research 026/04): it claims node-launcher and serves its verb @@ -12,23 +16,39 @@ import ( // its own i3 drop-in. func TestItClaimsTheLauncherSeatServingMenuAndRequiresTheXDisplay(t *testing.T) { - m := readManifest(t) - if m.Module != "rofi" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-launcher", Scope: "node", Serves: []string{"menu", "secret"}}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "rofi" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-launcher", Scope: "node", Serves: []string{"menu", "secret"}}}) { t.Fatalf("claims: %+v", m.Claims) } if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("requires: %v", m.Requires) } - if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"rofi"}) || absent != nil { + if present, absent := packages(m); !reflect.DeepEqual(present, []string{"rofi"}) || absent != nil { t.Fatalf("packages: %v, absent %v", present, absent) } } func TestItOwnsItsFilesAsWrittenInTheModule(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } for id, source := range map[string]string{ "configuration": "files/config.rasi", "theme": "files/themes/mesh.rasi", @@ -37,39 +57,55 @@ func TestItOwnsItsFilesAsWrittenInTheModule(t *testing.T) { "launch": "files/bin/rofi-launch", "powermenu": "files/bin/rofi-powermenu", } { - m.fromTemplate(t, id, source) + fromTemplate(t, m, id, source) } for _, id := range []string{"dmenu", "launch", "powermenu"} { - if m.resource(t, id)["mode"] != "0755" { + if resource(t, m, id)["mode"] != "0755" { t.Errorf("%s is executable", id) } } - if p := m.resource(t, "dmenu")["path"]; p != "${machine:account-home}/.local/bin/dmenu" { + if p := resource(t, m, "dmenu")["path"]; p != "${machine:account-home}/.local/bin/dmenu" { t.Fatalf("the seat's command is dmenu on the account's PATH: %v", p) } } func TestTheThemesAreTheMeshsFacesAndTheConfigurationNamesOne(t *testing.T) { - m := readManifest(t) - conf := m.text(t, "configuration") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + conf := templateText(t, m, "configuration") if !strings.Contains(conf, `@theme "mesh"`) || strings.Contains(conf, "@import") { t.Fatal("the configuration names the theme mesh and imports nothing") } for _, id := range []string{"theme", "theme-powermenu"} { - c := m.text(t, id) + c := templateText(t, m, id) if !strings.Contains(c, `"JetBrainsMono Nerd Font`) || strings.Contains(c, "@import") || strings.Contains(c, "Hack") || strings.Contains(c, "Iosevka") { t.Errorf("%s: the monospace face, and no imported file", id) } } - if !strings.Contains(m.text(t, "theme"), `"Inter 11"`) { + if !strings.Contains(templateText(t, m, "theme"), `"Inter 11"`) { t.Error("the theme's prose is in the interface face") } } func TestThePowerMenuNamesNoWindowManagerAndNoLocker(t *testing.T) { - m := readManifest(t) - menu := m.text(t, "powermenu") + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + menu := templateText(t, m, "powermenu") for _, never := range []string{"i3-msg", "i3lock", "betterlockscreen", "openbox", "bspc", "qdbus", "mpc"} { if strings.Contains(menu, never) { t.Errorf("the power menu names %s", never) @@ -83,9 +119,17 @@ func TestThePowerMenuNamesNoWindowManagerAndNoLocker(t *testing.T) { } func TestTheKeyBindingsAreAnI3DropInRunningTheModulesOwnCommands(t *testing.T) { - m := readManifest(t) - m.i3LinesAreSource(t, "files/i3/50-rofi.conf") - bindings := m.i3Lines() + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + i3LinesAreSource(t, m, "files/i3/50-rofi.conf") + bindings := i3Lines(m) for _, line := range strings.Split(bindings, "\n") { if line == "" || strings.HasPrefix(line, "#") { continue @@ -105,12 +149,29 @@ func TestTheKeyBindingsAreAnI3DropInRunningTheModulesOwnCommands(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/rofi/module.json b/modules/rofi/module.json index 69e7a5f70..1bba3a54f 100644 --- a/modules/rofi/module.json +++ b/modules/rofi/module.json @@ -1,6 +1,7 @@ { "module": "rofi", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/route-adapter/module.json b/modules/route-adapter/module.json index 28bbfa869..ee7e27f74 100644 --- a/modules/route-adapter/module.json +++ b/modules/route-adapter/module.json @@ -1,6 +1,7 @@ { "module": "route-adapter", "version": "0.1", + "class": "leaf", "moved": true, "slug": "radapt", "capabilities": [ diff --git a/modules/screen-lock/cmd/screen-lock-tools/lock_test.go b/modules/screen-lock/cmd/screen-lock-tools/lock_test.go index 982793085..20ebfe049 100644 --- a/modules/screen-lock/cmd/screen-lock-tools/lock_test.go +++ b/modules/screen-lock/cmd/screen-lock-tools/lock_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" "time" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) const nobody = 4194400 @@ -185,8 +187,16 @@ func TestAnInhibitionTurnsIdleOffAndRestoresWhatWasThereWhenItEndsOrIsStopped(t } func TestTheDeclaredTimeoutsAreTheSessionStartsOwn(t *testing.T) { - m := readManifest(t) - code := m.shell(t)[0].Code + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + code := shell(t, m)[0].Code if !strings.Contains(code, "xset s "+strconv.Itoa(declaredLock)+" "+strconv.Itoa(declaredLock)+"\n") || !strings.Contains(code, "xset dpms "+strconv.Itoa(declaredStandby)+" "+strconv.Itoa(declaredSuspend)+" "+strconv.Itoa(declaredOff)+"\n") { t.Fatalf("the tools' declared values and the session start's disagree:\n%s", code) diff --git a/modules/screen-lock/cmd/screen-lock-tools/manifest_helpers_test.go b/modules/screen-lock/cmd/screen-lock-tools/manifest_helpers_test.go index fb992951b..b121bfa63 100644 --- a/modules/screen-lock/cmd/screen-lock-tools/manifest_helpers_test.go +++ b/modules/screen-lock/cmd/screen-lock-tools/manifest_helpers_test.go @@ -1,64 +1,19 @@ package main import ( - "encoding/json" "os" "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) -// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in -// every desktop module that carries it. - -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Moved bool `json:"moved"` - Items []item `json:"items"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Claims []claim `json:"claims"` - Seats []any `json:"seats"` - Tools []string `json:"tools"` - Environment *environment `json:"environment"` - Shell []shellCode `json:"shell"` - Resources []map[string]any `json:"resources"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -type claim struct { - Name string `json:"name"` - Scope string `json:"scope"` - Serves []string `json:"serves"` -} - -type environment struct { - Variables map[string]string `json:"variables"` - Path []map[string]any `json:"path"` -} - -type shellCode struct { - For string `json:"for"` - Slot string `json:"slot"` - Code string `json:"code"` -} - -// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest. -type item struct { - Collection string `json:"collection"` - Name string `json:"name"` - Attributes map[string]string `json:"attributes"` - Template string `json:"template"` -} - // shell is the code the module adds to a shell's or the session's start, read from the templates of its items of // the collections shell::, in the order they are declared. -func (m manifest) shell(t *testing.T) []shellCode { +func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode { t.Helper() - var out []shellCode + var out []catalogue.ShellCode for _, it := range m.Items { parts := strings.Split(it.Collection, ":") if len(parts) != 3 || parts[0] != "shell" { @@ -68,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode { if err != nil { t.Fatal(err) } - out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)}) + out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)}) } return out } // environmentOf is the variables the module sets, read from the templates of its items of the environment. -func (m manifest) environmentOf(t *testing.T) *environment { +func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment { t.Helper() - var env *environment + var env *catalogue.Environment for _, it := range m.Items { if it.Collection != "environment" || it.Attributes["kind"] != "variable" { continue @@ -86,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment { t.Fatal(err) } if env == nil { - env = &environment{Variables: map[string]string{}} + env = &catalogue.Environment{Variables: map[string]string{}} } env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n") } return env } -func readManifest(t *testing.T) manifest { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) - if err != nil { - t.Fatal(err) - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { - t.Fatalf("module.json: %v", err) - } - m.Environment = m.environmentOf(t) - return m -} - -func (m manifest) resource(t *testing.T, id string) map[string]any { +func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any { t.Helper() for _, r := range m.Resources { if r["id"] == id { @@ -120,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any { return nil } -func (m manifest) packages() (present, absent []string) { +func packages(m catalogue.Manifest) (present, absent []string) { for _, r := range m.Resources { if r["type"] == "package" { if r["absent"] == true { @@ -136,9 +75,9 @@ func (m manifest) packages() (present, absent []string) { // fromTemplate checks that a file resource takes its text from its template file in the module's // repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the // template is there. The readable file in the repository is the one place the machine's text is written. -func (m manifest) fromTemplate(t *testing.T, id, template string) { +func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) { t.Helper() - r := m.resource(t, id) + r := resource(t, m, id) if r["type"] != "file" { t.Fatalf("%s is a %v, not a file", id, r["type"]) } @@ -158,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) { // everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs // files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2). -func (m manifest) everyFileIsATemplate(t *testing.T) { +func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) { t.Helper() for _, r := range m.Resources { if _, inline := r["content"]; inline { @@ -167,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } packs := 0 for _, a := range m.Build.Artifacts { - if a["kind"] == "archive" && a["from"] == "files" { + if a.Kind == "archive" && a.From == "files" { packs++ - if a["name"] != "files" { - t.Errorf("the templates archive is named %v, not files", a["name"]) + if a.Name != "files" { + t.Errorf("the templates archive is named %v, not files", a.Name) } } } @@ -180,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) { } // text is the text a file resource places on the machine: its template file's. -func (m manifest) text(t *testing.T, id string) string { +func templateText(t *testing.T, m catalogue.Manifest, id string) string { t.Helper() - name, _ := m.resource(t, id)["template"].(string) + name, _ := resource(t, m, id)["template"].(string) if name == "" { t.Fatalf("resource %s names no template", id) } @@ -195,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string { // checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle // serves each seat verb the claims promise as ., and that the Go bundle is declared. -func checkTheToolsAgree(t *testing.T, m manifest) { +func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) { t.Helper() own, seat := map[string]bool{}, map[string]bool{} for _, tool := range tools() { @@ -237,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) { t.Errorf("the bundle serves %s, which no claim promises", name) } } - var bundle map[string]any + var bundle *catalogue.Artifact for _, a := range m.Build.Artifacts { - if a["kind"] == "bundle" { - bundle = a + if a.Kind == "bundle" { + bundle = &a } } - if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" || - bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" { + if bundle == nil || bundle.Language != "go" || bundle.System != "arch" || + bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" { t.Errorf("the Go tools bundle: %v", bundle) } } diff --git a/modules/screen-lock/cmd/screen-lock-tools/manifest_test.go b/modules/screen-lock/cmd/screen-lock-tools/manifest_test.go index 3934c73bc..03644b08b 100644 --- a/modules/screen-lock/cmd/screen-lock-tools/manifest_test.go +++ b/modules/screen-lock/cmd/screen-lock-tools/manifest_test.go @@ -1,9 +1,13 @@ package main import ( + "os" + "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // screen-lock's shape (novox/hq ADR 0208, research 026/04): it claims node-lock-screen serving lock, @@ -12,11 +16,19 @@ import ( // the timeouts once, from the session's start. The lock key is the window manager's. func TestItClaimsTheLockScreenSeatServingLockAndRequiresTheXDisplay(t *testing.T) { - m := readManifest(t) - if m.Module != "screen-lock" || m.Seats != nil { - t.Fatalf("module %q declares seats %v", m.Module, m.Seats) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-lock-screen", Scope: "node", Serves: []string{"lock"}}}) { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if m.Module != "screen-lock" || m.DefinesSeats != nil { + t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats) + } + if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-lock-screen", Scope: "node", Serves: []string{"lock"}}}) { t.Fatalf("claims: %+v", m.Claims) } if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { @@ -25,17 +37,25 @@ func TestItClaimsTheLockScreenSeatServingLockAndRequiresTheXDisplay(t *testing.T } func TestTheColourBuildIsKeptWithAFallbackAndXscreensaverGoes(t *testing.T) { - m := readManifest(t) - present, absent := m.packages() + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + present, absent := packages(m) if !reflect.DeepEqual(present, []string{"xss-lock", "i3lock"}) || !reflect.DeepEqual(absent, []string{"xscreensaver"}) { t.Fatalf("packages: %v, absent %v", present, absent) } - m.fromTemplate(t, "wrapper", "files/bin/screen-lock") - wrapper := m.resource(t, "wrapper") + fromTemplate(t, m, "wrapper", "files/bin/screen-lock") + wrapper := resource(t, m, "wrapper") if wrapper["mode"] != "0755" || wrapper["path"] != "${machine:account-home}/.local/bin/screen-lock" { t.Fatalf("the locker: %v", wrapper) } - c := m.text(t, "wrapper") + c := templateText(t, m, "wrapper") // The colour build's options only once it has said it is the colour build: the distribution's // i3lock refuses an option it does not know, and the screen would not lock at all. check := strings.Index(c, `i3lock --version 2>&1 | grep -qE '[0-9]\.c\.[0-9]'`) @@ -52,11 +72,19 @@ func TestTheColourBuildIsKeptWithAFallbackAndXscreensaverGoes(t *testing.T) { } func TestTheSessionStartSetsTheTimeoutsAndKeepsOneWatcherForTheSession(t *testing.T) { - m := readManifest(t) - if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" { - t.Fatalf("one xinitrc contribution in normal: %+v", m.shell(t)) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) } - code := m.shell(t)[0].Code + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" { + t.Fatalf("one xinitrc contribution in normal: %+v", shell(t, m)) + } + code := shell(t, m)[0].Code if strings.Count(code, "xss-lock --") != 1 || !strings.Contains(code, "--transfer-sleep-lock") || !strings.Contains(code, "while kill -0 $$") || !strings.HasSuffix(strings.TrimSpace(code), "&") { t.Fatalf("the watcher: %q", code) @@ -72,7 +100,15 @@ func TestTheSessionStartSetsTheTimeoutsAndKeepsOneWatcherForTheSession(t *testin } func TestTheLockKeyIsTheWindowManagersNotThisModules(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } // The i3 module binds $mod+Delete to logind's lock, which names no locker; a binding here as well // would be i3's duplicate. for _, r := range m.Resources { @@ -83,12 +119,29 @@ func TestTheLockKeyIsTheWindowManagersNotThisModules(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } checkTheToolsAgree(t, m) checkNoSecretsOrInstallationNames(t) } // No file resource carries its text inline (novox/hq ADR 0349 §2). func TestEveryFileTakesItsTextFromATemplate(t *testing.T) { - readManifest(t).everyFileIsATemplate(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + everyFileIsATemplate(t, m) } diff --git a/modules/screen-lock/module.json b/modules/screen-lock/module.json index e73e79230..5f184f289 100644 --- a/modules/screen-lock/module.json +++ b/modules/screen-lock/module.json @@ -1,6 +1,7 @@ { "module": "screen-lock", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/searxng/module.json b/modules/searxng/module.json index d066a5cfb..14add9c82 100644 --- a/modules/searxng/module.json +++ b/modules/searxng/module.json @@ -1,6 +1,7 @@ { "module": "searxng", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/sensors/module.json b/modules/sensors/module.json index d029e350d..79a476d6f 100644 --- a/modules/sensors/module.json +++ b/modules/sensors/module.json @@ -1,6 +1,7 @@ { "module": "sensors", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/showcase/module.json b/modules/showcase/module.json index 7152479c7..06fea3efc 100644 --- a/modules/showcase/module.json +++ b/modules/showcase/module.json @@ -1,6 +1,7 @@ { "module": "showcase", "version": "0.1", + "class": "core", "templates": "templates", "slug": "show", "capabilities": [ diff --git a/modules/slack/cmd/slack-tools/manifest_test.go b/modules/slack/cmd/slack-tools/manifest_test.go index 01c43d747..4ccabe8a6 100644 --- a/modules/slack/cmd/slack-tools/manifest_test.go +++ b/modules/slack/cmd/slack-tools/manifest_test.go @@ -1,12 +1,13 @@ package main import ( - "encoding/json" "os" "path/filepath" "reflect" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // slack's shape (novox/hq ADR 0208, ADR 0210, ADR 0212, ADR 0182): no package (Slack comes from the @@ -14,46 +15,17 @@ import ( // its own machine; one contribution to node-display-session that is both Slack's one start and its // window rules; and the Go bundle serving exactly the listed slack_ tools. -type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Capabilities []string `json:"capabilities"` - Requires []string `json:"requires"` - Tools []string `json:"tools"` - Resources []map[string]any `json:"resources"` - Claims []any `json:"claims"` - Seats []any `json:"seats"` - Shell []any `json:"shell"` - Moved bool `json:"moved"` - Contributions []any `json:"contributions"` - Items []struct { - Collection string `json:"collection"` - Name string `json:"name"` - Template string `json:"template"` - } `json:"items"` - Environment any `json:"environment"` - Build struct { - Artifacts []map[string]any `json:"artifacts"` - } `json:"build"` -} - -func readManifest(t *testing.T) (manifest, string) { - t.Helper() - raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) +func TestItInstallsNothingAndOwnsNoFile(t *testing.T) { + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { t.Fatal(err) } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - var m manifest - if err := dec.Decode(&m); err != nil { + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { t.Fatalf("module.json: %v", err) } - return m, string(raw) -} - -func TestItInstallsNothingAndOwnsNoFile(t *testing.T) { - m, raw := readManifest(t) + raw := string(manifestJSON) if m.Module != "slack" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) { t.Fatalf("%+v", m) } @@ -61,7 +33,7 @@ func TestItInstallsNothingAndOwnsNoFile(t *testing.T) { if m.Resources != nil || m.Capabilities != nil { t.Fatalf("no package, no file: %v %v", m.Resources, m.Capabilities) } - if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil { + if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil { t.Fatal("it holds no seat, sets no environment and adds no session code") } // Slack's own setting writes ~/.config/autostart/slack.desktop (a link): never the module's. @@ -73,7 +45,15 @@ func TestItInstallsNothingAndOwnsNoFile(t *testing.T) { } func TestTheOneContributionIsTheStartAndTheWindowRules(t *testing.T) { - m, _ := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } content := displayLines(t, m) if !strings.HasSuffix(content, "\n") { t.Fatalf("%q", content) @@ -121,7 +101,16 @@ func TestTheOneContributionIsTheStartAndTheWindowRules(t *testing.T) { } func TestTheToolsAgreeWithTheManifest(t *testing.T) { - m, raw := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } + raw := string(manifestJSON) served := map[string]bool{} for _, tool := range tools() { served[tool.Name] = true @@ -142,8 +131,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { t.Fatalf("%v", m.Build.Artifacts) } b := m.Build.Artifacts[0] - if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" || - b["from"] != "cmd/slack-tools" || b["binary"] != "slack-tools" { + if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" || + b.From != "cmd/slack-tools" || b.Binary != "slack-tools" { t.Errorf("the Go tools bundle: %v", b) } s := strings.ToLower(raw) @@ -156,7 +145,7 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) { // displayLines is the module's lines for the window manager: the text of the template of its one item of the // collection contribution:node-display-session:config (design 57 L3, issue 848). -func displayLines(t *testing.T, m manifest) string { +func displayLines(t *testing.T, m catalogue.Manifest) string { t.Helper() if !m.Moved || len(m.Contributions) != 0 || len(m.Items) != 1 || m.Items[0].Collection != "contribution:node-display-session:config" { diff --git a/modules/slack/cmd/slack-tools/slack_test.go b/modules/slack/cmd/slack-tools/slack_test.go index 04296b5f3..3a5d72bf7 100644 --- a/modules/slack/cmd/slack-tools/slack_test.go +++ b/modules/slack/cmd/slack-tools/slack_test.go @@ -7,6 +7,8 @@ import ( "path/filepath" "strings" "testing" + + "git.novox.be/novox/mesh-sdk/go/catalogue" ) // Slack's settings as Slack writes them, with keys no answer may carry. @@ -108,7 +110,15 @@ func newSlack(t *testing.T) (*fake, map[string]string) { } func contribution(t *testing.T) string { - m, _ := readManifest(t) + manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json")) + if err != nil { + t.Fatal(err) + } + // manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside. + m, err := catalogue.Decode(manifestJSON) + if err != nil { + t.Fatalf("module.json: %v", err) + } return displayLines(t, m) } diff --git a/modules/slack/module.json b/modules/slack/module.json index 7736b3a1e..f791e2451 100644 --- a/modules/slack/module.json +++ b/modules/slack/module.json @@ -1,6 +1,7 @@ { "module": "slack", "version": "0.1", + "class": "leaf", "moved": true, "requires": [ "x11-display" diff --git a/modules/snapd/module.json b/modules/snapd/module.json index e0049a7fc..cd5ecd1d3 100644 --- a/modules/snapd/module.json +++ b/modules/snapd/module.json @@ -1,6 +1,7 @@ { "module": "snapd", "version": "0.1", + "class": "leaf", "tools": [ "snapd_status", "snapd_list", diff --git a/modules/ssh-client/module.json b/modules/ssh-client/module.json index 933b64acb..c4f8c3a91 100644 --- a/modules/ssh-client/module.json +++ b/modules/ssh-client/module.json @@ -1,6 +1,7 @@ { "module": "ssh-client", "version": "0.1", + "class": "leaf", "moved": true, "tools": [ "ssh_client_hosts", diff --git a/modules/sshd/module.json b/modules/sshd/module.json index c8bd15edd..b799d5a87 100644 --- a/modules/sshd/module.json +++ b/modules/sshd/module.json @@ -1,6 +1,7 @@ { "module": "sshd", "version": "0.1", + "class": "leaf", "upgrade": { "policy": "record", "why": "the operator's way into the machine when the mesh cannot reach it: a build that breaks it is found only when that way is needed, which no gate sees (hq ADR 0236)" diff --git a/modules/step-ca/module.json b/modules/step-ca/module.json index 0656bdfa8..887945e1f 100644 --- a/modules/step-ca/module.json +++ b/modules/step-ca/module.json @@ -1,6 +1,7 @@ { "module": "step-ca", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/sudo/module.json b/modules/sudo/module.json index 5b84c2a6e..019d9f992 100644 --- a/modules/sudo/module.json +++ b/modules/sudo/module.json @@ -1,6 +1,7 @@ { "module": "sudo", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/supabase/module.json b/modules/supabase/module.json index 64141d342..e67fad8e2 100644 --- a/modules/supabase/module.json +++ b/modules/supabase/module.json @@ -1,6 +1,7 @@ { "module": "supabase", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/systemd-networkd/module.json b/modules/systemd-networkd/module.json index e906eee0a..5c0e60f68 100644 --- a/modules/systemd-networkd/module.json +++ b/modules/systemd-networkd/module.json @@ -1,6 +1,7 @@ { "module": "systemd-networkd", "version": "0.1", + "class": "core", "upgrade": { "policy": "record", "why": "the machine's network: a build that breaks it can cut the machine off from the bus, and then neither the gate's rollback nor a push reaches it (hq ADR 0236)" diff --git a/modules/systemd-resolved/module.json b/modules/systemd-resolved/module.json index 93e3e2775..1e43e9f5b 100644 --- a/modules/systemd-resolved/module.json +++ b/modules/systemd-resolved/module.json @@ -1,6 +1,7 @@ { "module": "systemd-resolved", "version": "0.2", + "class": "core", "upgrade": { "policy": "record", "why": "the machine's names: a build that breaks this resolver stops every name resolving on a machine a person works on, the bus's included, and then neither the gate's rollback nor a push reaches it (hq ADR 0236, ADR 0247)" diff --git a/modules/systemd/module.json b/modules/systemd/module.json index a2c492a17..2f3cff730 100644 --- a/modules/systemd/module.json +++ b/modules/systemd/module.json @@ -1,6 +1,7 @@ { "module": "systemd", "version": "0.1", + "class": "core", "capabilities": [ "service-manager", "package-manager" diff --git a/modules/telegram/module.json b/modules/telegram/module.json index a333cfce8..22304d74c 100644 --- a/modules/telegram/module.json +++ b/modules/telegram/module.json @@ -1,6 +1,7 @@ { "module": "telegram", "version": "0.1", + "class": "core", "slug": "tgrm", "runs-as": "telegram", "claims": [ diff --git a/modules/time-sync/module.json b/modules/time-sync/module.json index ba4f1cf53..de09c9e59 100644 --- a/modules/time-sync/module.json +++ b/modules/time-sync/module.json @@ -1,6 +1,7 @@ { "module": "time-sync", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager", "service-manager" diff --git a/modules/triggerhappy/module.json b/modules/triggerhappy/module.json index bbc84be9e..babb95e7b 100644 --- a/modules/triggerhappy/module.json +++ b/modules/triggerhappy/module.json @@ -1,6 +1,7 @@ { "module": "triggerhappy", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "service-manager" diff --git a/modules/umami/module.json b/modules/umami/module.json index eb8df76e3..d1c618a88 100644 --- a/modules/umami/module.json +++ b/modules/umami/module.json @@ -1,6 +1,7 @@ { "module": "umami", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/unifi/module.json b/modules/unifi/module.json index 67348a912..c9f09c7e5 100644 --- a/modules/unifi/module.json +++ b/modules/unifi/module.json @@ -1,6 +1,7 @@ { "module": "unifi", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/website/module.json b/modules/website/module.json index b65fb187a..07970c19e 100644 --- a/modules/website/module.json +++ b/modules/website/module.json @@ -1,6 +1,7 @@ { "module": "website", "version": "0.1", + "class": "leaf", "capabilities": [ "container-runtime" ], diff --git a/modules/xclip/module.json b/modules/xclip/module.json index 9c0829670..a094b45ed 100644 --- a/modules/xclip/module.json +++ b/modules/xclip/module.json @@ -1,6 +1,7 @@ { "module": "xclip", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/xdg/module.json b/modules/xdg/module.json index f9afd0214..72b0650a2 100644 --- a/modules/xdg/module.json +++ b/modules/xdg/module.json @@ -1,6 +1,7 @@ { "module": "xdg", "version": "0.1", + "class": "leaf", "capabilities": [ "package-manager" ], diff --git a/modules/xorg/module.json b/modules/xorg/module.json index 72ea858d5..26550fec3 100644 --- a/modules/xorg/module.json +++ b/modules/xorg/module.json @@ -1,6 +1,7 @@ { "module": "xorg", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager", diff --git a/modules/xterm/module.json b/modules/xterm/module.json index def76a72d..195510057 100644 --- a/modules/xterm/module.json +++ b/modules/xterm/module.json @@ -1,6 +1,7 @@ { "module": "xterm", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/zfs/cmd/zfs-tools/keeper.go b/modules/zfs/cmd/zfs-tools/keeper.go index d4be817d1..399487826 100644 --- a/modules/zfs/cmd/zfs-tools/keeper.go +++ b/modules/zfs/cmd/zfs-tools/keeper.go @@ -328,6 +328,11 @@ func (c keeperClient) exchange(r KeeperRequest) (a KeeperAnswer, err error, unan defer conn.Close() _ = conn.SetDeadline(time.Now().Add(KeeperTimeout)) if err := json.NewEncoder(conn).Encode(r); err != nil { + // A keeper that refuses the peer answers and closes without reading, so the write can meet a closed socket + // (broken pipe) while the refusal already waits to be read: the refusal is the answer (issue 1960). + if derr := json.NewDecoder(conn).Decode(&a); derr == nil && a.Error != "" { + return a, errors.New(a.Error), false + } return KeeperAnswer{}, err, true } if err := json.NewDecoder(conn).Decode(&a); err != nil { diff --git a/modules/zfs/cmd/zfs-tools/keeper_test.go b/modules/zfs/cmd/zfs-tools/keeper_test.go index 6b6508917..5d36d1d39 100644 --- a/modules/zfs/cmd/zfs-tools/keeper_test.go +++ b/modules/zfs/cmd/zfs-tools/keeper_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" ) @@ -91,10 +92,12 @@ func shortTempDir(prefix string) (string, error) { // keeper answering it acts as with the bus down, with a warning (A-8). func TestOnlyRootOpensTheKeepersSocketAndANeedlessKeeperIsTheBusDown(t *testing.T) { st := memStates{} - uid := 0 + // The peer's uid is read by the keeper's serving goroutines and switched by the test: an atomic, so no connection + // sees it half-written (issue 1960: a data race failed the test under -race). + var uid atomic.Int32 k := &Keeper{Emit: func(string, any) error { return nil }, States: st, Call: func(string, any) (json.RawMessage, error) { return nil, errors.New("down") }, - PeerOf: func(net.Conn) (int, error) { return uid, nil }} + PeerOf: func(net.Conn) (int, error) { return int(uid.Load()), nil }} dir, err := shortTempDir("zk") if err != nil { t.Fatal(err) @@ -121,13 +124,21 @@ func TestOnlyRootOpensTheKeepersSocketAndANeedlessKeeperIsTheBusDown(t *testing. if _, err := c.call(ToolSchedule, map[string]any{}); err == nil || !strings.Contains(err.Error(), "down") { t.Errorf("an invoke that failed: %v", err) } - uid = 1000 + uid.Store(1000) if err := c.Put(StateSchedule, "x", 1); err == nil || !strings.Contains(err.Error(), "only root") { t.Errorf("a peer that is not root: %v", err) } + // A request larger than the socket's buffer: the keeper refuses and closes before it is written whole, so the write + // meets a closed socket every time; the peer is still told it is not root (issue 1960). + if err := c.Put(StateSchedule, "y", strings.Repeat("x", 1<<20)); err == nil || !strings.Contains(err.Error(), "only root") { + t.Errorf("a peer that is not root, its write cut: %v", err) + } if _, left := st["schedule/x"]; left { t.Errorf("a refused peer's call was read") } + if _, left := st["schedule/y"]; left { + t.Errorf("a refused peer's cut call was read") + } // No socket variable: the machine keeps no bus and says so. t.Setenv(KeeperSocketEnv, "") m := newFake(t).machine() @@ -151,6 +162,8 @@ func TestOnlyRootOpensTheKeepersSocketAndANeedlessKeeperIsTheBusDown(t *testing. if err != nil { t.Fatal(err) } + // The socket is bound before the call below, so the call waits in its backlog until Serve accepts it: the keeper + // is up from the moment Listen returns, whenever its goroutine runs. lctx, lcancel := context.WithCancel(context.Background()) defer lcancel() go (&Keeper{Emit: func(string, any) error { return nil }, States: memStates{}, PeerOf: func(net.Conn) (int, error) { return 0, nil }, @@ -159,7 +172,7 @@ func TestOnlyRootOpensTheKeepersSocketAndANeedlessKeeperIsTheBusDown(t *testing. t.Errorf("a keeper that came up later is not used: %v", err) } t.Setenv(KeeperSocketEnv, sock) - uid = 0 + uid.Store(0) m2 := newFake(t).machine() m2.JoinBus() if m2.Emit == nil || m2.States == nil || m2.Call == nil || m2.keeper == nil { diff --git a/modules/zfs/module.json b/modules/zfs/module.json index 072a3f285..9e41b0586 100644 --- a/modules/zfs/module.json +++ b/modules/zfs/module.json @@ -1,6 +1,7 @@ { "module": "zfs", "version": "0.1", + "class": "leaf", "capabilities": [ "bus-state-calls", "ledger-calls", @@ -118,7 +119,7 @@ "findings-stated.*" ], "max-age-days": 7, - "max-mib": 16 + "max-mib": 8 } } ], diff --git a/modules/zsh-autosuggestions/module.json b/modules/zsh-autosuggestions/module.json index b4702085c..16415c596 100644 --- a/modules/zsh-autosuggestions/module.json +++ b/modules/zsh-autosuggestions/module.json @@ -1,6 +1,7 @@ { "module": "zsh-autosuggestions", "version": "0.1", + "class": "leaf", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/zsh-syntax-highlighting/module.json b/modules/zsh-syntax-highlighting/module.json index 4e4ea24a0..8fa4c1cb4 100644 --- a/modules/zsh-syntax-highlighting/module.json +++ b/modules/zsh-syntax-highlighting/module.json @@ -1,6 +1,7 @@ { "module": "zsh-syntax-highlighting", "version": "0.1", + "class": "leaf", "moved": true, "capabilities": [ "package-manager" diff --git a/modules/zsh/module.json b/modules/zsh/module.json index 028f2213d..c4bbfb570 100644 --- a/modules/zsh/module.json +++ b/modules/zsh/module.json @@ -1,6 +1,7 @@ { "module": "zsh", "version": "0.1", + "class": "core", "moved": true, "capabilities": [ "package-manager"