Compare commits
139
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ecadf294e | ||
|
|
ae8b0c65bc | ||
|
|
1568877f35 | ||
|
|
04eda6130d | ||
|
|
959e8d6d30 | ||
|
|
01543d9121 | ||
|
|
8c8b4367f1 | ||
|
|
c775aab29a | ||
|
|
df79ab8769 | ||
|
|
5b06dd7e43 | ||
|
|
c99ad77633 | ||
|
|
401289afac | ||
|
|
a6a6135f74 | ||
|
|
c91ab3acfa | ||
|
|
ba0330c205 | ||
|
|
15458aeb61 | ||
|
|
815be6bdce | ||
|
|
f85f639afe | ||
|
|
0400d7bbe7 | ||
|
|
3ba309c5e4 | ||
|
|
7f5f285b60 | ||
|
|
f0bf4578a9 | ||
|
|
40dc5fe11d | ||
|
|
82d5688477 | ||
|
|
57984e9b98 | ||
|
|
2f471edc0f | ||
|
|
6cde12bf2f | ||
|
|
e534f667da | ||
|
|
4f10af81b0 | ||
|
|
6d398264db | ||
|
|
e44a2d140d | ||
|
|
f9857ab712 | ||
|
|
0cafb62d0e | ||
|
|
d7dada57aa | ||
|
|
a1bc613702 | ||
|
|
abcbeed115 | ||
|
|
673d1db95a | ||
|
|
c7f54357ad | ||
|
|
a30852939c | ||
|
|
9cfda8d6c7 | ||
|
|
a943b6a7db | ||
|
|
d901c6c19d | ||
|
|
30d1527e6a | ||
|
|
f82338e8ff | ||
|
|
c28fd39d23 | ||
|
|
ac2cd3749c | ||
|
|
4bdcedd0f0 | ||
|
|
f85199f624 | ||
|
|
13d43a7de0 | ||
|
|
5dfb357333 | ||
|
|
83accdbb4e | ||
|
|
7c64c17e65 | ||
|
|
0a446c7572 | ||
|
|
e1521a2ecf | ||
|
|
3a94021766 | ||
|
|
282758456c | ||
|
|
0e9f916806 | ||
|
|
daa5d3ea5f | ||
|
|
be993cb2c5 | ||
|
|
cd3b8fe8e9 | ||
|
|
f0c21ca033 | ||
|
|
c6ec42bc2e | ||
|
|
f65d789052 | ||
|
|
62b8251b99 | ||
|
|
90c88fc7b5 | ||
|
|
740c218139 | ||
|
|
1481465ec7 | ||
|
|
d2b8f64c94 | ||
|
|
eed95cd63b | ||
|
|
84106a9338 | ||
|
|
9ed13cd9dc | ||
|
|
d76c3588e3 | ||
|
|
377d42f5ea | ||
|
|
9ade421e12 | ||
|
|
46f3dc8cd7 | ||
|
|
7da6dd20a1 | ||
|
|
c87cf1ace5 | ||
|
|
3f3f6789dd | ||
|
|
8b5cc8be8d | ||
|
|
7c6aed9d69 | ||
|
|
4f9f307eaf | ||
|
|
e87c6cd3b6 | ||
|
|
73c2286ec9 | ||
|
|
3be2f79921 | ||
|
|
cf5ea429a2 | ||
|
|
1419dcef7d | ||
|
|
8c96a02a01 | ||
|
|
03cc8eac90 | ||
|
|
f31d6c645d | ||
|
|
bbc9eb7c93 | ||
|
|
1310c28102 | ||
|
|
affffa9c23 | ||
|
|
94f3cde557 | ||
|
|
6962da2f98 | ||
|
|
0aee792af6 | ||
|
|
86367f65b2 | ||
|
|
932e5c4e4b | ||
|
|
930c0fb783 | ||
|
|
79bd15884d | ||
|
|
13a0277f8c | ||
|
|
fcdf21d615 | ||
|
|
d6b75616f5 | ||
|
|
096668a14a | ||
|
|
2b1bc1d302 | ||
|
|
a55241c30b | ||
|
|
e1ee303a1c | ||
|
|
c9f8e6e8cd | ||
|
|
0afca54a0f | ||
|
|
8bb73eb61f | ||
|
|
229c887999 | ||
|
|
cdf168706b | ||
|
|
ae78fb039f | ||
|
|
928de07c43 | ||
|
|
666be37916 | ||
|
|
ccab80d726 | ||
|
|
1168376930 | ||
|
|
2679399d60 | ||
|
|
ce30601b0c | ||
|
|
d2c1a24a24 | ||
|
|
88ff34e855 | ||
|
|
76195e421f | ||
|
|
59704456c3 | ||
|
|
4a99f7044e | ||
|
|
7d17441a9a | ||
|
|
c006538064 | ||
|
|
bfc877209f | ||
|
|
99f3e23492 | ||
|
|
e8204a9c27 | ||
|
|
89397466aa | ||
|
|
28f616e379 | ||
|
|
8ea8ef9768 | ||
|
|
fb24d384a2 | ||
|
|
5236c2aa72 | ||
|
|
5df0fb64f5 | ||
|
|
ed536102ac | ||
|
|
a98b6ba77e | ||
|
|
b1125c02cf | ||
|
|
a4bc3d95ed | ||
|
|
6ba73d4e2a |
@@ -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(")
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -118,12 +119,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -734,17 +734,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>.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 +749,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
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
||||
|
||||
"distribution/internal/holder"
|
||||
)
|
||||
|
||||
// stepBound bounds each bus operation of a publish well under the tool runner's 30 s call bound, so a hang is an error
|
||||
// naming its step and the publish answers with it.
|
||||
const stepBound = 10 * time.Second
|
||||
|
||||
// step runs f, logs its start and its end with its time, and gives up on it after bound: the error names the step. A step
|
||||
// given up on is not cancelled (the SDK's bus calls take no context): its call ends at the SDK's own bound of the ask, and
|
||||
// the log says, by the step's name, that it was given up and later when the call behind it ended and how (A-443, A-443a).
|
||||
func step[T any](bound time.Duration, what string, f func() (T, error)) (T, error) {
|
||||
type res struct {
|
||||
v T
|
||||
err error
|
||||
}
|
||||
start := time.Now()
|
||||
logf("step %s starts", what)
|
||||
ch := make(chan res, 1)
|
||||
go func() { v, err := f(); ch <- res{v, err} }()
|
||||
select {
|
||||
case r := <-ch:
|
||||
logf("step %s ended after %s (%v)", what, time.Since(start).Round(time.Millisecond), r.err)
|
||||
return r.v, r.err
|
||||
case <-time.After(bound):
|
||||
var zero T
|
||||
err := fmt.Errorf("%s did not answer within %s", what, bound)
|
||||
logf("step %s: %v; given up, its call is left to end at the SDK's own bound", what, err)
|
||||
go func() {
|
||||
r := <-ch
|
||||
logf("step %s, given up after %s: its call ended after %s (%v)", what, bound, time.Since(start).Round(time.Millisecond), r.err)
|
||||
}()
|
||||
return zero, err
|
||||
}
|
||||
}
|
||||
|
||||
func stepErr(bound time.Duration, what string, f func() error) error {
|
||||
_, err := step(bound, what, func() (struct{}, error) { return struct{}{}, f() })
|
||||
return err
|
||||
}
|
||||
|
||||
// boundedObjects is the incoming object store with each operation bounded and logged.
|
||||
type boundedObjects struct{ parts.Objects }
|
||||
|
||||
func (b boundedObjects) Used() (uint64, error) {
|
||||
return step(stepBound, "the incoming object store's fill (objects)", b.Objects.Used)
|
||||
}
|
||||
func (b boundedObjects) Put(name string, data []byte) error {
|
||||
return stepErr(stepBound, "the put of a chunk in the incoming object store (objects)", func() error { return b.Objects.Put(name, data) })
|
||||
}
|
||||
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) })
|
||||
}
|
||||
|
||||
// boundedTransfers is the transfers state with its reads and writes bounded and logged.
|
||||
type boundedTransfers struct {
|
||||
parts.Transfers[holder.Opening]
|
||||
}
|
||||
|
||||
func (b boundedTransfers) Get(id string) (parts.Transfer[holder.Opening], bool, error) {
|
||||
type r struct {
|
||||
t parts.Transfer[holder.Opening]
|
||||
ok bool
|
||||
}
|
||||
x, err := step(stepBound, "the read of the transfer in the transfers state", func() (r, error) {
|
||||
t, ok, err := b.Transfers.Get(id)
|
||||
return r{t, ok}, err
|
||||
})
|
||||
return x.t, x.ok, err
|
||||
}
|
||||
func (b boundedTransfers) Put(t parts.Transfer[holder.Opening]) error {
|
||||
return stepErr(stepBound, "the write of the transfer in the transfers state", func() error { return b.Transfers.Put(t) })
|
||||
}
|
||||
func (b boundedTransfers) Delete(id string) error {
|
||||
return stepErr(stepBound, "the delete of the transfer in the transfers state", func() error { return b.Transfers.Delete(id) })
|
||||
}
|
||||
|
||||
// boundedCap is the incoming cap read from its binding, bounded and logged.
|
||||
func boundedCap(c func() (uint64, error)) func() (uint64, error) {
|
||||
return func() (uint64, error) {
|
||||
return step(stepBound, "the read of incoming's cap from its binding (objects)", c)
|
||||
}
|
||||
}
|
||||
|
||||
// boundedArm is the idle key's write, bounded and logged.
|
||||
func boundedArm(a func(string, time.Duration) error) func(string, time.Duration) error {
|
||||
return func(id string, ttl time.Duration) error {
|
||||
return stepErr(stepBound, "the write of the idle key in the idle state", func() error { return a(id, ttl) })
|
||||
}
|
||||
}
|
||||
|
||||
// boundedFinding is the findings writer's say moved off the publish's path: the receiver says the incoming fill on every
|
||||
// open, and a publish never waits for it. One worker says them in order, each bounded and logged; one said while the worker
|
||||
// is full is dropped and logged (the next open says the fill again).
|
||||
func boundedFinding(f holder.Finding) holder.Finding {
|
||||
type said struct {
|
||||
kind, subject, words string
|
||||
raised bool
|
||||
}
|
||||
queue := make(chan said, 64)
|
||||
go func() {
|
||||
for s := range queue {
|
||||
_ = stepErr(stepBound, "the finding "+s.kind+" of "+s.subject, func() error { f(s.kind, s.subject, s.words, s.raised); return nil })
|
||||
}
|
||||
}()
|
||||
return func(kind, subject, words string, raised bool) {
|
||||
select {
|
||||
case queue <- said{kind, subject, words, raised}:
|
||||
default:
|
||||
logf("the finding %s of %s is not said now: the writer is behind, the next open says it again", kind, subject)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A bus operation that never answers becomes an error naming its step, within the bound.
|
||||
func TestAHungStepAnswersWithItsName(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 })
|
||||
if err == nil || !strings.Contains(err.Error(), "the write of the idle key did not answer within") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if v, err := step(time.Second, "x", func() (int, error) { return 7, nil }); v != 7 || err != nil {
|
||||
t.Fatalf("%d %v", v, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
var mu sync.Mutex
|
||||
var lines []string
|
||||
ended := make(chan struct{})
|
||||
w := func(f string, a ...any) {
|
||||
l := fmt.Sprintf(f, a...)
|
||||
mu.Lock()
|
||||
lines = append(lines, l)
|
||||
mu.Unlock()
|
||||
if strings.Contains(l, "the put of a chunk") && strings.Contains(l, "its call ended after") {
|
||||
close(ended)
|
||||
}
|
||||
}
|
||||
old := logTo.Swap(&w)
|
||||
defer logTo.Store(old)
|
||||
release := make(chan struct{})
|
||||
if _, err := step(10*time.Millisecond, "the put of a chunk", func() (int, error) { <-release; return 0, fmt.Errorf("bus closed") }); err == nil {
|
||||
t.Fatal("not given up")
|
||||
}
|
||||
close(release)
|
||||
<-ended
|
||||
mu.Lock()
|
||||
all := strings.Join(lines, "\n")
|
||||
mu.Unlock()
|
||||
if !strings.Contains(all, "given up") || !strings.Contains(all, "bus closed") {
|
||||
t.Fatalf("log: %s", all)
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
block := make(chan struct{})
|
||||
defer close(block)
|
||||
say := boundedFinding(func(string, string, string, bool) { <-block })
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
say("incoming-full", "incoming", "w", false)
|
||||
say("incoming-full", "incoming", "w", false)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the call was held by the finding")
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
@@ -29,7 +30,15 @@ import (
|
||||
"distribution/internal/holder"
|
||||
)
|
||||
|
||||
func logf(format string, a ...any) { fmt.Fprintf(os.Stderr, "[distribution-tools] "+format+"\n", a...) }
|
||||
// logTo is where logf writes; a test replaces it (atomically: a step given up on logs from its own goroutine).
|
||||
var logTo atomic.Pointer[func(string, ...any)]
|
||||
|
||||
func init() {
|
||||
w := func(format string, a ...any) { fmt.Fprintf(os.Stderr, "[distribution-tools] "+format+"\n", a...) }
|
||||
logTo.Store(&w)
|
||||
}
|
||||
|
||||
func logf(format string, a ...any) { (*logTo.Load())(format, a...) }
|
||||
|
||||
// kept is one state of distribution's, through the runtime.
|
||||
type kept[T any] struct {
|
||||
@@ -249,10 +258,21 @@ func tools(v *holder.Verbs, windows kept[holder.Window]) []stdio.Tool {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, err := v.Publish(seat, stdio.CallerOf(args), publishOf(in))
|
||||
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))
|
||||
if err == nil {
|
||||
learnPublishing(windows, stdio.CallerOf(args))
|
||||
// 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.
|
||||
go func() {
|
||||
t := time.Now()
|
||||
logf("learning the publishing build of %s starts (mesh-delivery-view.node_haves)", caller)
|
||||
learnPublishing(windows, caller)
|
||||
logf("learning the publishing build of %s ended after %s", caller, time.Since(t).Round(time.Millisecond))
|
||||
}()
|
||||
}
|
||||
logf("%s.publish from %s answered after %s (error: %v)", seat, caller, time.Since(start).Round(time.Millisecond), err)
|
||||
return publishAnswer(a), err
|
||||
}},
|
||||
stdio.Tool{Name: seat + "." + holder.VerbPublishPart, Description: "Send one chunk (at most 1 MiB) of one part of an open transfer, from the caller that opened it.",
|
||||
@@ -468,8 +488,8 @@ func main() {
|
||||
}()
|
||||
base, _ := url.Parse("http://127.0.0.1:5001")
|
||||
store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}}
|
||||
h := &holder.Holder{Objects: parts.BusObjects(holder.IncomingObjects), Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: findings.Say,
|
||||
Transfers: parts.BusTransfers[holder.Opening](holder.TransfersState), Cap: parts.BusCap(holder.IncomingObjects), Record: recordAct, Idle: parts.BusArm(holder.IdleState)}
|
||||
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),
|
||||
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) }}
|
||||
|
||||
@@ -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
|
||||
@@ -71,6 +72,7 @@ func (s *fakeStore) Put(t PublishRequest, parts map[string][]byte) (string, erro
|
||||
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 }
|
||||
|
||||
type said struct {
|
||||
seat, event string
|
||||
@@ -231,6 +233,21 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
return PublishRequest{Transfer: id, Name: "m/program", Version: "0.1.4", Kind: KindBundle, Digest: part.Digest, Parts: []Part{part}}
|
||||
}
|
||||
|
||||
t.Run("a publish says each of its waits with its time", func(t *testing.T) {
|
||||
b := newBed(true)
|
||||
var lines []string
|
||||
b.h.Logf = func(f string, a ...any) { lines = append(lines, fmt.Sprintf(f, a...)) }
|
||||
if _, err := b.h.Publish(ArtifactSeat, builder, req("tl")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all := strings.Join(lines, "\n")
|
||||
for _, want := range []string{"the store's read of what it holds (the program's registry) starts", "(the program's registry) ended after", "the opening of the transfer on the bus"} {
|
||||
if !strings.Contains(all, want) {
|
||||
t.Errorf("no log line %q in:\n%s", want, all)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
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"))
|
||||
@@ -650,30 +667,53 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a late publish names a held bundle with no size: tagged at the store's size, nothing sent", func(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
|
||||
// stored, naming the digest.
|
||||
store := newFakeRegistry()
|
||||
sts := httptest.NewServer(store)
|
||||
defer sts.Close()
|
||||
base, _ := url.Parse(sts.URL)
|
||||
o := &OCI{Base: base}
|
||||
b := newBed(true)
|
||||
b.h.Store = &OCI{Base: base}
|
||||
blob := []byte(strings.Repeat("b", 4321))
|
||||
store.blobs["m/tools@"+digestOf(blob)] = blob
|
||||
ref, err := o.Put(PublishRequest{Name: "m/tools", Version: "0.1.4", Kind: KindBundle, Digest: digestOf(blob),
|
||||
Parts: []Part{{Digest: digestOf(blob)}}}, map[string][]byte{})
|
||||
if err != nil || ref != "m/tools@"+digestOf(blob) {
|
||||
t.Fatalf("Put = %q, %v", ref, err)
|
||||
got, err := b.h.Publish(ArtifactSeat, "x.mesh-delivery-builder", PublishRequest{Name: "m/tools", Version: "0.1.4", Kind: KindBundle, Digest: digestOf(blob),
|
||||
Transfer: "republish-m-0-1-4-tools"})
|
||||
if err != nil || !got.Ended || len(b.said) != 1 || b.said[0].event != EventPublished || b.said[0].body.Reference != SeatReference(ArtifactSeat, "m/tools@"+digestOf(blob)) {
|
||||
t.Fatalf("Publish = %+v, %v; said %+v", got, err, b.said)
|
||||
}
|
||||
var man struct {
|
||||
Layers []struct {
|
||||
Size int64 `json:"size"`
|
||||
Digest string `json:"digest"`
|
||||
Size int64 `json:"size"`
|
||||
} `json:"layers"`
|
||||
}
|
||||
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)) {
|
||||
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))
|
||||
}
|
||||
if _, err := o.Put(PublishRequest{Name: "m/tools", Version: "0.1.5", Kind: KindBundle, Digest: "sha256:" + strings.Repeat("e", 64),
|
||||
Parts: []Part{{Digest: "sha256:" + strings.Repeat("e", 64)}}}, map[string][]byte{}); err == nil {
|
||||
t.Error("a digest the store does not hold was tagged")
|
||||
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 ||
|
||||
len(b.said) != 2 || b.said[1].event != EventRefused || !b.findings["publish-refused m/tools@0.1.5"] {
|
||||
t.Errorf("a digest not held: %v; said %+v; findings %v", err, b.said, b.findings)
|
||||
}
|
||||
})
|
||||
t.Run("mirror answers at once and says the copy's end on the seat's events", func(t *testing.T) {
|
||||
|
||||
@@ -219,6 +219,25 @@ func (o *OCI) Held(name, version, digest string) (string, bool, error) {
|
||||
return name + "@" + d, true, 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
|
||||
// or an archive's blob.
|
||||
func (o *OCI) Holds(r PublishRequest) (bool, error) {
|
||||
if r.Kind != KindImage && r.Kind != KindUpstream {
|
||||
return o.Has(r.Name, r.Digest)
|
||||
}
|
||||
resp, _, err := o.do(http.MethodHead, "/v2/"+r.Name+"/manifests/"+r.Digest, "", nil, accepted...)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
return true, nil
|
||||
case http.StatusNotFound:
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("the store answered %d for the manifest %s of %s", resp.StatusCode, r.Digest, r.Name)
|
||||
}
|
||||
|
||||
// Versions are name's tags.
|
||||
func (o *OCI) Versions(name string) ([]string, error) {
|
||||
resp, b, err := o.do(http.MethodGet, "/v2/"+name+"/tags/list", "", nil)
|
||||
|
||||
@@ -143,6 +143,9 @@ type Store interface {
|
||||
// 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)
|
||||
// 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://<name>/blobs/<digest>` is that blob.
|
||||
Holds(r PublishRequest) (bool, error)
|
||||
}
|
||||
|
||||
// SeatReference is a reference in the form the seat answers (novox/hq ADR 0605 §9): the seat's name, then the path the
|
||||
@@ -173,6 +176,20 @@ type Holder struct {
|
||||
// Idle writes a transfer's idle key with its own time to live, once (parts.BusArm over IdleState); the receiver
|
||||
// arms it on each open that leaves a transfer open. Nil arms nothing.
|
||||
Idle func(id string, ttl time.Duration) error
|
||||
// Logf says each wait of a publish with its time (stderr in the bundle); nil says nothing.
|
||||
Logf func(string, ...any)
|
||||
}
|
||||
|
||||
// timed runs f and logs its name and time when the holder logs.
|
||||
func (h *Holder) timed(what string, f func() error) error {
|
||||
if h.Logf == nil {
|
||||
return f()
|
||||
}
|
||||
start := time.Now()
|
||||
h.Logf("publish: %s starts", what)
|
||||
err := f()
|
||||
h.Logf("publish: %s ended after %s (%v)", what, time.Since(start).Round(time.Millisecond), err)
|
||||
return err
|
||||
}
|
||||
|
||||
func (h *Holder) now() time.Time {
|
||||
@@ -249,23 +266,83 @@ 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 != "" {
|
||||
if ref, ok, err := h.Store.Held(r.Name, r.Version, r.Digest); err != nil {
|
||||
var ref string
|
||||
var ok bool
|
||||
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)
|
||||
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 {
|
||||
return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.Say(seat, EventPublished, h.eventOf(seat, r, SeatReference(seat, 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), ""))
|
||||
})
|
||||
}
|
||||
}
|
||||
if r.Version != "" && len(r.Parts) == 0 {
|
||||
return h.tagHeld(seat, r)
|
||||
}
|
||||
wants := make([]parts.Want, 0, len(r.Parts))
|
||||
for _, p := range r.Parts {
|
||||
wants = append(wants, parts.Want{Digest: p.Digest, Size: p.Size})
|
||||
}
|
||||
got, err := h.receiver().Open(r.Transfer, caller, wants, Opening{PublishRequest: r, Seat: seat})
|
||||
var got parts.Received
|
||||
err := h.timed("the opening of the transfer on the bus (objects, transfer state, idle key)", func() (err error) {
|
||||
got, err = h.receiver().Open(r.Transfer, caller, wants, Opening{PublishRequest: r, Seat: seat})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return answerOf(got), fmt.Errorf("publish: %w", err)
|
||||
}
|
||||
return answerOf(got), nil
|
||||
}
|
||||
|
||||
// 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,
|
||||
// naming the digest. Nothing travels.
|
||||
func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) {
|
||||
var held bool
|
||||
err := h.timed("the store's read of the digest it holds (the program's registry)", func() (err error) {
|
||||
held, err = h.Store.Holds(r)
|
||||
return err
|
||||
})
|
||||
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)
|
||||
}
|
||||
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))
|
||||
}
|
||||
ok, why, err := h.Builder.Recorded(r.Name, r.Version, r.Digest)
|
||||
if err != nil {
|
||||
return PublishAnswer{}, fmt.Errorf("publish: the reservation could not be read, so nothing is tagged: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return refuse("the builder did not reserve it: " + why)
|
||||
}
|
||||
tag := r
|
||||
tag.Parts = []Part{{Digest: r.Digest}}
|
||||
var path string
|
||||
if err := h.timed("the store's tag of the held digest (the program's registry)", func() (err error) {
|
||||
path, err = h.Store.Put(tag, map[string][]byte{})
|
||||
return err
|
||||
}); err != nil {
|
||||
return refuse("the store did not tag it: " + err.Error())
|
||||
}
|
||||
h.Finding("publish-refused", r.Name+"@"+r.Version, "", false)
|
||||
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, path), ""))
|
||||
})
|
||||
}
|
||||
|
||||
// PublishPart is `publish-part`: one chunk, from the caller that opened the transfer alone.
|
||||
func (h *Holder) PublishPart(seat, caller string, r PartRequest) (PublishAnswer, error) {
|
||||
got, err := h.receiver().Take(r.Transfer, caller, r.Digest, r.Sequence, r.Last, r.Data, func(t Transfer) error {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/sh
|
||||
# The wallpaper (module feh, novox/hq ADR 0208). Owned by the mesh: replaced at every push. The
|
||||
# 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.
|
||||
# without touching this file (the second single-module proof, 2026-11-17).
|
||||
feh --no-fehbg --bg-fill "$HOME/.local/share/feh/wallpapers/default.jpg"
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// **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.<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<string, unknown>)["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<unknown>, private readonly retentionDays: () => number = () => CALL_RETENTION_DAYS,
|
||||
private readonly log: (line: string) => void = () => {}) {}
|
||||
|
||||
/** Every call kept, newest first. */
|
||||
async all(): Promise<KeptCall[]> {
|
||||
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<KeptCall | undefined> {
|
||||
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<void> {
|
||||
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<string[]> {
|
||||
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 }): 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 } : {}) });
|
||||
|
||||
/** Says a seat event on its subject, under an id the bus keeps once. */
|
||||
export type Say = (subject: string, body: unknown, id?: string) => Promise<void>;
|
||||
|
||||
/** 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. */
|
||||
export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined {
|
||||
const landed = c.members.filter((m) => m.state === "merged" && m.commit);
|
||||
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<boolean> {
|
||||
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<string[]> {
|
||||
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;
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, any> } {
|
||||
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<unknown> = 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<StateFill> = askFill) {}
|
||||
private readonly fillOf: () => Promise<StateFill> = askFill,
|
||||
/** The module's state findings, where step-unread is written (G §585, H-A-93); none writes no finding. */
|
||||
private readonly findings?: State<unknown>) {}
|
||||
|
||||
private turn<T>(act: () => Promise<T>): Promise<T> {
|
||||
const r = this.chain.then(act, act);
|
||||
@@ -98,9 +117,13 @@ export class FailedSteps {
|
||||
|
||||
private record(ev: StepEndedEvent): Promise<void> {
|
||||
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 `<run>.<module>.<step>`, 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<void> {
|
||||
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<Judged | null> {
|
||||
return this.turn(async () => {
|
||||
|
||||
@@ -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<void>;
|
||||
/** 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<Record<string, HeadCheck>>;
|
||||
}
|
||||
|
||||
/** 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<void>;
|
||||
}
|
||||
|
||||
export class GateWriter {
|
||||
private heads = new Map<string, Head>();
|
||||
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<void>): Promise<void> {
|
||||
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<void>): Promise<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<string, HeadCheck>) => CommitStatus[] | Promise<CommitStatus[]>, target?: string): Promise<CommitStatus[]> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+35
-148
@@ -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.
|
||||
@@ -50,18 +44,18 @@ 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 { Partials } from "./partials.js";
|
||||
import { callTools } from "./tools/calls.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";
|
||||
@@ -107,7 +101,7 @@ async function pollRepos(client: GiteaClient): Promise<void> {
|
||||
// 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 +173,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 +232,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 +239,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<boolean> {
|
||||
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<void> {
|
||||
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<ReturnType<GiteaClient["listOpenPullsSince"]>>[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<boolean> {
|
||||
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<void> {
|
||||
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<string, string> = {};
|
||||
let changedTrunks = false;
|
||||
if (trunksRecord && existsSync(trunksRecord)) {
|
||||
try {
|
||||
trunks = (JSON.parse(readFileSync(trunksRecord, "utf8")) as { trunks: Record<string, string> }).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<boolean> {
|
||||
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<void> {
|
||||
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 +280,34 @@ 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<void> = async () => {};
|
||||
const failedSteps = new FailedSteps(state<unknown>("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<unknown>("calls"), () => callRetentionDays(), (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<unknown>("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<unknown>("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit),
|
||||
undefined, state<unknown>("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.watched, calls, say: seatPublish, partials }) : []),
|
||||
...callTools(calls, partials, seatPublish, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
|
||||
...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<void> => actOn<RepoOf, PullOf>(event, {
|
||||
getRepo: (o, r) => client.getRepo(o, r),
|
||||
getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise<PullOf & { state?: string; merged?: boolean }>,
|
||||
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 +453,9 @@ 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<StepEndedEvent>(`${RUNNER}.${RUNNER_EVENTS.stepEnded}`, (event) => failedSteps.stepEnded(event.body)));
|
||||
// The runner's step-ended is said on step-ended.<module>.<branch>.<commit> (the seat's definition).
|
||||
const stepEnded = `${RUNNER}.${RUNNER_EVENTS.stepEnded}.*.*.*`;
|
||||
void bindUntilHeld(stepEnded, () => on<StepEndedEvent>(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<BranchMovedEvent>(`${GIT}.${GIT_EVENTS.branchMoved}`, async (event) => {
|
||||
const { repository, branch } = event.body;
|
||||
@@ -580,9 +469,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 +483,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<void> = Promise.resolve();
|
||||
const pass = (): Promise<void> => (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 = () => {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"},
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,483 @@
|
||||
//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).
|
||||
// - 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).
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"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/testbus"
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
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 `<owner>/<name>#<number>` and every merge asked.
|
||||
type forge struct {
|
||||
mu sync.Mutex
|
||||
pulls map[string]*pull
|
||||
merges []string
|
||||
paths []string
|
||||
}
|
||||
|
||||
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)
|
||||
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
|
||||
}
|
||||
|
||||
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/publish", "mesh/state.watch", "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
|
||||
}
|
||||
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.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 {
|
||||
r.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
|
||||
return
|
||||
}
|
||||
r.say(map[string]any{"id": id, "result": result})
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func TestTheSeatGitWholeOverARealBus(t *testing.T) {
|
||||
dir, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "node_modules", "@novox", "mesh-sdk")); err != nil {
|
||||
t.Fatalf("the forge module's packages are not installed in %s (npm install first): %v", dir, err)
|
||||
}
|
||||
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"} {
|
||||
kv, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "gitea_" + name})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kvs[name] = kv
|
||||
}
|
||||
A, B, X := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("e", 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},
|
||||
}}
|
||||
srv := httptest.NewServer(http.HandlerFunc(f.serve))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
state := t.TempDir()
|
||||
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,
|
||||
"GITEA_TOKEN=t", "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"}}}}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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)
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
// 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" },
|
||||
|
||||
@@ -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<string[]>, say: (line: string) => void): () => Promise<void> {
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// **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.
|
||||
|
||||
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 `<owner>/<name>`. */
|
||||
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
|
||||
/** The failed `required` step that refuses a head, or null (failedsteps.ts). */
|
||||
judge: (head: string) => Promise<Judged | null>;
|
||||
/** 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<GiteaClient, "getPullRequest" | "mergePullRequest" | "commitParents">;
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
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<string>();
|
||||
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 <owner>/<name>`);
|
||||
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, m: Member): Promise<string> {
|
||||
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`;
|
||||
}
|
||||
if (!deps.watched().get(m.repository)?.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<string> {
|
||||
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 } : {}) });
|
||||
|
||||
/** merge-pull: one merge call (design 47 H §734, §735). */
|
||||
export async function mergeCall(forge: CallForge, args: Record<string, unknown>, deps: CallDeps): Promise<MergePullAnswer> {
|
||||
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`);
|
||||
// Every member is judged before any is merged (§735).
|
||||
let refused = false;
|
||||
for (const m of members) {
|
||||
const why = await judgeMember(forge, deps, m);
|
||||
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";
|
||||
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) };
|
||||
}
|
||||
@@ -211,9 +211,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
|
||||
},
|
||||
@@ -358,7 +365,8 @@
|
||||
"takes-config": [
|
||||
"url",
|
||||
"keep-main-rules",
|
||||
"main-mergers"
|
||||
"main-mergers",
|
||||
"call-retention"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -623,6 +631,10 @@
|
||||
{
|
||||
"name": "failed-steps",
|
||||
"history": 1
|
||||
},
|
||||
{
|
||||
"name": "calls",
|
||||
"history": 1
|
||||
}
|
||||
],
|
||||
"reads": [
|
||||
@@ -642,7 +654,7 @@
|
||||
"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",
|
||||
|
||||
@@ -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, `<repository>#<number>`. */
|
||||
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<string, unknown> } {
|
||||
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<unknown>, 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<void> {
|
||||
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<KeptCall[]> {
|
||||
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<string[]> {
|
||||
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<boolean> {
|
||||
const held = !!(await this.findings.get(partialKey(call)))?.value;
|
||||
if (held) await this.findings.delete(partialKey(call));
|
||||
return held;
|
||||
}
|
||||
}
|
||||
+2
-92
@@ -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 <head12> on <trunk12> …". */
|
||||
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 <machine> 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<string, string>;
|
||||
|
||||
/** 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";
|
||||
|
||||
+26
-81
@@ -9,9 +9,9 @@
|
||||
// 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.
|
||||
//
|
||||
// **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 {
|
||||
@@ -26,6 +26,9 @@ import { containedFrom, newestByContext } from "./checks.js";
|
||||
import { Refused, checkName } from "./guard.js";
|
||||
import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js";
|
||||
import type { Judged } from "./failedsteps.js";
|
||||
import { mergeCall } from "./mergecall.js";
|
||||
import type { Calls, Say } from "./calls.js";
|
||||
import type { Partials } from "./partials.js";
|
||||
|
||||
/** The verbs of the seat, in its definition's order. */
|
||||
export const VERBS: readonly string[] = Object.values(GIT_VERBS);
|
||||
@@ -37,22 +40,23 @@ 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<void>;
|
||||
}
|
||||
|
||||
/** 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<Judged | null>;
|
||||
/** The watched branches the registrations name, by their origin repository (registrations.ts): a member's base is one. */
|
||||
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** A failure as the contract says it: the forge's or this holder's refusal, or a forge that failed. */
|
||||
@@ -149,13 +153,16 @@ 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<BranchAnswer> => {
|
||||
const { owner, repo, full } = repositoryOf(args.repository);
|
||||
const branch = String(args.branch ?? "");
|
||||
// No branch named is the repository's default branch, read from the forge, as the verb file reads it (A-399).
|
||||
let branch = String(args.branch ?? "");
|
||||
if (branch === "") branch = String((await gitea.getRepo(owner, repo)).default_branch ?? "");
|
||||
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<OpenPullsAnswer> => {
|
||||
@@ -215,14 +222,14 @@ 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<StatusAnswer> => {
|
||||
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 };
|
||||
}),
|
||||
@@ -255,8 +262,8 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
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<MergePullAnswer> => mergePull(gitea, args, deps.registered, deps.judge)),
|
||||
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<MergePullAnswer> => mergeCall(gitea, args, deps)),
|
||||
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.",
|
||||
async (args): Promise<TagAnswer> => {
|
||||
const { owner, repo } = repositoryOf(args.repository);
|
||||
@@ -272,68 +279,6 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
];
|
||||
}
|
||||
|
||||
/** 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<string, unknown>, registered: () => boolean,
|
||||
judge: (head: string) => Promise<Judged | null>): Promise<MergePullAnswer> {
|
||||
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["refused-kind"]>): 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 };
|
||||
}
|
||||
|
||||
@@ -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<string, SiblingEntry>;
|
||||
|
||||
/** 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<string, unknown>;
|
||||
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<GiteaPull>;
|
||||
branchHead(owner: string, repo: string, branch: string): Promise<string>;
|
||||
commitParents(owner: string, repo: string, sha: string): Promise<string[]>;
|
||||
}
|
||||
|
||||
/** 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<string, HeadCheck>, 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<boolean> {
|
||||
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<Record<string, HeadCheck>>;
|
||||
}
|
||||
|
||||
/** 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@<full sha>`, one per member, by repository. A malformed entry is refused, never skipped. */
|
||||
export function approvedHeadsOf(given: unknown): Map<string, string> | undefined {
|
||||
if (given === undefined || given === null) return undefined;
|
||||
if (!Array.isArray(given)) throw new Refused("approved_heads must be a list of owner/repo@<full sha>. Nothing was merged");
|
||||
const out = new Map<string, string>();
|
||||
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@<full sha>. 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<string, string>, 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<string, string> | undefined): Promise<string | undefined> {
|
||||
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;
|
||||
}
|
||||
@@ -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[] = [];
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
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.<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<string, any> = { 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.<call> 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<number, any> = { 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");
|
||||
});
|
||||
|
||||
// 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");
|
||||
});
|
||||
@@ -20,7 +20,7 @@ function memory() {
|
||||
}
|
||||
const ended = (commit: string, outcome: string, extra: Record<string, unknown> = {}, over: Record<string, unknown> = {}) => ({
|
||||
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 <run>.<module>.<step>, 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");
|
||||
});
|
||||
|
||||
@@ -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<string, { state: string; description: string; updated_at: string }> = {};
|
||||
const written: string[] = [];
|
||||
let failNext = 0;
|
||||
let hold: Promise<void> | 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<void>((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<typeof aForge>) =>
|
||||
`${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");
|
||||
});
|
||||
|
||||
@@ -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<void> | 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<string, unknown>, caller = bridge) =>
|
||||
runAs({ "mesh/caller": caller }, args, () => seat.find((t: any) => t.name === `git.${verb}`)!.run(args)) as Promise<any>;
|
||||
const merge = (extra: Record<string, unknown> = {}, 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<string, unknown>; 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<void>((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));
|
||||
@@ -552,10 +494,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<string, unknown>, over: Record<string, unknown> = {}) => {
|
||||
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<any>;
|
||||
};
|
||||
const rows: [string, string, Record<string, unknown>, Record<string, unknown>, (a: any) => unknown, unknown][] = [
|
||||
@@ -563,9 +505,7 @@ 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]],
|
||||
["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"]],
|
||||
|
||||
@@ -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: "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: "transfers" }] });
|
||||
});
|
||||
|
||||
test("index.ts says the announcement as the event `states` before the tools are served", () => {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<string, unknown>();
|
||||
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 () => {},
|
||||
} };
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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 `<repository>#<number>`, recording each merge asked. It has no protection API: a call that
|
||||
* read a branch's protection would throw. */
|
||||
function forge(pulls: Record<string, FakePull>) {
|
||||
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<typeof forge>, args: Record<string, unknown>, over: Record<string, unknown> = {}, 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<any>;
|
||||
}
|
||||
|
||||
const two = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/lib", number: 9, head: B }] };
|
||||
const open = (): Record<string, FakePull> => ({ "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<string, FakePull>) => void; over?: Record<string, unknown>; 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);
|
||||
}
|
||||
});
|
||||
|
||||
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/);
|
||||
});
|
||||
@@ -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<number, any> = { 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<any>;
|
||||
};
|
||||
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]);
|
||||
});
|
||||
@@ -41,33 +41,6 @@ async function serve(count: number, heads: Record<number, string>) {
|
||||
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<string, string> = {};
|
||||
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, {});
|
||||
|
||||
@@ -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<string, string> = { [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);
|
||||
});
|
||||
|
||||
@@ -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<string, { state: string; description?: string }>;
|
||||
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<any[]>) {
|
||||
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<string, string> = {};
|
||||
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<string, string> = {};
|
||||
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<typeof composedMembers>): 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);
|
||||
});
|
||||
@@ -487,9 +487,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");
|
||||
|
||||
@@ -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<string, string>) {
|
||||
const statuses = new Map<string, Record<string, { state: string; description?: string }>>();
|
||||
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<string, string> = { 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<string, string> = {};
|
||||
|
||||
// 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<string, string> = { main: TRUNK };
|
||||
const { forge } = aForge([{ number: 1, base: "main", head: "1".repeat(40) }], heads);
|
||||
const trunks: Record<string, string> = { "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<string, string> = { main: TRUNK };
|
||||
const { forge, statuses } = aForge([{ number: 1, base: "main", head: HEAD }], heads);
|
||||
const trunks: Record<string, string> = { "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<string, string> = { 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<string, string> = {};
|
||||
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 "<head12> on <trunk12>".
|
||||
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);
|
||||
});
|
||||
@@ -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<string, string> = {};
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// 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";
|
||||
|
||||
const word = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
|
||||
|
||||
export function callTools(calls: Calls, partials: Partials, say: Say, acts: (act: HandAct) => Promise<void>): 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<string, unknown>) => {
|
||||
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<string, unknown>) => {
|
||||
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<string, unknown>) => {
|
||||
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 };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -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 <head12> on <trunk12>"), 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): "<head12> on <trunk12>".
|
||||
?? /\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<string, HeadCheck>, 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<string, HeadCheck>, 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<GiteaPull[]>;
|
||||
branchHead(owner: string, repo: string, branch: string): Promise<string>;
|
||||
/** 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<string, HeadCheck>) => CommitStatus[] | Promise<CommitStatus[]>, target?: string): Promise<CommitStatus[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, string>, owner: string,
|
||||
name: string, moved?: (base: string) => Promise<void>): Promise<boolean> {
|
||||
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<Record<string, unknown>> {
|
||||
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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -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<Record<string, unknown>> {
|
||||
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 } : {}),
|
||||
};
|
||||
}
|
||||
+6
-54
@@ -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<R, P> {
|
||||
getRepo(owner: string, repo: string): Promise<R>;
|
||||
getPull(owner: string, repo: string, number: number): Promise<P & { state?: string; merged?: boolean }>;
|
||||
announceHead(repo: R, pull: P): Promise<unknown>;
|
||||
announceUpdated(repo: R, pull: P): Promise<unknown>;
|
||||
announceMerge(repo: R, pull: P): Promise<unknown>;
|
||||
announceClosed(repo: R, pull: P): Promise<unknown>;
|
||||
siblingMoves(full: string, number: number): Promise<unknown>;
|
||||
}
|
||||
|
||||
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<R, P>(event: ForgeEvent, d: ActDeps<R, P>): Promise<void> {
|
||||
const b = event.body as { owner?: string; repo?: string; number?: number; merged?: boolean };
|
||||
@@ -37,51 +32,8 @@ export async function actOn<R, P>(event: ForgeEvent, d: ActDeps<R, P>): 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<void>, opts: { retryMs: number; log?: (l: string) => void }): Promise<void> {
|
||||
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<void>((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<boolean>;
|
||||
/** Announce it; true when it was this call that announced it (not an event before it). */
|
||||
announceHead(pull: GiteaPull): Promise<boolean>;
|
||||
/** 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<void> {
|
||||
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 };
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -57,9 +57,6 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
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 +88,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{KeepOutput: steprun.KeepOutputIn(m.Outputs), 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 {
|
||||
|
||||
@@ -55,7 +55,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)
|
||||
@@ -87,7 +87,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 = ""
|
||||
}
|
||||
|
||||
@@ -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.AskGo)
|
||||
for _, event := range []string{"ask-taken", "step-progress", "step-ended"} {
|
||||
if err := p.Say(event, nil, "id"); err != nil {
|
||||
|
||||
@@ -198,7 +198,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 {
|
||||
|
||||
@@ -58,6 +58,7 @@ func main() {
|
||||
// compiles that program and runs it shut off, answers its mark judged by the candidate at the tree's commit, and the
|
||||
// program reached no key, no login, no name and no socket of the machine.
|
||||
func TestTheUnitLevelUnderTheWorkspaceRunnerRunsTheTreesProgramShutOff(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the candidate's program shut off", "go", "git", "bwrap")
|
||||
home := t.TempDir()
|
||||
key, login := filepath.Join(home, ".ssh", "mesh_ed25519"), filepath.Join(home, "broker")
|
||||
|
||||
@@ -195,6 +195,7 @@ func TestACandidateThatDoesNotCompileFailsTheStepWithTheCompilersFirstErrorAndRu
|
||||
}
|
||||
|
||||
func TestTheInstalledProgramSaysItJudged(t *testing.T) { // 1898 K1, ADR 0535 §5
|
||||
t.Parallel()
|
||||
m, states, ws, _ := workspaceFor(t, "slow")
|
||||
for _, runner := range []any{nil, RunnerInstalled} {
|
||||
args := map[string]any{"workspace": ws, "level": LevelUnit}
|
||||
@@ -223,6 +224,7 @@ func TestAnUnknownRunnerIsRefused(t *testing.T) { // 1898 K1
|
||||
}
|
||||
|
||||
func TestTheShutOffProcessRunsTheStepItIsAsked(t *testing.T) { // 1898 K2: the candidate's side of the spec
|
||||
t.Parallel()
|
||||
m, _, ws, calls := workspaceFor(t, "slow")
|
||||
m.Inside = true
|
||||
a := m.answer(context.Background(), levelSpec{Step: stepUnit, Workspace: ws, Packages: []string{"./..."}, Bound: UnitBound})
|
||||
|
||||
@@ -24,70 +24,7 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
)
|
||||
|
||||
// nodeEngineTree is the node-engine's repository as the checker places it beside this check (MESH_CHECK_BESIDE, the
|
||||
// repository mesh-host), and with it every Go module of the other repositories placed there (mesh-sdk, mesh-contracts,
|
||||
// mesh-delivery, mesh-networking, the catalogue's trunk) and of the catalogue under check, first, as candidates: the workspace lays those the
|
||||
// node-engine's composer requires at the zero version, transitively (workspaceOf), so they resolve as the group lays
|
||||
// them, wherever the composer lives. The test
|
||||
// builds the node-engine's real composer command from that tree; it does not stand one in. With no beside directory it
|
||||
// fails, and with the node-engine beside but no composer command in it it fails: a composer test that could not build its
|
||||
// composer proves nothing. With a beside directory that holds no node-engine at all it skips aloud (NOT JUDGED), since a
|
||||
// checker from before this release places none for the catalogue.
|
||||
func nodeEngineTree(t *testing.T) (tree string, modules []string) {
|
||||
t.Helper()
|
||||
beside := os.Getenv("MESH_CHECK_BESIDE")
|
||||
if beside == "" {
|
||||
t.Fatal("NOT CHECKED: MESH_CHECK_BESIDE is not set, so the node-engine's repository (mesh-host) is not beside this check")
|
||||
}
|
||||
tree = filepath.Join(beside, "mesh-host")
|
||||
if !dirExists(tree) {
|
||||
// A checker from before novox/hq ADR 0593 places only mesh-sdk beside a catalogue check, so the node-engine's
|
||||
// repository is absent, not wrong: said aloud, since nothing here could build a composer to judge.
|
||||
t.Skipf("NOT JUDGED: the node-engine's repository (mesh-host) is not beside this check in MESH_CHECK_BESIDE=%s; the running checker places none for the catalogue, so the composer is judged only once it does", beside)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tree, "cmd", "mesh-compose")); err != nil {
|
||||
t.Fatalf("NOT CHECKED: the node-engine's composer command is not beside this check in MESH_CHECK_BESIDE=%s: %v", beside, err)
|
||||
}
|
||||
entries, err := os.ReadDir(beside)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var roots []string
|
||||
for _, e := range entries {
|
||||
if e.Name() == "mesh-host" || !dirExists(filepath.Join(beside, e.Name())) {
|
||||
continue
|
||||
}
|
||||
root, err := filepath.EvalSymlinks(filepath.Join(beside, e.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roots = append(roots, root)
|
||||
}
|
||||
// The catalogue under check, first: beside lies its trunk (issue 1295), whose modules a head's must win over.
|
||||
catalogue, err := filepath.Abs(filepath.Join("..", "..", "..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, root := range append([]string{catalogue}, roots...) {
|
||||
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() && (d.Name() == ".git" || d.Name() == "testdata" || d.Name() == "node_modules") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if !d.IsDir() && d.Name() == "go.mod" {
|
||||
modules = append(modules, filepath.Dir(p))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return tree, modules
|
||||
}
|
||||
|
||||
func dirExists(p string) bool { st, err := os.Stat(p); return err == nil && st.IsDir() }
|
||||
|
||||
// copyTree copies the files of a source tree into dst, leaving out its .git.
|
||||
// copyHostTree copies the files of a source tree into dst, leaving out its .git.
|
||||
func copyHostTree(t *testing.T, src, dst string) {
|
||||
t.Helper()
|
||||
src, err := filepath.EvalSymlinks(src)
|
||||
@@ -130,7 +67,7 @@ func goEnvOf(t *testing.T, name string) string {
|
||||
}
|
||||
|
||||
// 1622/AC1, AC3 against the real bus (ADR 0593 §7, C9): a compose ask put on the Go build seat's check stream is pulled by
|
||||
// the module started whole on that bus, which fetches the commit (the node-engine's repository beside the check, its Go module at the root), builds the composer command the ask names there with nothing fetched, fills the
|
||||
// the module started whole on that bus, which fetches the commit (a stand-in composer of this module's testdata, its Go module at the root), builds the composer command the ask names there with nothing fetched, fills the
|
||||
// request's manifests from the indexer's state and runs the composer; the step key <node>.<ask id> passes with the
|
||||
// composer's verdict. A second ask of the same commit runs the kept composer: fetched and built once.
|
||||
func TestAComposeAskIsBuiltOnceAndAnsweredOnTheBus(t *testing.T) {
|
||||
@@ -157,14 +94,11 @@ func TestAComposeAskIsBuiltOnceAndAnsweredOnTheBus(t *testing.T) {
|
||||
m.Run = StepRunner(t.TempDir())
|
||||
m.GoModCache = goEnvOf(t, "GOMODCACHE") // the module cache this module's own build filled, read and not fetched
|
||||
run, gocache := m.Run, goEnvOf(t, "GOCACHE") // this machine's build cache, so the composer's packages compile once
|
||||
hostTree, beside := nodeEngineTree(t)
|
||||
workFile := ""
|
||||
// The composer is a stand-in of this module's own testdata (design 47 G A-474: a module's tests read nothing outside it, and a
|
||||
// pipeline's step places no other repository beside the tree): a program of the composer's contract that imports nothing.
|
||||
hostTree := filepath.Join("testdata", "composer")
|
||||
m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
env = append(env, "GOCACHE="+gocache)
|
||||
if workFile != "" {
|
||||
env = append(env, "GOWORK="+workFile, "GOFLAGS=-mod=readonly") // a workspace takes no -mod=mod
|
||||
}
|
||||
return run(ctx, env, name, args...)
|
||||
return run(ctx, append(env, "GOCACHE="+gocache), name, args...)
|
||||
}
|
||||
read, digests := catalogHolds(t, `{"module":"demo","version":"1"}`)
|
||||
m.ReadEntry = read
|
||||
@@ -181,18 +115,6 @@ func TestAComposeAskIsBuiltOnceAndAnsweredOnTheBus(t *testing.T) {
|
||||
return nil, err
|
||||
}
|
||||
copyHostTree(t, hostTree, tree)
|
||||
if len(beside) > 0 { // the group's other repositories, laid beside the node-engine's tree as one workspace
|
||||
work, err := workspaceOf(tree, beside)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(m.Work, ws, "go.work"), []byte(work), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
workFile = filepath.Join(m.Work, ws, "go.work")
|
||||
// Nothing is downloaded here: this level has no network. The check's own fetch downloaded this workspace's
|
||||
// graph (downloadBeside), and a module it lacks fails the build naming it.
|
||||
}
|
||||
return map[string]any{"workspace": ws}, nil
|
||||
}
|
||||
}
|
||||
@@ -203,7 +125,7 @@ func TestAComposeAskIsBuiltOnceAndAnsweredOnTheBus(t *testing.T) {
|
||||
|
||||
ask := func() sdkstep.Step {
|
||||
a := composeAskOf(t, digests[0])
|
||||
a.Compose.Fetch.Repository, a.Compose.Dir, a.Compose.Package = "novox/mesh-host", catalogclient.RootPath, "github.com/novox/mesh-host/cmd/mesh-compose"
|
||||
a.Compose.Fetch.Repository, a.Compose.Dir, a.Compose.Package = "novox/mesh-catalog", catalogclient.RootPath, "standin/cmd/mesh-compose"
|
||||
raw, err := sdkstep.EncodeStepAsk(a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func (m *Module) digestHere(ctx context.Context, workspace, level string, names
|
||||
namesHeader = []string{"node-names " + strings.Join(sortedNames, ",")}
|
||||
}
|
||||
|
||||
dirs, err := m.goModDirs(ctx, tree)
|
||||
dirs, err := m.testDirs(ctx, tree)
|
||||
if err != nil {
|
||||
return DigestResult{}, err
|
||||
}
|
||||
|
||||
@@ -273,6 +273,7 @@ func TestAPackageWithTheReadsOutsideMarkerIsKeptOnlyByWhatItLists(t *testing.T)
|
||||
}
|
||||
edit(t, tree, "docs/one.md", "one\n")
|
||||
edit(t, tree, "other.md", "other\n")
|
||||
// Each marker is judged in a fixture of its own, side by side: the digests are go commands, and the table is the test's longest part.
|
||||
for name, marker := range map[string]string{
|
||||
"an empty marker": "# nothing listed\n\n",
|
||||
"a sentence": "the tests read ../docs\n",
|
||||
@@ -282,19 +283,44 @@ func TestAPackageWithTheReadsOutsideMarkerIsKeptOnlyByWhatItLists(t *testing.T)
|
||||
"a path that is not clean": "docs/./one.md\n",
|
||||
"a good line and a bad line": "docs\nnope/*.md\n",
|
||||
} {
|
||||
edit(t, tree, "c/"+ReadsOutsideMarker, marker)
|
||||
first, second := digests(t, m, "unit"), digests(t, m, "unit")
|
||||
if len(first.Packages[c]) != 64 || first.Packages[c] == second.Packages[c] || first.Packages[c] == plain.Packages[c] {
|
||||
t.Errorf("%s: c's digest is stable: %s, %s, before %s", name, first.Packages[c], second.Packages[c], plain.Packages[c])
|
||||
}
|
||||
if strings.Join(first.ReadsOutside, ",") != c {
|
||||
t.Errorf("%s: the answer does not name the package that reads outside: %v", name, first.ReadsOutside)
|
||||
}
|
||||
if first.Packages[a] != plain.Packages[a] || first.Packages[a] != second.Packages[a] {
|
||||
t.Errorf("%s: a has no marker and its digest moved: %s, %s, before %s", name, first.Packages[a], second.Packages[a], plain.Packages[a])
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, tree := digestFixture(t)
|
||||
plain := digests(t, m, "unit")
|
||||
if err := os.MkdirAll(filepath.Join(tree, "docs"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
edit(t, tree, "docs/one.md", "one\n")
|
||||
edit(t, tree, "other.md", "other\n")
|
||||
edit(t, tree, "c/"+ReadsOutsideMarker, marker)
|
||||
first, second := digests(t, m, "unit"), digests(t, m, "unit")
|
||||
if len(first.Packages[c]) != 64 || first.Packages[c] == second.Packages[c] || first.Packages[c] == plain.Packages[c] {
|
||||
t.Errorf("%s: c's digest is stable: %s, %s, before %s", name, first.Packages[c], second.Packages[c], plain.Packages[c])
|
||||
}
|
||||
if strings.Join(first.ReadsOutside, ",") != c {
|
||||
t.Errorf("%s: the answer does not name the package that reads outside: %v", name, first.ReadsOutside)
|
||||
}
|
||||
if first.Packages[a] != plain.Packages[a] || first.Packages[a] != second.Packages[a] {
|
||||
t.Errorf("%s: a has no marker and its digest moved: %s, %s, before %s", name, first.Packages[a], second.Packages[a], plain.Packages[a])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// The marker that lists what the package's tests read, and the marker of what the package needs (issue 890/AC3): in a fixture of its
|
||||
// own, so it runs beside the table above.
|
||||
func TestAListedReadsOutsideMarkerKeepsTheDigestOfOnlyWhatItLists(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, tree := digestFixture(t)
|
||||
plain := digests(t, m, "unit")
|
||||
c, a := "fixture/digest/c", "fixture/digest/a"
|
||||
if err := os.MkdirAll(filepath.Join(tree, "docs"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
edit(t, tree, "docs/one.md", "one\n")
|
||||
edit(t, tree, "other.md", "other\n")
|
||||
|
||||
// A list: a glob, a directory read whole, and a path whose absence is read.
|
||||
edit(t, tree, "c/"+ReadsOutsideMarker, "# what c's tests read\ndocs/*.md\ndocs\n?gone\n")
|
||||
before := digests(t, m, "unit")
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestTheGuardSaysToolchainReportedOnAChangeWithTheProgramDigest(t *testing.T
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].subject != "mesh.seat.node-build-go.event.toolchain-reported.ace" || got[0].body["node"] != "ace" || got[0].body["language"] != "go" ||
|
||||
got[0].body["version"] != "go1.27.1" || got[0].body["recipe"] != m.Recipe.Version() || len(got[0].body["digest"]) != len("sha256:")+64 {
|
||||
got[0].body["version"] != "go1.27" || got[0].body["recipe"] != m.Recipe.Version() || len(got[0].body["digest"]) != len("sha256:")+64 {
|
||||
t.Fatalf("events = %+v, want one toolchain-reported for ace, go with the program's digest", got)
|
||||
}
|
||||
if tc, _ := states.toolchain("ace.go"); tc.Digest != got[0].body["digest"] {
|
||||
@@ -51,7 +51,7 @@ func TestTheGuardSaysToolchainReportedOnAChangeWithTheProgramDigest(t *testing.T
|
||||
os.WriteFile(prog, []byte("another go program"), 0o755)
|
||||
m.Probe = func(context.Context) (string, error) { return "go1.27.2", nil }
|
||||
m.Check(context.Background())
|
||||
if len(got) != 2 || got[1].body["version"] != "go1.27.2" || got[1].body["digest"] == got[0].body["digest"] {
|
||||
if len(got) != 2 || got[1].body["version"] != "go1.27" || got[1].body["digest"] == got[0].body["digest"] {
|
||||
t.Errorf("a new version said %+v, want a second event with another digest", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/mod/modfile"
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
dforgekey "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/forgekey"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
@@ -106,6 +108,8 @@ func (m *Module) fetch(ctx context.Context, args map[string]any) (res any, err e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A fetch with no dir (the checker's check of a pull request, until G removes the checker; A-447e) fetches the tree
|
||||
// whole: every go.mod of it.
|
||||
siblings, err := siblingsArg(args["beside"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -165,6 +169,20 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dir := cleanDir(req.Dir); dir != "" {
|
||||
// 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 {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, scopeMark), []byte(strings.Join(dirs, "\n")), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, moduleDirMark), []byte(dir), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
res.Modules = dirs
|
||||
if base != "" && res.Merge == "" {
|
||||
return res, nil // a conflict: the tree is at the trunk, nothing of the head is built or tested
|
||||
@@ -313,7 +331,13 @@ func (m *Module) shutOffLoad(ctx context.Context, env []string, dir, d string, j
|
||||
if _, err := os.Stat(filepath.Join(dir, "vendor", "modules.txt")); err == nil {
|
||||
return nil // a directory that vendors is read from its vendor directory, never through the module cache
|
||||
}
|
||||
missing, err := ownFilesCover(dir, loaded)
|
||||
// The files the steps build with: a directory with a temporary modfile (an asked version, a pin) is built with it and
|
||||
// the sums beside it, which hold the requirements of the versions taken (takeRequirementsOf).
|
||||
files := dir
|
||||
if modfile, ok := m.pinModfile(dir); ok {
|
||||
files = filepath.Dir(modfile)
|
||||
}
|
||||
missing, err := ownFilesCover(files, loaded)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the go.mod and go.sum of %s: %w", d, err)
|
||||
}
|
||||
@@ -324,7 +348,7 @@ func (m *Module) shutOffLoad(ctx context.Context, env []string, dir, d string, j
|
||||
return nil
|
||||
}
|
||||
|
||||
// ownFilesCover is what the go.mod and go.sum in dir lack for the modules its packages load, each as the line it lacks:
|
||||
// ownFilesCover is what the go.mod and go.sum in dir (a directory's own, or those of its temporary modfile) lack for the modules its packages load, each as the line it lacks:
|
||||
// a mesh module (of the forge) required, the line it lacks naming the zero version (ADR 0573 §2; one named at a commit
|
||||
// is built against the asked version all the same, §4, and needs no lookup), every other required at the version the
|
||||
// load selected, with its two go.sum lines (the module's and its go.mod's) for the version Go reads it at. A module
|
||||
@@ -434,7 +458,11 @@ func (m *Module) downloadAndVerify(ctx context.Context, dir, d string) error {
|
||||
}
|
||||
|
||||
// goModDirs are the directories of the tree that hold a go.mod, relative to it, in order.
|
||||
// When the fetch was asked with a module's directory (scopeMark), the steps after it see only the directories it chose.
|
||||
func (m *Module) goModDirs(ctx context.Context, tree string) ([]string, error) {
|
||||
if b, err := os.ReadFile(filepath.Join(filepath.Dir(tree), scopeMark)); err == nil {
|
||||
return strings.Fields(string(b)), nil
|
||||
}
|
||||
r := m.Run(ctx, nil, "git", "-C", tree, "ls-files", "--", "go.mod", "*/go.mod")
|
||||
if r.Status != 0 || r.Err != "" {
|
||||
return nil, fmt.Errorf("git ls-files: %s", dforgekey.Said(r.Err+"\n"+r.Stderr))
|
||||
@@ -454,6 +482,27 @@ func (m *Module) goModDirs(ctx context.Context, tree string) ([]string, error) {
|
||||
return dirs, nil
|
||||
}
|
||||
|
||||
// testDirs are the directories the unit and integration steps and the digest take: the chosen go.mod directories at or
|
||||
// under the module's own directory. A directory the module's go.mod replaces from outside its own stays for download and
|
||||
// resolution alone; its tests are another module's (design 47 G, A-447c). A workspace fetched with no dir keeps every go.mod.
|
||||
func (m *Module) testDirs(ctx context.Context, tree string) ([]string, error) {
|
||||
all, err := m.goModDirs(ctx, tree)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
own, ok := moduleDirOf(tree)
|
||||
if !ok || own == "." || own == "" {
|
||||
return all, nil
|
||||
}
|
||||
out := []string{}
|
||||
for _, d := range all {
|
||||
if d == own || strings.HasPrefix(d, own+"/") {
|
||||
out = append(out, d)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// inTestdata says a path lies under a directory named testdata, whose go.mod files are fixtures Go ignores, not modules
|
||||
// of the tree (issue 1810).
|
||||
func inTestdata(path string) bool {
|
||||
@@ -608,3 +657,85 @@ func narrowed(tree string) bool {
|
||||
_, err := os.Stat(filepath.Join(filepath.Dir(tree), narrowedMark))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// scopeMark is the file beside a workspace's tree naming the Go module directories a fetch asked with a module's
|
||||
// directory chose, one to a line (empty: none).
|
||||
const scopeMark = "gomodules"
|
||||
|
||||
// moduleDirMark is the file beside a workspace's tree naming the module directory the fetch was asked with: the one
|
||||
// module.json a step compares generated files for (design 47 G, A-447c).
|
||||
const moduleDirMark = "moduledir"
|
||||
|
||||
// moduleDirOf is the module directory the workspace of tree was fetched for, ok false for a workspace with none.
|
||||
func moduleDirOf(tree string) (string, bool) {
|
||||
b, err := os.ReadFile(filepath.Join(filepath.Dir(tree), moduleDirMark))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return string(b), true
|
||||
}
|
||||
|
||||
// cleanDir is a request's module directory in the form goModDirs lists, "" for none.
|
||||
func cleanDir(dir string) string {
|
||||
if strings.TrimSpace(dir) == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.Trim(filepath.ToSlash(filepath.Clean(dir)), "/")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
have := map[string]bool{}
|
||||
for _, d := range all {
|
||||
have[d] = true
|
||||
}
|
||||
chosen := map[string]bool{}
|
||||
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).
|
||||
todo = nil
|
||||
for _, d := range all {
|
||||
if dir == "." || strings.HasPrefix(d, dir+"/") {
|
||||
todo = append(todo, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
for len(todo) > 0 {
|
||||
d := todo[0]
|
||||
todo = todo[1:]
|
||||
if chosen[d] || !have[d] {
|
||||
continue
|
||||
}
|
||||
chosen[d] = true
|
||||
file := filepath.Join(tree, filepath.FromSlash(d), "go.mod")
|
||||
body, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := modfile.Parse(file, body, nil) // not ParseLax: that one ignores the replaces
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
for _, r := range f.Replace {
|
||||
if !modfile.IsDirectoryPath(r.New.Path) {
|
||||
continue
|
||||
}
|
||||
target := filepath.ToSlash(filepath.Clean(filepath.Join(filepath.FromSlash(d), filepath.FromSlash(r.New.Path))))
|
||||
todo = append(todo, target)
|
||||
}
|
||||
}
|
||||
out := []string{}
|
||||
for _, d := range all {
|
||||
if chosen[d] {
|
||||
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)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -61,6 +61,13 @@ func (f *fakeStep) run(ctx context.Context, env []string, name string, args ...s
|
||||
os.MkdirAll(filepath.Dir(filepath.Join(args[i+1], name)), 0o755)
|
||||
os.WriteFile(filepath.Join(args[i+1], name), []byte(text), 0o644)
|
||||
}
|
||||
// Every go.mod the fake lists exists, since a fetch asked with a directory reads its go.mod (A-447).
|
||||
for _, l := range strings.Fields(f.gomods) {
|
||||
if _, err := os.Stat(filepath.Join(args[i+1], l)); err != nil && f.files[l] == "" {
|
||||
os.MkdirAll(filepath.Dir(filepath.Join(args[i+1], l)), 0o755)
|
||||
os.WriteFile(filepath.Join(args[i+1], l), []byte("module fake\n"), 0o644)
|
||||
}
|
||||
}
|
||||
for _, v := range f.vendors {
|
||||
os.MkdirAll(filepath.Join(args[i+1], v, "vendor"), 0o755)
|
||||
os.WriteFile(filepath.Join(args[i+1], v, "vendor", "modules.txt"), nil, 0o644)
|
||||
@@ -91,7 +98,24 @@ func fetchModule(t *testing.T, f *fakeStep) (*Module, *keptStates) {
|
||||
return m, states
|
||||
}
|
||||
|
||||
// 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) {
|
||||
t.Helper()
|
||||
raw := rawFetchTool(t, m)
|
||||
return func(args map[string]any) (any, error) {
|
||||
if _, ok := args["dir"]; !ok {
|
||||
named := map[string]any{"dir": "."}
|
||||
for k, v := range args {
|
||||
named[k] = v
|
||||
}
|
||||
args = named
|
||||
}
|
||||
return raw(args)
|
||||
}
|
||||
}
|
||||
|
||||
func rawFetchTool(t *testing.T, m *Module) func(map[string]any) (any, error) {
|
||||
t.Helper()
|
||||
for _, tool := range m.Tools(m.StepTools()) {
|
||||
if tool.Name == "build_go_fetch" {
|
||||
@@ -107,7 +131,9 @@ var fetchArgs = map[string]any{"repository": "novox/mesh-sdk", "commit": commitS
|
||||
// 1485/AC1: git is asked through FetchCommit with the ssh remote, and go mod download and verify run in each go.mod
|
||||
// directory (not in one that vendors) with GOTOOLCHAIN=local, GOFLAGS=-mod=mod and the module's cache paths.
|
||||
func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
|
||||
f := &fakeStep{gomods: "go.mod\nsub/dir/go.mod\nvend/go.mod\n", vendors: []string{"vend"}}
|
||||
// The root go.mod replaces the other two by directory: a fetch asked with a module's directory chooses what it replaces.
|
||||
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"}}
|
||||
m, states := fetchModule(t, f)
|
||||
if _, err := fetchTool(t, m)(fetchArgs); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -270,7 +296,8 @@ func TestAVerifyThatFailsEndsTheStepNamingTheDirectoryAndTheLine(t *testing.T) {
|
||||
return forgekey.Ran{}
|
||||
}}
|
||||
m, states := fetchModule(t, f)
|
||||
if _, err := fetchTool(t, m)(fetchArgs); err != nil {
|
||||
// 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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := states.waitEnd(t)
|
||||
|
||||
@@ -2,9 +2,13 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
)
|
||||
|
||||
@@ -25,3 +29,123 @@ func TestGoModDirsLeaveOutTheFixturesUnderTestdata(t *testing.T) {
|
||||
t.Fatalf("go.mod directories = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A-447: a fetch asked with a module's directory chooses that Go module and the directories its go.mod replaces with a
|
||||
// local path, through their own replaces; the later steps list the same. The takein module of the indexer is no module
|
||||
// of the assigner's build (live, 2026-11-16).
|
||||
func TestAFetchAskedWithADirectoryChoosesItsModuleAndWhatItReplacesAlone(t *testing.T) {
|
||||
all := []string{".", "modules/assigner", "modules/indexer", "modules/indexer/takein", "modules/lib", "modules/lib/deep", "modules/other", "rootless/x/go", "seats/a", "seats/b"}
|
||||
mods := map[string]string{
|
||||
"modules/assigner": "module a\nreplace x => ../lib\nreplace (\n\ty => ../../outside\n\tz v1.0.0 => z v1.1.0\n)\n",
|
||||
"modules/indexer": "module i\nreplace t => ./takein\n",
|
||||
"modules/indexer/takein": "module t\n",
|
||||
"modules/lib": "module l\nreplace d => ./deep\n",
|
||||
"modules/lib/deep": "module d\n",
|
||||
"modules/other": "module o\n",
|
||||
".": "module r\n",
|
||||
"seats/a": "module sa\nreplace q => ../q\n",
|
||||
"seats/b": "module sb\n",
|
||||
"rootless/x/go": "module rx\n",
|
||||
}
|
||||
for _, c := range []struct {
|
||||
dir string
|
||||
want []string
|
||||
}{
|
||||
{"modules/assigner", []string{"modules/assigner", "modules/lib", "modules/lib/deep"}},
|
||||
{"modules/indexer", []string{"modules/indexer", "modules/indexer/takein"}},
|
||||
{"modules/other/", []string{"modules/other"}},
|
||||
{"modules/lib/deep/", []string{"modules/lib/deep"}},
|
||||
{"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
|
||||
} {
|
||||
tree := t.TempDir()
|
||||
for d, body := range mods {
|
||||
if err := os.MkdirAll(filepath.Join(tree, d), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(tree, d, "go.mod"), []byte(body), 0o600); err != nil {
|
||||
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
|
||||
}
|
||||
if err != nil || !reflect.DeepEqual(got, c.want) {
|
||||
t.Errorf("dir %q chooses %v, %v; want %v", c.dir, got, err, c.want)
|
||||
}
|
||||
}
|
||||
// What the steps after the fetch list is what the fetch chose, beside the tree.
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, scopeMark), []byte("modules/assigner\nmodules/lib"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := &Module{}
|
||||
got, err := m.goModDirs(context.Background(), filepath.Join(root, "tree"))
|
||||
if err != nil || !reflect.DeepEqual(got, []string{"modules/assigner", "modules/lib"}) {
|
||||
t.Errorf("the later steps list %v, %v", got, err)
|
||||
}
|
||||
if cleanDir("") != "" || cleanDir(".") != "." {
|
||||
t.Errorf("cleanDir of nothing = %q, of . = %q", cleanDir(""), cleanDir("."))
|
||||
}
|
||||
}
|
||||
|
||||
// A-447e: a fetch with no dir (the checker's check of a pull request, until G removes the checker) fetches the tree whole:
|
||||
// it chooses every go.mod of it.
|
||||
func TestAFetchWithNoDirectoryChoosesEveryGoModOfTheTree(t *testing.T) {
|
||||
f := &fakeStep{gomods: "go.mod\nsub/go.mod\n"}
|
||||
m, states := fetchModule(t, f)
|
||||
if _, err := rawFetchTool(t, m)(map[string]any{"repository": "novox/mesh-sdk", "commit": commitSHA}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := states.waitEnd(t)
|
||||
if st.State != sdkstep.StepPassed || !strings.Contains(string(st.Result), `"modules":[".","sub"]`) {
|
||||
t.Fatalf("a fetch with no dir ended %s: %q %s", st.State, st.Reason, st.Result)
|
||||
}
|
||||
}
|
||||
|
||||
// A-447c: the unit level of a module whose go.mod replaces ../lib tests the module alone; lib is downloaded and resolved
|
||||
// for it, and its tests are another module's.
|
||||
func TestTheUnitLevelTestsOnlyTheModulesOwnDirectoriesNotWhatItReplaces(t *testing.T) {
|
||||
f := &fakeStep{}
|
||||
m, _ := fetchModule(t, f)
|
||||
root := filepath.Join(m.Work, "ws1")
|
||||
tree := filepath.Join(root, "tree")
|
||||
for d, body := range map[string]string{"mod": "module example.org/mod\nreplace example.org/lib => ../lib\n", "lib": "module example.org/lib\n"} {
|
||||
if err := os.MkdirAll(filepath.Join(tree, d), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(tree, d, "go.mod"), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for name, body := range map[string]string{scopeMark: "lib\nmod", moduleDirMark: "mod"} {
|
||||
if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
dirs, err := m.testDirs(context.Background(), tree)
|
||||
if err != nil || !reflect.DeepEqual(dirs, []string{"mod"}) {
|
||||
t.Fatalf("the test directories = %v, %v; want mod alone", dirs, err)
|
||||
}
|
||||
if _, err := m.runLevel(context.Background(), tree, levelOpts{workspace: "ws1", level: LevelUnit}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, l := range f.lines() {
|
||||
if strings.Contains(l, "/tree/lib test") {
|
||||
t.Errorf("the module's unit level tested lib: %s", l)
|
||||
}
|
||||
}
|
||||
// No dir asked: every go.mod of the tree stays.
|
||||
if err := os.Remove(filepath.Join(root, moduleDirMark)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dirs, _ = m.testDirs(context.Background(), tree); len(dirs) != 2 {
|
||||
t.Errorf("a workspace with no module directory tests %v, want every go.mod", dirs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,8 +149,8 @@ func TestAnyInstalledGoIsHealthyNamedAndReported(t *testing.T) {
|
||||
t.Errorf("health = %+v, want healthy naming %s", a, installed)
|
||||
}
|
||||
tc, ok := states.toolchain("ace.go")
|
||||
if !ok || tc.Version != installed || tc.Recipe != m.Recipe.Version() {
|
||||
t.Errorf("ace.go = %+v, %v; want version %s and recipe %s", tc, ok, installed, m.Recipe.Version())
|
||||
if !ok || tc.Version != sdkstep.LanguageVersion(installed) || tc.Recipe != m.Recipe.Version() {
|
||||
t.Errorf("ace.go = %+v, %v; want version %s and recipe %s", tc, ok, sdkstep.LanguageVersion(installed), m.Recipe.Version())
|
||||
}
|
||||
ran := false
|
||||
run := func(context.Context, map[string]any) (any, error) { ran = true; return "done", nil }
|
||||
|
||||
@@ -58,7 +58,7 @@ func (m *Module) integrationHere(ctx context.Context, workspace, tree string, pa
|
||||
defer os.RemoveAll(run)
|
||||
|
||||
began := m.clock()
|
||||
dirs, err := m.goModDirs(ctx, tree)
|
||||
dirs, err := m.testDirs(ctx, tree)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -186,6 +186,7 @@ func TestABuildRunsShutOffAndOnlyATrunkBuildWritesTheCaches(t *testing.T) {
|
||||
|
||||
// 1309-S3: the digest's go list runs shut off.
|
||||
func TestTheDigestListsPackagesShutOff(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, _ := digestFixture(t)
|
||||
var seen []shutOff
|
||||
m.Run = throughBubblewrap(t, m.Run, &seen)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
// resolves no name, reaches no socket of the machine (a TCP port on its loopback, a unix socket) and leaves the shared
|
||||
// caches unchanged. The probe is testdata/repos/probe.
|
||||
func TestARunStepReachesNoKeyLoginNameOrSocketAndLeavesTheCachesUnchanged(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the shut-off unit level", "go", "git", "bwrap")
|
||||
tree := repository(t, "probe")
|
||||
work, err := os.MkdirTemp("", "w")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
)
|
||||
|
||||
// A directory built with a temporary modfile (an asked version, a pin) is judged by the modfile and the sums beside it, the
|
||||
// files its steps build with, and not by its own go.mod and go.sum: the requirements of an asked version of a mesh package
|
||||
// are in the modfile (takeRequirementsOf), and the directory's own files lack them.
|
||||
func TestADirectoryWithAModfileIsJudgedByTheModfileAndItsSums(t *testing.T) {
|
||||
const nats = "github.com/nats-io/nats.go"
|
||||
for _, c := range []struct {
|
||||
name, modfile, sums string
|
||||
lacks bool
|
||||
}{
|
||||
{name: "the modfile names it with its sums", modfile: "require " + nats + " v1.54.0\n", sums: nats + " v1.54.0 h1:a=\n" + nats + " v1.54.0/go.mod h1:b=\n"},
|
||||
{name: "the modfile lacks it", modfile: "", sums: "", lacks: true},
|
||||
{name: "the modfile names it and the sums lack it", modfile: "require " + nats + " v1.54.0\n", sums: nats + " v1.54.0 h1:a=\n", lacks: true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
m := &Module{Work: t.TempDir()}
|
||||
dir := filepath.Join(m.Work, "ws", "tree", "mod")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := "module fixture/mod\n\ngo 1.26\n\n"
|
||||
// The directory's own files lack the requirement, whatever the modfile holds.
|
||||
os.WriteFile(filepath.Join(dir, "go.mod"), []byte(head), 0o644)
|
||||
pins := m.pinsDir(dir)
|
||||
os.MkdirAll(pins, 0o755)
|
||||
os.WriteFile(filepath.Join(pins, "go.mod"), []byte(head+c.modfile), 0o644)
|
||||
os.WriteFile(filepath.Join(pins, "go.sum"), []byte(c.sums), 0o644)
|
||||
m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
return forgekey.Ran{Stdout: loadedModuleMark + nats + " v1.54.0\n"}
|
||||
}
|
||||
err := m.shutOffLoad(context.Background(), nil, dir, "mod", true)
|
||||
if c.lacks != (err != nil) || (err != nil && !strings.Contains(err.Error(), "lacking")) {
|
||||
t.Errorf("shutOffLoad = %v, want a refusal naming what is lacking: %v", err, c.lacks)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -56,3 +56,19 @@ 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))
|
||||
}
|
||||
|
||||
// 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())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -87,8 +87,9 @@ func main() {
|
||||
go func() {
|
||||
<-stdio.Served()
|
||||
if err := findings.Start(ctx); err != nil {
|
||||
logf("the finding writer: %v", err)
|
||||
os.Exit(1)
|
||||
// Said, and the module goes on serving: a finding writer that cannot hear its asks keeps its findings
|
||||
// in its state alone, as the indexer does (lead answer A-394); its builds and steps never wait on it.
|
||||
logf("the finding writer cannot start, its findings are kept in the state alone: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -195,6 +195,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 {
|
||||
|
||||
@@ -158,6 +158,7 @@ func sleepABit() { time.Sleep(30 * time.Millisecond) }
|
||||
// The workspace is self-contained after the fetch: no alternates file, and git finds the commit with the mirror gone,
|
||||
// as a step shut off with the workspace alone needs. Real git, a local repository as the forge.
|
||||
func TestTheWorkspaceIsSelfContainedAfterAFetchThroughTheMirror(t *testing.T) {
|
||||
t.Parallel()
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("no git")
|
||||
}
|
||||
@@ -176,6 +177,10 @@ func TestTheWorkspaceIsSelfContainedAfterAFetchThroughTheMirror(t *testing.T) {
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
git(src, "init", "-q")
|
||||
// A fetch is for one module (A-447b): the repository holds a module at its root.
|
||||
if err := os.WriteFile(filepath.Join(src, "go.mod"), []byte("module example.org/x\n\ngo 1.26\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(src, "f.txt"), []byte("one\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -119,7 +116,7 @@ type Module struct {
|
||||
// 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
|
||||
|
||||
@@ -93,8 +93,8 @@ func TestStartWritesTheToolchainAndHealthIsHealthy(t *testing.T) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if tc.Version != "go1.27.1" || tc.Recipe != m.Recipe.Version() || tc.Language != "go" {
|
||||
t.Fatalf("ace.go = %+v, want go1.27.1 and recipe %s", tc, m.Recipe.Version())
|
||||
if tc.Version != "go1.27" || tc.Recipe != m.Recipe.Version() || tc.Language != "go" {
|
||||
t.Fatalf("ace.go = %+v, want go1.27 and recipe %s", tc, m.Recipe.Version())
|
||||
}
|
||||
if a := m.Health(ctx); a.State != health.StateHealthy || !a.Healthy {
|
||||
t.Errorf("health = %+v, want healthy", a)
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestAFetchWithNamedPathsNarrowsTheWorkspace(t *testing.T) {
|
||||
if strings.Join(res.Modules, ",") != "lib" {
|
||||
t.Errorf("the fetch answered the modules %v, want lib alone", res.Modules)
|
||||
}
|
||||
_, st = fetched(t, m, states, map[string]any{"repository": "novox/narrow", "commit": head, "paths": []any{"cmd"}})
|
||||
_, 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)
|
||||
}
|
||||
|
||||
@@ -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 := ""
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
// 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.
|
||||
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).
|
||||
for _, tool := range []string{"go", "git"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
|
||||
@@ -50,7 +50,15 @@ func newPinHarness(t *testing.T, gomod string, vendor bool, pulls string) (*pinH
|
||||
for _, g := range strings.Fields(f.gomods) {
|
||||
d := filepath.Join(args[i+1], filepath.Dir(g))
|
||||
os.MkdirAll(d, 0o755)
|
||||
os.WriteFile(filepath.Join(d, "go.mod"), []byte(gomod), 0o644)
|
||||
body := gomod
|
||||
if g == "go.mod" { // the root replaces the other directories, so a fetch asked with it chooses them (A-447)
|
||||
for _, o := range strings.Fields(f.gomods) {
|
||||
if o != "go.mod" {
|
||||
body += "\nreplace local/" + filepath.Dir(o) + " => ./" + filepath.Dir(o) + "\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
os.WriteFile(filepath.Join(d, "go.mod"), []byte(body), 0o644)
|
||||
os.WriteFile(filepath.Join(d, "go.sum"), []byte("sum\n"), 0o644)
|
||||
}
|
||||
if vendor {
|
||||
@@ -296,6 +304,7 @@ func TestARelativeReplaceStillResolvesInTheTemporaryModfile(t *testing.T) {
|
||||
// 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) {
|
||||
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"
|
||||
trunk := strings.Repeat("a", 40)
|
||||
|
||||
@@ -171,6 +171,7 @@ func TestRealFetchMergesConflictsAndPlainlyFetches(t *testing.T) {
|
||||
// sibling and passes with it; the sibling is a plain directory with no symlink in it; and a sibling that holds a
|
||||
// symlink fails the fetch naming it.
|
||||
func TestRealTestsReadTheSiblingBesideTheTree(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the shut-off unit level", "go", "git", "bwrap") // the tests run in bubblewrap (1309)
|
||||
f := newForge(t)
|
||||
files := map[string]string{}
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -36,7 +36,7 @@ func (m *Module) run(ctx context.Context, fetch steprun.StepFunc, a sdkstep.Step
|
||||
return nil, err
|
||||
}
|
||||
key := sdkstep.RunKey(job.Program, sdkstep.ToolchainUsed{Version: installed, Recipe: m.Recipe.Version()}, a.Packages)
|
||||
fetchArgs := sdkstep.FetchRequest{Repository: job.Program.Repository, Commit: job.Program.Commit, Packages: a.Packages}.Args()
|
||||
fetchArgs := sdkstep.FetchRequest{Repository: job.Program.Repository, Commit: job.Program.Commit, Dir: job.Program.Dir, Packages: a.Packages}.Args()
|
||||
exe, built, err := m.programOf(ctx, fetch, "programs", "checking program", key, fetchArgs, job.Program.Dir, job.Program.Package)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 <node>.<ask id>: 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
|
||||
}
|
||||
|
||||
@@ -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))})
|
||||
|
||||
@@ -118,6 +118,7 @@ func resolve(t *testing.T, addr string, a builds.BuiltArtifact) []byte {
|
||||
// reference resolves in a real artifact store to bytes of that digest. The build is the real go's, shut off, of the
|
||||
// fixture testdata/repos/build, with an archive beside its bundle.
|
||||
func TestADoneBuildsArtifactsResolveInARealArtifactStore(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the build", "go", "bwrap")
|
||||
work := t.TempDir()
|
||||
tree := filepath.Join(work, "ws1", "tree")
|
||||
|
||||
@@ -109,18 +109,22 @@ func (m *Module) test(ctx context.Context, args map[string]any) (any, error) {
|
||||
}
|
||||
|
||||
// compareGenerated regenerates the generated Go files of each contracts module in the tree (every module.json in the tree, in
|
||||
// any folder: ADR 0634 §8; CAT-BG5) and fails the level on any out of step, Why naming each path.
|
||||
// any folder: ADR 0634 §8; CAT-BG5; for a workspace fetched for a module's directory, that module's own alone) and fails the level on any out of step, Why naming each path.
|
||||
func compareGenerated(tree string, res *TestResult) error {
|
||||
dirs, err := steprun.ModuleDirs(tree)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
// A step for a module compares its own module.json alone, never another module's of the repository (A-447c).
|
||||
rel, _ := filepath.Rel(tree, dir)
|
||||
if own, ok := moduleDirOf(tree); ok && filepath.ToSlash(rel) != own {
|
||||
continue
|
||||
}
|
||||
paths, err := steprun.OutOfStep(dir, steprun.GeneratedRootGo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(tree, dir)
|
||||
for _, p := range paths {
|
||||
res.OutOfStep = append(res.OutOfStep, filepath.ToSlash(filepath.Join(rel, p)))
|
||||
}
|
||||
@@ -252,7 +256,7 @@ type levelOpts struct {
|
||||
|
||||
// runLevel runs `go test -json` in each go.mod directory of the tree and judges the whole against the bounds.
|
||||
func (m *Module) runLevel(ctx context.Context, tree string, o levelOpts) (*TestResult, error) {
|
||||
dirs, err := m.goModDirs(ctx, tree)
|
||||
dirs, err := m.testDirs(ctx, tree)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ func repository(t *testing.T, name string) string {
|
||||
// test_test.go read the output captured from them, and this one proves the capture is what the real go says today. It
|
||||
// starts go test, so it carries the tag.
|
||||
func TestUnitLevelRunsTheRealGoOnTheFixtureRepositories(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the unit level on fixtures", "go", "git", "bwrap")
|
||||
want := map[string]struct {
|
||||
passed, noTests bool
|
||||
@@ -104,6 +105,7 @@ func TestUnitLevelRunsTheRealGoOnTheFixtureRepositories(t *testing.T) {
|
||||
// 086 A-C3 against the real go (design 47 line 571 at b229f5c4): a tree holding an unformatted file passes its unit
|
||||
// level, its two tests run, and the lint step's body fails naming the file.
|
||||
func TestAnUnformattedFileFailsTheRealLintStepAndNotTheUnitLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the unit level's gofmt and vet", "go", "git", "bwrap")
|
||||
home := t.TempDir()
|
||||
m := &Module{Home: home, Work: t.TempDir(), Cache: t.TempDir()}
|
||||
@@ -150,7 +152,7 @@ func TestIntegrationLevelRunsAgainstARealStoreAndBusAndLeavesNothing(t *testing.
|
||||
needTools(t, "the integration level", "go", "git", "initdb", "pg_ctl", "postgres", "bwrap")
|
||||
tree := repository(t, "store")
|
||||
// A short work directory: a unix socket's path is bounded at 108 bytes.
|
||||
work, err := os.MkdirTemp("/tmp", "w")
|
||||
work, err := os.MkdirTemp(os.TempDir(), "w")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -185,6 +187,7 @@ func TestIntegrationLevelRunsAgainstARealStoreAndBusAndLeavesNothing(t *testing.
|
||||
// 1487/AC2: given a fixture Go module, when it is built twice, both digests are equal and the archive holds one
|
||||
// executable named as binaryName says. It runs the real go, so it carries the tag.
|
||||
func TestBuildTwiceGivesOneDigestAndOneExecutable(t *testing.T) {
|
||||
t.Parallel()
|
||||
needTools(t, "the build", "go", "bwrap")
|
||||
work := t.TempDir()
|
||||
tree := filepath.Join(work, "ws1", "tree")
|
||||
|
||||
@@ -340,3 +340,36 @@ func TestADirectoryThatVendorsIsReadFromItsVendorDirectory(t *testing.T) {
|
||||
t.Errorf("the last GOFLAGS of go test in a vendoring directory is %q", flags)
|
||||
}
|
||||
}
|
||||
|
||||
// A-447c: a workspace fetched for a module's directory compares the generated files of that module's own module.json
|
||||
// alone, never another module's of the repository.
|
||||
func TestUnitLevelComparesOnlyTheOwnModulesGeneratedFiles(t *testing.T) {
|
||||
m, states, ws, _ := workspaceFor(t, "empty")
|
||||
tree := filepath.Join(m.Work, ws, "tree")
|
||||
for _, folder := range []string{"domain", "other"} {
|
||||
for p, text := range map[string]string{
|
||||
"module.json": `{"module":"c","build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"],"generated-from":"."}]}}`,
|
||||
"seats/one-store/seat.json": `{"format":1,"seat":"one-store","scope":"mesh","grain":"seat-list","domain":"Module","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"}}]}`,
|
||||
"go/go.mod": "module example.org/c/go\n",
|
||||
"go/stray.go": "package stray\n",
|
||||
} {
|
||||
full := filepath.Join(tree, folder, filepath.FromSlash(p))
|
||||
_ = os.MkdirAll(filepath.Dir(full), 0o755)
|
||||
if err := os.WriteFile(full, []byte(text), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(m.Work, ws, moduleDirMark), []byte("domain"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, _ := runUnit(t, m, states, ws)
|
||||
if len(res.OutOfStep) == 0 {
|
||||
t.Fatalf("nothing out of step: %+v", res)
|
||||
}
|
||||
for _, p := range res.OutOfStep {
|
||||
if !strings.HasPrefix(p, "domain/") {
|
||||
t.Errorf("out of step = %v, want the module's own files under domain/ alone", res.OutOfStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// Command mesh-compose is the stand-in composer the compose ask's test builds: a program of the contract the Go build module
|
||||
// runs (`-request <file>`, the last line of its standard output a composer verdict of version 1), which judges nothing and
|
||||
// answers each case of the request by its name, with no manifest and no machine. It imports nothing of the mesh.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
file := flag.String("request", "", "the request file")
|
||||
flag.Parse()
|
||||
raw, err := os.ReadFile(*file)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
var req struct {
|
||||
Cases []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"cases"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
type verdict struct {
|
||||
Name string `json:"name"`
|
||||
Manifests map[string]any `json:"manifests"`
|
||||
}
|
||||
out := struct {
|
||||
V int `json:"v"`
|
||||
SDK string `json:"sdk"`
|
||||
Cases []verdict `json:"cases"`
|
||||
}{V: 1, SDK: "stand-in"}
|
||||
for _, c := range req.Cases {
|
||||
out.Cases = append(out.Cases, verdict{Name: c.Name, Manifests: map[string]any{}})
|
||||
}
|
||||
line, _ := json.Marshal(out)
|
||||
fmt.Println(string(line))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module standin
|
||||
|
||||
go 1.26
|
||||
@@ -74,6 +74,8 @@ func putReporting(put steprun.Put, r *toolchainReporter, digest func(version str
|
||||
}
|
||||
if eerr := r.Report(key, rev, t); eerr != nil && say != nil {
|
||||
say("toolchain-reported could not be said: %v", eerr)
|
||||
} else if eerr == nil && say != nil {
|
||||
say("toolchain-reported said: %s %s (key %s, revision %d)", t.Language, t.Version, key, rev)
|
||||
}
|
||||
return rev, nil
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestGoModVerifyRunsOncePerGoModAndGoSumDigest(t *testing.T) {
|
||||
|
||||
// Without bubblewrap the module cache is not read-only to a step: a pass is never reused.
|
||||
func TestAPassOfVerifyIsNotReusedWhenStepsAreNotShutOff(t *testing.T) {
|
||||
f := &fakeStep{gomods: "a/go.mod\nb/go.mod\n", files: map[string]string{"a/go.mod": "m\n", "b/go.mod": "m\n"}}
|
||||
f := &fakeStep{gomods: "a/go.mod\nb/go.mod\n", files: map[string]string{"a/go.mod": "module m\n", "b/go.mod": "module m\n"}}
|
||||
m, states := fetchModule(t, f) // no Bubblewrap
|
||||
fetchOnce(t, m, states, fetchArgs)
|
||||
fetchOnce(t, m, states, fetchArgs)
|
||||
@@ -65,7 +65,7 @@ func TestAPassOfVerifyIsNotReusedWhenStepsAreNotShutOff(t *testing.T) {
|
||||
// A verify that fails leaves no mark: the next fetch verifies again.
|
||||
func TestAFailedVerifyLeavesNoMark(t *testing.T) {
|
||||
fail := true
|
||||
f := &fakeStep{gomods: "go.mod\n", files: map[string]string{"go.mod": "m\n"}}
|
||||
f := &fakeStep{gomods: "go.mod\n", files: map[string]string{"go.mod": "module m\n"}}
|
||||
f.goRule = func(line string) forgekey.Ran {
|
||||
if strings.HasSuffix(line, " mod verify") && fail {
|
||||
return forgekey.Ran{Status: 1, Stdout: "x v1: dir has been modified\n"}
|
||||
@@ -88,7 +88,7 @@ func TestDownloadsRunSideBySideUpToTheBound(t *testing.T) {
|
||||
running, most := 0, 0
|
||||
release := make(chan struct{}) // closed once two run at once: they overlap however slowly the machine starts them
|
||||
f := &fakeStep{gomods: "a/go.mod\nb/go.mod\nc/go.mod\nd/go.mod\n", files: map[string]string{
|
||||
"a/go.mod": "a\n", "b/go.mod": "b\n", "c/go.mod": "c\n", "d/go.mod": "d\n"}}
|
||||
"a/go.mod": "module a\n", "b/go.mod": "module b\n", "c/go.mod": "module c\n", "d/go.mod": "module d\n"}}
|
||||
f.goRule = func(line string) forgekey.Ran {
|
||||
if strings.HasSuffix(line, " mod download") {
|
||||
mu.Lock()
|
||||
|
||||
@@ -53,6 +53,7 @@ type downloadInfo struct {
|
||||
Version string
|
||||
Sum string
|
||||
GoModSum string
|
||||
GoMod string // the go.mod of the version in the module cache
|
||||
Error string
|
||||
}
|
||||
|
||||
@@ -159,7 +160,10 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
return fmt.Errorf("the asked version %s of %s: %w", tv.Asked, tv.Package, err)
|
||||
}
|
||||
tv.Built, tv.Said = tv.Asked, "Go cannot fetch it: placed from the pull request's head, which has no checksum"
|
||||
return nil
|
||||
if _, err := os.Stat(filepath.Join(where, "go.mod")); err != nil {
|
||||
return nil
|
||||
}
|
||||
return m.takeRequirementsOf(ctx, pinsDir, filepath.Join(where, "go.mod"))
|
||||
}
|
||||
if tagged && compareVersions(tv.Named, info.Version) > 0 {
|
||||
tv.Said = fmt.Sprintf("go.mod names %s, newer than the group's tagged version %s, which is built: the group's check is of its tagged version (ADR 0607 §3)", tv.Named, info.Version)
|
||||
@@ -177,12 +181,21 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
return fmt.Errorf("the asked version %s of %s could not be required: %s", info.Version, tv.Package, causeLine(r.Err+"\n"+r.Stderr))
|
||||
}
|
||||
// The checksums Go computed of the download, which go mod verify checks the module cache against.
|
||||
if err := appendSums(pinsDir, tv.Package, info); err != nil {
|
||||
return err
|
||||
}
|
||||
// The requirements of that version go in too: the modfile names every module its packages load (ownFilesCover).
|
||||
return m.takeRequirementsOf(ctx, pinsDir, info.GoMod)
|
||||
}
|
||||
|
||||
// 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 := ""
|
||||
if info.Sum != "" {
|
||||
sums += tv.Package + " " + info.Version + " " + info.Sum + "\n"
|
||||
sums += module + " " + info.Version + " " + info.Sum + "\n"
|
||||
}
|
||||
if info.GoModSum != "" {
|
||||
sums += tv.Package + " " + info.Version + "/go.mod " + info.GoModSum + "\n"
|
||||
sums += module + " " + info.Version + "/go.mod " + info.GoModSum + "\n"
|
||||
}
|
||||
f, err := os.OpenFile(filepath.Join(pinsDir, "go.sum"), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
|
||||
if err != nil {
|
||||
@@ -195,6 +208,46 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
return err
|
||||
}
|
||||
|
||||
// takeRequirementsOf requires, in the modfile of pinsDir, each module the go.mod at gomodPath (the go.mod of a version just
|
||||
// taken, from what the fetch downloaded) requires at a version the modfile lacks or names older, with the checksums of
|
||||
// each: the graph of a package version taken into a modfile is the version's, not the one go.mod was written against (a
|
||||
// module whose go.mod names mesh-sdk v0.1.13 and is built at a newer one loads what the newer requires). A module of the
|
||||
// forge is left to its own rule (the zero version, a pin, an asked version).
|
||||
func (m *Module) takeRequirementsOf(ctx context.Context, pinsDir, gomodPath string) error {
|
||||
if gomodPath == "" {
|
||||
return nil
|
||||
}
|
||||
raw, err := os.ReadFile(gomodPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the go.mod of the version taken: %w", err)
|
||||
}
|
||||
have, err := os.ReadFile(filepath.Join(pinsDir, "go.mod"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want, _ := goModRequirements(string(raw))
|
||||
named, _ := goModRequirements(string(have))
|
||||
for _, module := range slices.Sorted(maps.Keys(want)) {
|
||||
version := want[module]
|
||||
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)
|
||||
var info downloadInfo
|
||||
_ = json.Unmarshal([]byte(r.Stdout), &info)
|
||||
if r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != "" {
|
||||
return downloadFailure(strings.TrimSpace(info.Error+"\n"+r.Err+"\n"+r.Stderr), "downloading %s@%s, a requirement of the version taken", module, version)
|
||||
}
|
||||
if r := m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "edit", "-require="+module+"@"+info.Version); r.Status != 0 || r.Err != "" {
|
||||
return fmt.Errorf("%s@%s, a requirement of the version taken, could not be required: %s", module, info.Version, causeLine(r.Err+"\n"+r.Stderr))
|
||||
}
|
||||
if err := appendSums(pinsDir, module, info); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// goModRequirements are the module paths a go.mod requires, with the version each names, and those it replaces.
|
||||
func goModRequirements(gomod string) (required map[string]string, replaced map[string]bool) {
|
||||
required, replaced = map[string]string{}, map[string]bool{}
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
// group's head Go cannot fetch is placed from the forge's pull request heads; a go.mod that does not require the package
|
||||
// takes nothing.
|
||||
func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sdk = "git.novox.be/novox/mesh-sdk/go"
|
||||
trunk := strings.Repeat("a", 40)
|
||||
offHead := strings.Repeat("b", 40) // a commit no pull request's head carries
|
||||
@@ -30,10 +31,17 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
forgeDown bool // the forge's listing of pull request heads fails too
|
||||
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
|
||||
}{
|
||||
{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="}`,
|
||||
built: "v0.1.15-0.20261101000000-aaaaaaaaaaaa", edit: "-require=" + sdk + "@v0.1.15-0.20261101000000-aaaaaaaaaaaa"},
|
||||
// The requirements of the version taken go into the modfile with their sums, but a module of the forge is left to its
|
||||
// own rule and one the modfile names at or above the version is left as it is.
|
||||
{name: "a trunk commit whose go.mod requires more", asked: trunk,
|
||||
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"},
|
||||
@@ -96,11 +104,20 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
if name == "git" && strings.Contains(line, "ls-remote") && c.forgeDown {
|
||||
return forgekey.Ran{Status: 128, Stderr: "fatal: unable to access the forge: Could not resolve host\n"}
|
||||
}
|
||||
if name == "go" && strings.Contains(line, " mod download -json github.com/") {
|
||||
module, version, _ := strings.Cut(strings.Fields(line)[len(strings.Fields(line))-1], "@")
|
||||
return forgekey.Ran{Stdout: `{"Path":"` + module + `","Version":"` + version + `","Sum":"h1:` + module + `zip=","GoModSum":"h1:` + module + `mod="}`}
|
||||
}
|
||||
if name == "go" && strings.Contains(line, " mod download -json "+sdk+"@") {
|
||||
h.mu.Lock()
|
||||
h.cmds = append(h.cmds, cmdRecord{env: env, line: line})
|
||||
h.mu.Unlock()
|
||||
downloads++
|
||||
if c.requires != "" {
|
||||
gomod := filepath.Join(t.TempDir(), "go.mod")
|
||||
os.WriteFile(gomod, []byte(c.requires), 0o644)
|
||||
return forgekey.Ran{Stdout: strings.ReplaceAll(c.answer, "GOMOD", gomod)}
|
||||
}
|
||||
if c.failing {
|
||||
return forgekey.Ran{Status: 1, Stdout: c.answer}
|
||||
}
|
||||
@@ -158,6 +175,18 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
if placed := strings.Contains(string(body), "replace "+sdk+" => "); placed != c.failing {
|
||||
t.Errorf("the modfile replaces mesh-sdk by a placed head: %v, want %v:\n%s", placed, c.failing, body)
|
||||
}
|
||||
if c.requires != "" {
|
||||
for _, dep := range []string{"github.com/nats-io/nats.go@v1.54.0", "github.com/klauspost/compress@v1.20.0"} {
|
||||
module, _, _ := strings.Cut(dep, "@")
|
||||
if !h.ran("-require="+dep) || !strings.Contains(string(sums), module+" "+strings.TrimPrefix(dep, module+"@")+" h1:"+module+"zip=") ||
|
||||
!strings.Contains(string(sums), module+" "+strings.TrimPrefix(dep, module+"@")+"/go.mod h1:"+module+"mod=") {
|
||||
t.Errorf("the requirement %s of the version taken was not required with its sums:\n%s", dep, sums)
|
||||
}
|
||||
}
|
||||
if h.ran("mesh-contracts/go/x") {
|
||||
t.Error("a module of the forge required by the version taken was looked for as a requirement")
|
||||
}
|
||||
}
|
||||
if _, other := h.m.pinModfile(filepath.Join(h.m.Work, res.Workspace, "tree", "other")); other {
|
||||
t.Error("a go.mod that requires no asked package was handed a modfile")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -33,7 +33,9 @@
|
||||
}
|
||||
],
|
||||
"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 +43,11 @@
|
||||
"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": {
|
||||
|
||||
@@ -31,16 +31,24 @@ 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(),
|
||||
}
|
||||
}
|
||||
|
||||
// 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 +77,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{KeepOutput: steprun.KeepOutputIn(m.Outputs), 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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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-module-assigner.assignments", "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)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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"
|
||||
@@ -44,3 +45,19 @@ 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))
|
||||
}
|
||||
|
||||
// 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())
|
||||
})
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user