package view import ( "bufio" "bytes" "context" "encoding/json" "fmt" "maps" "net/http" "net/http/httptest" "slices" "strings" "sync" "testing" "time" "git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient" "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" ) // fakeRunner answers the seat mesh-pipeline-runner's list and show as the runner's process does, from rows and pipelines // the test sets; it counts the lists asked. type fakeRunner struct { mu sync.Mutex rows map[string][]seat.PipelineRow // by branch shows map[string]seat.ShowAnswer // by pipeline, or pipeline/mover steps map[string][]seat.StepResult // by pipeline, every mover's steps, which show filtered by a step answers two a page lists int } func (f *fakeRunner) call(key string, body any) (json.RawMessage, error) { f.mu.Lock() defer f.mu.Unlock() switch key { case PipelinesListVerb: in := body.(seat.ListInput) if in.Limit < 1 || in.Full { return nil, fmt.Errorf("list asked with limit %d, full %v", in.Limit, in.Full) } f.lists++ rows := f.rows[in.Branch] if in.Branch == "" { // every branch's, each row naming its branch, newest first (design 47 H2 H-A-533) rows = nil for _, b := range slices.Sorted(maps.Keys(f.rows)) { for _, r := range f.rows[b] { carries := in.Module == "" for _, mv := range f.shows[r.Pipeline].Pipeline.Movers { carries = carries || mv.Module == in.Module } if r.Branch = b; carries { rows = append(rows, r) } } } slices.SortStableFunc(rows, func(a, b seat.PipelineRow) int { return int(b.Revision - a.Revision) }) } return json.Marshal(seat.ListAnswer{Rows: rows[:min(int(in.Limit), len(rows))]}) case PipelinesShowVerb: in := body.(seat.ShowInput) if in.Step != "" { a := f.shows[in.Pipeline] var held []seat.StepResult for _, s := range f.steps[in.Pipeline] { if s.Step == in.Step { held = append(held, s) } } from := 0 fmt.Sscan(in.Next, &from) a.Pipeline.Steps = held[min(from, len(held)):min(from+2, len(held))] if a.Next = ""; from+2 < len(held) { a.Next = fmt.Sprint(from + 2) } return json.Marshal(a) } k := in.Pipeline if in.Mover != "" { k += "/" + in.Mover } a, ok := f.shows[k] if !ok { return json.Marshal(map[string]any{"isError": true, "content": []map[string]string{{"type": "text", "text": "no pipeline " + k}}}) } return json.Marshal(a) } return nil, fmt.Errorf("the runner serves no %s", key) } func (f *fakeRunner) setRows(branch string, rows ...seat.PipelineRow) { f.mu.Lock() defer f.mu.Unlock() f.rows[branch] = rows } // The builds of the pipeline's movers, in the new form a want names. var ( fpA = "src2:" + strings.Repeat("a", 64) fpB = "src2:" + strings.Repeat("b", 64) fpB0 = "src2:" + strings.Repeat("0", 64) ) // changedWithin is p.Changed bounded, so a change never said fails the test instead of hanging it. func changedWithin(ctx context.Context, p *Pipelines, what string, since uint64) bool { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() return p.Changed(ctx, what, since) } // Design 47 H2 H-A-467, H-A-531: the pipelines page reads the runner's list and show, refreshes on its events and on the wants' // and haves', never on a timer, shows one pipeline by tier and stage with its nodes, and links each delivery to its pipeline. func TestThePipelinesPage(t *testing.T) { started, ended := t0, t0.Add(3*60e9) taken := t0.Add(160e9) // a build node took the step 2m40s after its ask, and it ran 20s (design 47 H2 H-A-516) runner := &fakeRunner{rows: map[string][]seat.PipelineRow{}, shows: map[string]seat.ShowAnswer{ "main.12": {Pipeline: seat.Pipeline{Pipeline: "main.12", Branch: "main", Source: 9, Revision: 12, Outcome: seat.PipelineOutcomeFailed, Started: &started, Ended: &ended, Movers: []seat.Mover{{Module: "alpha", Fingerprint: fpA, Version: "0.1.4", Tier: 1}, {Module: "beta", Fingerprint: fpB, Tier: 2}, {Module: "gamma", Fingerprint: fpNew, Tier: 2}, {Module: "delta", Fingerprint: fpOld}}}, Movers: []seat.MoverRow{{Module: "alpha", Outcome: seat.MoverRowOutcomePassed}, {Module: "beta", Outcome: seat.MoverRowOutcomeFailed, Failed: &seat.FailedStep{Step: "unit", Artifact: "beta:program", Outcome: "could not run", Why: "no build node"}}, {Module: "gamma", Outcome: seat.MoverRowOutcomePassed}, {Module: "delta", Outcome: seat.MoverRowOutcomePassed}}}, "main.12/beta": {Pipeline: seat.Pipeline{Pipeline: "main.12", Branch: "main", Source: 9, Revision: 12, Outcome: seat.PipelineOutcomeFailed, Steps: []seat.StepResult{{Module: "beta", Step: "unit", Artifact: "beta:program", Seat: "node-build-go", Node: "n1", Outcome: "could not run", AskedAt: &started, Started: &started, TakenAt: &taken, Ended: &ended, Why: "no build node"}, {Module: "beta", Step: "lint", Artifact: "beta:program", Seat: "node-build-go", Outcome: "could not run", AskedAt: &started, Ended: &ended}}}}, }, steps: map[string][]seat.StepResult{"main.12": { {Module: "alpha", Step: "build", Artifact: "alpha:program", Outcome: "passed"}, {Module: "alpha", Step: "build", Artifact: "alpha:image", Outcome: "carried"}, {Module: "alpha", Step: "build", Artifact: "alpha:tool", Outcome: "passed"}, {Module: "alpha", Step: "review", Outcome: "passed"}, {Module: "beta", Step: "unit", Artifact: "beta:program", Node: "n1", Outcome: "could not run", AskedAt: &started, TakenAt: &taken, Ended: &ended, Why: "no build node"}, {Module: "beta", Step: "unit", Artifact: "beta:tool", Outcome: "passed"}, {Module: "beta", Step: "approval", Outcome: "waiting", Why: "a person"}}}} runner.setRows("main", seat.PipelineRow{Pipeline: "main.12", Source: 9, Revision: 12, Started: &started, Outcome: seat.PipelineOutcomeFailed, MoverCount: 2, Steps: map[string]int64{"passed": 5, "failed": 1, "could not run": 1, "waiting for a build node": 2}}) runner.setRows(testBranch, seat.PipelineRow{Pipeline: "release.8", Source: 4, Revision: 8, Outcome: seat.PipelineOutcomePassed}, seat.PipelineRow{Pipeline: "release.7", Source: 4, Revision: 7, Outcome: seat.PipelineOutcomeSuperseded}) p := NewPipelines(runner.call, func() []string { return []string{testBranch} }, 0, nil) m := New(testView) fill(m, sourceE(t, 4)) // alpha runs its build on both its nodes; beta is wanted on n1, applying on n2 and has no want on n3; gamma's build failed // its health on n1 and the assigner holds it; delta is placed on no node (design 47 H2 H-A-531 and its addendum). applying, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: fpB0, Phase: nodeengineclient.PhaseApplying, Health: nodeengineclient.HealthWaits}) sick, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: fpNew, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthFailed, Detail: "connection refused"}) delivery := []Entry{place(t, "n1", "alpha", "beta", "gamma"), place(t, "n2", "alpha", "beta", "gamma"), place(t, "n3", "beta"), haveFP(t, "n1", "alpha", fpA, nodeengineclient.HealthOK), haveFP(t, "n2", "alpha", fpA, nodeengineclient.HealthOK), wantE(t, "n1", "beta", meshwantsclient.Want{Fp: fpB}), wantE(t, "n2", "beta", meshwantsclient.Want{Fp: fpB}), haveE(t, "n2", "beta", applying, t0), wantE(t, "n1", "gamma", meshwantsclient.Want{Fp: fpNew}), haveE(t, "n1", "gamma", sick, t0), heldE(t, "gamma", fpNew, "n1", "health failed on n1")} fill(m, delivery...) m.SetPipelines(p) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go p.Run(ctx) if !changedWithin(ctx, p, "", 0) { // the first reading at the start t.Fatal("the lists were never read") } web := func(path string) string { rec := httptest.NewRecorder() Web(m).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) if rec.Code != 200 { t.Fatalf("%s = %d %s", path, rec.Code, rec.Body.String()) } return rec.Body.String() } text := func(f func(*bytes.Buffer)) string { var b bytes.Buffer f(&b) return strings.Join(strings.Fields(b.String()), " ") } rows := []struct { name string got func() string want []string }{ {"the terminal view's list counts the steps per outcome", func() string { return text(func(b *bytes.Buffer) { PipelinesTable(b, p.Page("", 0)) }) }, []string{"PIPELINES PIPELINE BRANCH REVISION", "PASSED FAILED COULD NOT RUN NOT ASKED WAITING WAITING FOR A BUILD NODE BYPASSED NOTHING TO RUN", "main.12 main 12 9 2026-10-18", "release.8 release 8 4", "failed 2 5 1 1 0 0 2 0 0"}}, {"the web list links each pipeline and reloads on the view's changes, never a timer", func() string { return web("/pipelines") }, []string{ `main.12`, `new EventSource("/pipelines/changes?since=`}}, {"a pipeline's page is its header, then a block per tier, a row per mover with a cell per stage and per node", func() string { return web("/pipelines/show?pipeline=main.12") }, []string{ "failed; first failure: unit beta:program: could not run: no build node; 1 of 4 movers run their build on every node they are placed on; 1 is placed on none", "

TIER 1

", "MOVEROUTCOMEBUILDLINTUNITINTEGRATIONVALIDATECOMPOSITIONCODE REVIEWAPPROVALn1n2n3", `alphapassedpassed`, `running the pipeline's buildrunning the pipeline's build`, `could not run 1/2", `waiting`, `wantedapplyingno want written`, `held: connection refusedheld: health failed on n1`, "

TIER 2

", `changes?pipeline=main.12\u0026since=`}}, {"a stage's worst outcome follows the runner's step words, an unknown one counting as failed", func() string { at := func(o ...string) string { var ss []seat.StepResult for _, x := range o { ss = append(ss, seat.StepResult{Step: "unit", Outcome: x}) } return stageCell(ss, t0).Text() } return strings.Join([]string{at("passed", "running", "waiting for a build node", "not asked", "running"), at("cancelled", "could not run"), at("frobbed", "passed"), at("running", "running"), at("nothing to run"), at("failed", "passed", "carried"), at()}, "|") }, []string{"not asked 1/5|could not run 1/2|frobbed 1/2|running|nothing to run|failed 1/3|"}}, {"a mover's page is its steps, each asked, taken and ended, how long it waited and how long it ran", func() string { return web("/pipelines/show?pipeline=main.12&mover=beta") }, []string{"ASKEDTAKENENDEDWAITEDRAN", "unit beta:programnode-build-gon1could not run" + since(started) + "" + since(taken) + "" + since(ended) + "2m40s20sno build node", "lint beta:programnode-build-gocould not run" + since(started) + "" + since(ended) + "3m0s"}}, {"the terminal view's mover splits each step's waiting from its running", func() string { a, err := p.Show("main.12", "beta", "") if err != nil { return err.Error() } return text(func(b *bytes.Buffer) { PipelineTable(b, PipelineAnswer{ShowAnswer: a}, "beta") }) }, []string{"STEPS OF beta", "OUTCOME ASKED TAKEN ENDED WAITED RAN WHY", "could not run " + since(started) + " " + since(taken) + " " + since(ended) + " 2m40s 20s no build node"}}, {"a step still waiting counts its wait to now, one running its run", func() string { now := t0.Add(400e9) w1, r1 := waitedRan(seat.StepResult{AskedAt: &started}, now) w2, r2 := waitedRan(seat.StepResult{AskedAt: &started, TakenAt: &taken}, now) w3, r3 := waitedRan(seat.StepResult{Ended: &ended}, now) return fmt.Sprintf("waiting %s/%s; running %s/%s; never asked %q/%q", w1, r1, w2, r2, w3, r3) }, []string{`waiting 6m40s/; running 2m40s/4m0s; never asked ""/""`}}, {"the terminal view's pipeline is its header and a block per tier, as the page's", func() string { path, sm := served(t) fill(sm, delivery...) sm.SetPipelines(p) var got *PipelineAnswer if err := AskPipelines(path, "", 0, "main.12", "", "", false, func(_ PipelinesPage, a *PipelineAnswer) bool { got = a; return true }); err != nil { return err.Error() } return text(func(b *bytes.Buffer) { PipelineTable(b, *got, "") }) }, []string{"PIPELINE main.12: failed; first failure: unit beta:program: could not run: no build node; 1 of 4 movers", "TIER 1 MOVER OUTCOME BUILD LINT UNIT INTEGRATION VALIDATE COMPOSITION CODE REVIEW APPROVAL N1 N2 N3", "alpha passed passed - - - - - passed - running the pipeline's build running the pipeline's build -", "delta passed - - - - - - - - - - -", "TIER 2", "beta failed - - could not run 1/2 - - - - waiting wanted applying no want written", "gamma passed - - - - - - - - held: connection refused held: health failed on n1 -"}}, {"the web list asks the newest limit of every branch", func() string { return web("/pipelines?limit=1") }, []string{ "main.12", `name="limit" value="1"`}}, {"the web list is every branch's newest 20 by default, the branch a column", func() string { return web("/pipelines") }, []string{ "

PIPELINES

", `module `, "BRANCH", "main.12main", "release.8release", "release.7", `name="limit" value="20"`}}, {"the only filter is a module: the pipelines that carry it", func() string { got := web("/pipelines?module=beta") if strings.Contains(got, "release.8") { return "release.8 does not carry beta: " + got } return got }, []string{"

PIPELINES CARRYING beta

", "main.12main"}}, {"a delivery of a branch the view reads no list of links through every branch's list", func() string { q := NewPipelines(runner.call, nil, 0, nil) q.Refresh() return q.Of(testBranch, 4) + " " + q.Of("main", 4) }, []string{"release.8 "}}, {"a pipeline the runner does not hold says so", func() string { return web("/pipelines/show?pipeline=main.99") }, []string{"unreadable: ", "no pipeline main.99"}}, {"a delivery links to the newest pipeline of its source revision", func() string { return text(func(b *bytes.Buffer) { Table(b, m.Snapshot()) }) + web("/") }, []string{testBranch + ": source revision 4: delivered (pipeline release.8)", `(pipeline)`, `Pipelines`}}, } for _, r := range rows { t.Run(r.name, func(t *testing.T) { got := r.got() for _, w := range r.want { if !strings.Contains(got, w) { t.Errorf("got %s\nwant it to hold %q", got, w) } } }) } if got := web("/pipelines?limit=1"); strings.Contains(got, "release.8") { t.Errorf("the newest 1 shows release.8: %s", got) } for _, l := range []string{"0", "x"} { rec := httptest.NewRecorder() Web(m).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/pipelines?limit="+l, nil)) if rec.Code != http.StatusBadRequest { t.Errorf("limit %s = %d, want 400", l, rec.Code) } } if strings.Contains(web("/pipelines"), "http-equiv=\"refresh\"") || strings.Contains(web("/pipelines/show?pipeline=main.12"), "http-equiv=\"refresh\"") { t.Error("a pipelines page reloads on a timer") } t.Run("an event of the runner reads the lists again and tells the pages", func(t *testing.T) { srv := httptest.NewServer(Web(m)) defer srv.Close() v := p.Version() res, err := http.Get(srv.URL + "/pipelines/changes?since=" + fmt.Sprint(v)) if err != nil { t.Fatal(err) } defer res.Body.Close() stream := bufio.NewReader(res.Body) if line, _ := stream.ReadString('\n'); !strings.HasPrefix(line, ":") { t.Fatalf("the stream starts %q", line) } shown := make(chan bool, 1) go func() { shown <- changedWithin(ctx, p, "main.13", v) }() runner.mu.Lock() before := runner.lists runner.mu.Unlock() runner.setRows("main", seat.PipelineRow{Pipeline: "main.13", Source: 10, Revision: 13, Outcome: seat.PipelineOutcomeRunning, MoverCount: 1}) if err := p.Hear([]byte(`{"pipeline":"main.13","branch":"main","source":10}`)); err != nil { t.Fatal(err) } if !<-shown { t.Fatal("the page of the pipeline heard is not told") } for { line, err := stream.ReadString('\n') if err != nil { t.Fatalf("the stream ended before the change: %v", err) } if line == "data: changed\n" { break } } runner.mu.Lock() after := runner.lists runner.mu.Unlock() if !strings.Contains(web("/pipelines"), "main.13") || after <= before { t.Errorf("the list was not read again (%d lists, %d before): %s", after, before, web("/pipelines")) } if err := p.Hear([]byte(`{"step":"unit"}`)); err == nil { t.Error("an event naming no pipeline is taken") } }) t.Run("a want or a have heard tells every pipeline's page, never the lists", func(t *testing.T) { v := p.Version() fill(m, haveFP(t, "n2", "gamma", fpNew, nodeengineclient.HealthOK)) if !changedWithin(ctx, p, "main.12", v) { t.Fatal("the page of main.12 is not told of the have") } p.mu.Lock() lists := p.changedSince("", v) p.mu.Unlock() if lists { t.Error("a have tells the lists") } if got := web("/pipelines/show?pipeline=main.12"); !strings.Contains(got, `held: connection refusedrunning the pipeline's build`) { t.Errorf("the page does not show gamma running on n2: %s", got) } }) t.Run("the terminal view follows the list on the socket, again at each event", func(t *testing.T) { path, sm := served(t) sm.SetPipelines(p) var seen []string heard := false err := AskPipelines(path, "", 0, "", "", "", true, func(page PipelinesPage, _ *PipelineAnswer) bool { seen = append(seen, page.Rows[0].Pipeline) if !heard { heard = true runner.setRows("main", seat.PipelineRow{Pipeline: "main.14", Source: 11, Revision: 14, Outcome: seat.PipelineOutcomeRunning, MoverCount: 1}) if err := p.Hear([]byte(`{"pipeline":"main.14","mover":"alpha","revision":14}`)); err != nil { // a re-pinned names no branch t.Error(err) } return true } return len(seen) < 2 || seen[len(seen)-1] != "main.14" }) if err != nil || seen[len(seen)-1] != "main.14" { t.Fatalf("followed %v, %v", seen, err) } var show *PipelineAnswer if err := AskPipelines(path, "", 0, "main.12", "beta", "", false, func(_ PipelinesPage, a *PipelineAnswer) bool { show = a; return true }); err != nil { t.Fatal(err) } if len(show.Pipeline.Steps) != 2 || show.Pipeline.Steps[0].Node != "n1" { t.Fatalf("the mover's steps on the socket = %+v", show) } if err := AskPipelines(path, "", 0, "main.99", "", "", false, func(PipelinesPage, *PipelineAnswer) bool { return true }); err == nil || !strings.Contains(err.Error(), "no pipeline main.99") { t.Fatalf("a pipeline the runner does not hold = %v", err) } }) t.Run("the pipelines heard are kept up to the setting pipelines-heard", func(t *testing.T) { few := NewPipelines(runner.call, nil, 2, nil) for _, k := range []string{"main.1", "main.2", "main.2", "main.3"} { few.notify(k) } few.mu.Lock() n, last := len(few.heard), few.heard["main.3"] few.mu.Unlock() if n > 2 || last == 0 { t.Errorf("heard holds %d pipelines (main.3 at %d), want at most the setting's 2, the newest kept", n, last) } if d := NewPipelines(runner.call, nil, 0, nil); d.most != DefaultPipelinesHeard { t.Errorf("the default keeps %d, want %d", d.most, DefaultPipelinesHeard) } }) t.Run("a list not read is shown unreadable and followed on, read again at the next event", func(t *testing.T) { var mu sync.Mutex away := true // the runner not answering yet, as the bus says when no holder listens call := func(key string, body any) (json.RawMessage, error) { mu.Lock() defer mu.Unlock() if away { return nil, fmt.Errorf("nats: no responders available for request") } return runner.call(key, body) } up := NewPipelines(call, nil, 0, nil) upCtx, upCancel := context.WithCancel(ctx) defer upCancel() go up.Run(upCtx) if !changedWithin(upCtx, up, "", 0) { t.Fatal("the lists were never read") } path, sm := served(t) sm.SetPipelines(up) var seen []PipelinesPage err := AskPipelines(path, "", 0, "", "", "", true, func(page PipelinesPage, _ *PipelineAnswer) bool { seen = append(seen, page) if len(seen) == 1 { mu.Lock() away = false mu.Unlock() if err := up.Hear([]byte(`{"pipeline":"main.14"}`)); err != nil { t.Error(err) } } return page.Error != "" || len(page.Rows) == 0 }) if err != nil || len(seen) < 2 || !strings.Contains(seen[0].Error, "no responders") || seen[len(seen)-1].Rows[0].Pipeline != "main.14" { t.Fatalf("followed %+v, %v; want the unreadable list, then main.14 after the event", seen, err) } var b bytes.Buffer PipelinesTable(&b, seen[0]) if !strings.Contains(b.String(), "unreadable: ") { t.Errorf("the terminal view of an unreadable list = %q", b.String()) } }) }