Files
mesh-delivery/modules/mesh-delivery-view/internal/view/pipelines_test.go
T
jschoubben 81387d0f3b Pipelines page: one pipeline by tier and stage, and its delivery on each node
The operator read every step of main.417 as passed and took it for delivered
while it had failed on one step and no want was written: the page listed a
pipeline's steps flat, with no tier, no stage and no delivery. One pipeline now
shows a header (outcome, first failure's why, how many movers run their build
on every node they are placed on), then a block per tier with a row per mover,
a cell per stage (the worst outcome over its artifacts, waited, ran and why on
hover) and a cell per node its module is placed on (no want written, wanted,
applying, running the pipeline's build, held with why), in the web page and the
terminal view. The page reloads on the runner's events and on the wants',
haves' and assignments' changes the view already hears.

Builds: design 47 H2 H-A-531, H-A-531 addendum (hq 7dc6592b, f870d24b)
2026-11-23 10:56:14 +01:00

405 lines
20 KiB
Go

package view
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"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]
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 OF main", "PASSED FAILED COULD NOT RUN NOT ASKED WAITING WAITING FOR A BUILD NODE BYPASSED NOTHING TO RUN",
"main.12 12 9 2026-10-18", "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{
`<a href="/pipelines/show?pipeline=main.12">main.12</a>`, `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",
"<h2>TIER 1</h2>", "<th>MOVER</th><th>OUTCOME</th><th>BUILD</th><th>LINT</th><th>UNIT</th><th>INTEGRATION</th><th>VALIDATE</th><th>COMPOSITION</th><th>CODE REVIEW</th><th>APPROVAL</th><th>n1</th><th>n2</th><th>n3</th>",
`<a href="/pipelines/show?mover=alpha&amp;pipeline=main.12">alpha</a></td><td class="passed">passed</td><td class="passed" title="alpha:program: passed`,
">passed 2/3</td>", `<td class="passed">running the pipeline&#39;s build</td><td class="passed">running the pipeline&#39;s build</td><td class="none"></td></tr>`,
`<td class="failed" title="beta:program: could not run, waited 2m40s, ran 20s on n1: no build node`, ">could not run 1/2</td>",
`<td class="waiting" title="approval: waiting: a person">waiting</td>`,
`<td class="wanted">wanted</td><td class="applying">applying</td><td class="not-run">no want written</td>`,
`<td class="held">held: connection refused</td><td class="held">held: health failed on n1</td>`,
"<h2>TIER 2</h2>", `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()}, "|")
}, []string{"not asked 1/5|could not run 1/2|frobbed 1/2|running 2/2|nothing to run|"}},
{"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{"<th>ASKED</th><th>TAKEN</th><th>ENDED</th><th>WAITED</th><th>RAN</th>",
"<td>unit beta:program</td><td>node-build-go</td><td>n1</td><td>could not run</td><td>" + since(started) + "</td><td>" + since(taken) + "</td><td>" + since(ended) + "</td><td>2m40s</td><td>20s</td><td>no build node</td>",
"<td>lint beta:program</td><td>node-build-go</td><td></td><td>could not run</td><td>" + since(started) + "</td><td></td><td>" + since(ended) + "</td><td>3m0s</td><td></td>"}},
{"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 2/3 - - - - - 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 a branch", func() string { return web("/pipelines?branch=" + testBranch + "&limit=1") }, []string{
"release.8", `name="limit" value="1"`}},
{"the web list is the newest 20 by default", func() string { return web("/pipelines?branch=" + testBranch) }, []string{
"release.8", "release.7", `name="limit" value="20"`}},
{"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)", `(<a href="/pipelines/show?pipeline=release.8">pipeline</a>)`, `<a href="/pipelines">Pipelines</a>`}},
}
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?branch=" + testBranch + "&limit=1"); strings.Contains(got, "release.7") {
t.Errorf("the newest 1 shows release.7: %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, `<td class="held">held: connection refused</td><td class="passed">running the pipeline&#39;s build</td>`) {
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())
}
})
}