Merge pull request 'Import fingerprint: the build modules report each build's import set (issue 721, design 47 H2)' (#748) from fix/fp-imports into main

This commit was merged in pull request #748.
This commit is contained in:
2026-11-23 12:22:47 +00:00
19 changed files with 578 additions and 50 deletions
@@ -51,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(seat.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskGo, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -4,6 +4,7 @@ package main
import (
"context"
"encoding/json"
"sync"
"testing"
"time"
@@ -11,6 +12,7 @@ import (
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/testbus"
@@ -30,6 +32,9 @@ const checkCommit = "89abcdef0123456789abcdef0123456789abcdef"
// **The order is read from the record.** At capacity 1 the puller starts the check the instant the delivery ask's step
// ends, well before any poll, so "the check key holds a state" is true on correct behaviour (issue 1887). The test
// waits for both asks to end and compares the step records' own Started and Ended times, and the fetch order by commit.
//
// G1/AC2 (design 47 H2 H-A-517, H-A-532 DQ-2): each build that read its imports says imports-reported, and the
// delivery ask's is on the bus, on the seat's subject of the node.
func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
@@ -64,9 +69,24 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
states := newStates()
m := moduleWith(states, "go1.26.0")
m.Capacity = func() int { return 1 }
reported := make(chan *nats.Msg, 4)
sub, err := nc.ChanSubscribe(seat.SubjectImportsReportedAll, reported)
if err != nil {
t.Fatal(err)
}
defer func() { _ = sub.Unsubscribe() }()
m.SayEvent = func(subject string, body any, _ string) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
return nc.Publish(subject, raw)
}
var mu sync.Mutex
var order []string
steps := fakeSteps(new([]string))
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"git.novox.be/novox/mesh-sdk/go"}}, nil
}})
for i := range steps {
if steps[i].Name == "build_go_fetch" {
run := steps[i].Run
@@ -113,8 +133,26 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
t.Fatalf("the check ask started at %v, before the delivery ask ended at %v at capacity 1", checkStarted, deliveryEnded)
}
mu.Lock()
defer mu.Unlock()
if len(order) != 2 || order[0] != askCommit || order[1] != checkCommit {
t.Fatalf("fetched %v, want the delivery ask's commit %s first, then the check's %s", order, askCommit, checkCommit)
}
mu.Unlock()
for timeout := time.After(10 * time.Second); ; {
select {
case msg := <-reported:
var r seat.ImportsReported
if err := json.Unmarshal(msg.Data, &r); err != nil {
t.Fatal(err)
}
if r.Commit != askCommit {
continue
}
if msg.Subject != seat.SubjectImportsReported("ace") || r.Module != "mesh-delivery-view" || len(r.Imports) != 1 {
t.Fatalf("imports-reported on %s: %+v", msg.Subject, r)
}
return
case <-timeout:
t.Fatal("the delivery ask's imports-reported never reached the bus")
}
}
}
@@ -1,8 +1,11 @@
package main
import (
"context"
"encoding/json"
"testing"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +31,47 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// G1/AC1 (design 47 H2 H-A-517, H-A-532 DQ-2): a build ask of a module with Go bundles that ends done says one
// imports-reported on the seat's subject of the node, naming the module, the fingerprint, the commit and the imports
// the imports step read.
func TestADoneBuildSaysItsImportSetOnTheNodesSubject(t *testing.T) {
type said struct {
subject, id string
body seat.ImportsReported
}
var events []said
m := moduleWith(newStates(), "go1.26.0")
m.SayEvent = func(subject string, body any, id string) error {
r, ok := body.(seat.ImportsReported)
if !ok {
raw, _ := json.Marshal(body)
t.Fatalf("said %s with %T: %s", subject, body, raw)
}
events = append(events, said{subject, id, r})
return nil
}
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/busstate"}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: imports}, nil
}})
a := deliveryAsk()
a.Build.Fp = "src2:0123"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
if len(events) != 1 {
t.Fatalf("said %d imports-reported, want 1: %+v", len(events), events)
}
e := events[0]
if e.subject != seat.SubjectImportsReported("ace") {
t.Errorf("said on %s, want %s", e.subject, seat.SubjectImportsReported("ace"))
}
if e.id != "imports-reported.mesh-delivery-view.src2:0123" {
t.Errorf("id %s", e.id)
}
if e.body.Node != "ace" || e.body.Module != "mesh-delivery-view" || e.body.Fingerprint != "src2:0123" || e.body.Commit != askCommit ||
len(e.body.Imports) != 2 || e.body.Imports[0] != imports[0] || e.body.Imports[1] != imports[1] {
t.Errorf("said %+v", e.body)
}
}
@@ -195,6 +195,10 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no prefix tells a mesh package apart, so the module declares no setting import-prefix.
if _, ok := doc.Config["import-prefix"]; ok {
t.Errorf("the manifest declares import-prefix, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -1,10 +1,12 @@
package main
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which mesh packages the module's Go programs
// import, so the indexer can take the fingerprint over those packages' content and no other. It is `go list -deps` of
// each Go bundle artifact's program, the tests left out, kept to the packages of the mesh's forge that lie outside the
// module's own directory (a sibling package of the module's own repository counts, a package under the module itself
// comes with its tree).
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which packages the module's Go programs
// import, so the indexer can take the fingerprint over the ones a module of the module graph publishes and no other. It
// is `go list -deps` of each Go bundle artifact's program and of the packages each Go package artifact's paths hold
// (design 47 H2 H-A-532 DQ-5), the tests left out: the import path of every package of the import closure (H-A-517,
// H-A-541) but the standard library's, with no prefix telling a mesh package apart (H-A-539: mesh modules come from the
// seat go-package-registry), and none of the module's own (its main module, or a module that lies under its own
// directory, which comes with its tree).
import (
"context"
@@ -14,7 +16,6 @@ import (
"slices"
"strings"
trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
@@ -27,8 +28,9 @@ type ImportsResult struct {
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the mesh packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact, without tests, kept to the forge's packages outside the module's own directory, sorted and each once. " +
Description: "Read the packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact and of the packages each Go package artifact's paths hold, without tests, the import path of every " +
"package but the standard library's and the module's own, sorted and each once. " +
"It is what a build says at its end for the fingerprint (ADR 0593 §2). Read-only.",
Input: map[string]any{
"type": "object",
@@ -68,24 +70,44 @@ func (m *Module) imports(ctx context.Context, args map[string]any) (any, error)
return ModuleImports(ctx, run, m.buildEnv(dir), dir, manifest)
}
// ModuleImports are the mesh packages the Go bundle artifacts of manifest, in the module directory dir, import.
// ModuleImports are the packages the Go bundle and package artifacts of manifest, in the module directory dir, import:
// one sorted union of import paths (design 47 H2 H-A-518, H-A-541), the standard library, the tests and the module's
// own left out.
func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
seen := map[string]bool{}
if manifest.Build != nil {
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "go" || strings.TrimSpace(a.From) == "" {
if a.Language != "go" {
continue
}
r := run(ctx, env, "go", "-C", dir, "list", "-deps", "-f", "{{.ImportPath}} {{.Dir}}", "./"+strings.Trim(a.From, "./"))
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
// A bundle lists its program; a package (design 47 H2 H-A-532 DQ-5) lists every package each of its paths
// holds, in the Go module that path is, so a contracts module reports its import set too.
var lists [][2]string
switch a.Kind {
case "bundle":
if strings.TrimSpace(a.From) != "" {
lists = append(lists, [2]string{dir, "./" + strings.Trim(a.From, "./")})
}
case "package":
for _, p := range a.Paths {
if strings.TrimSpace(p) != "" {
lists = append(lists, [2]string{filepath.Join(dir, filepath.FromSlash(strings.Trim(p, "./"))), "./..."})
}
}
}
for _, l := range strings.Split(r.Stdout, "\n") {
pkg, where, ok := strings.Cut(strings.TrimSpace(l), " ")
if !ok || !meshPackage(pkg) || ownedBy(dir, where) {
continue
for _, l := range lists {
r := run(ctx, env, "go", "-C", l[0], "list", "-deps", "-f", listFormat, l[1])
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
}
for _, line := range strings.Split(r.Stdout, "\n") {
// <import path> <dir> <module path> <main>; a package of the standard library has no module.
f := strings.Fields(line)
if len(f) != 4 || f[3] == "true" || ownedBy(dir, f[1]) {
continue
}
seen[f[0]] = true
}
seen[pkg] = true
}
}
}
@@ -94,16 +116,12 @@ func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir s
out = append(out, p)
}
slices.Sort(out)
if err := trunk.CheckImports(out); err != nil {
return ImportsResult{}, err
}
return ImportsResult{Imports: out}, nil
}
func meshPackage(pkg string) bool {
_, _, ok := trunk.PackageRepository(pkg)
return ok
}
// listFormat is what go list says of each package a program reaches: its import path, its directory and, outside the
// standard library, its module's path and whether that is the main module.
const listFormat = "{{.ImportPath}} {{.Dir}}{{with .Module}} {{.Path}} {{.Main}}{{end}}"
// ownedBy says the package directory where lies under the module directory dir and is not a vendored copy.
func ownedBy(dir, where string) bool {
@@ -12,22 +12,24 @@ import (
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
// ADR 0593 §2 (C3): a fixture whose program imports announce, a sibling package of its own repository and a package of its
// own directory reports the first two; a test's import never appears (go list is run without -test), and the standard
// library, a package of another host and the module's own packages are left out.
func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) {
// ADR 0593 §2 (C3), design 47 H2 H-A-517, H-A-539, H-A-541: a fixture whose program imports packages of other Go
// modules reports the import path of each package, whatever its host (a mesh module comes from the seat
// go-package-registry, never told apart by a forge prefix): a sibling module's package and an outside package count,
// each once; the standard library (no module), the module's own packages (its main module, or a module under its own
// directory) and a test's import (go list runs without -test) are left out.
func TestModuleImportsAreTheModulesItsBuildResolved(t *testing.T) {
dir := "/w/ws1/tree/modules/demo"
var line string
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line = name + " " + strings.Join(args, " ")
return forgekey.Ran{Stdout: strings.Join([]string{
"fmt /usr/lib/go/src/fmt",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib",
"git.novox.be/novox/mesh-catalog/modules/demo/internal/own " + dir + "/internal/own",
"git.novox.be/novox/mesh-sdk/go/vendored " + dir + "/vendor/git.novox.be/novox/mesh-sdk/go/vendored",
"github.com/nats-io/nats.go /cache/nats.go",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-sdk/go/busstate /cache/mesh-sdk@v1/go/busstate git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib git.novox.be/novox/mesh-catalog/modules/sibling/lib false",
"demo/internal/own " + dir + "/internal/own demo true",
"git.novox.be/novox/mesh-catalog/modules/demo/inner " + dir + "/inner git.novox.be/novox/mesh-catalog/modules/demo/inner false",
"github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}, "\n")}
}
m, err := catalogue.Decode([]byte(`{"module":"demo","version":"1","build":{"artifacts":[` + goBundle + `,{"name":"files","kind":"archive","from":"files"}]}}`))
@@ -38,7 +40,8 @@ func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) {
if err != nil {
t.Fatal(err)
}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", "git.novox.be/novox/mesh-sdk/go/vendored"}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce",
"git.novox.be/novox/mesh-sdk/go/busstate", "github.com/nats-io/nats.go"}
if !slices.Equal(got.Imports, want) {
t.Errorf("imports %v, want %v", got.Imports, want)
}
@@ -61,3 +64,54 @@ func TestImportsStepReadsTheWorkspace(t *testing.T) {
t.Errorf("a fake compiler's go list names no package, and the answer was %v", got)
}
}
// G2 (design 47 H2 H-A-532 DQ-5, H-A-518, H-A-541): a Go package artifact reports the packages the packages its paths
// hold import, listed in the Go module each path is, without tests and without the module's own directory; a module
// with both kinds reports one sorted union.
func TestAPackageArtifactReportsItsImportSet(t *testing.T) {
dir := "/w/ws1/tree/modules/contracts"
pkg := `{"name":"seat","kind":"package","language":"go","paths":["go/seats/demo"],"series":"0.1"}`
listed := map[string]string{
dir + "/go/seats/demo ./...": strings.Join([]string{
"encoding/json /usr/lib/go/src/encoding/json",
"git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo " + dir + "/go/seats/demo git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo true",
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
}, "\n"),
dir + " ./cmd/demo-tools": "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}
for _, c := range []struct {
name string
artifacts string
want []string
}{
// G2/AC1: a contracts module whose artifact is of kind package.
{"package", pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio"}},
// G2/AC2: a module with a bundle and a package reports one sorted union.
{"both", goBundle + "," + pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio", "github.com/nats-io/nats.go"}},
} {
t.Run(c.name, func(t *testing.T) {
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line := args[1] + " " + args[len(args)-1]
if slices.Contains(args, "-test") || args[2] != "list" {
t.Errorf("go ran as %v: it lists dependencies without tests", args)
}
out, ok := listed[line]
if !ok {
t.Errorf("go list in %q, not asked", line)
}
return forgekey.Ran{Stdout: out}
}
m, err := catalogue.Decode([]byte(`{"module":"contracts","version":"1","build":{"artifacts":[` + c.artifacts + `]}}`))
if err != nil {
t.Fatal(err)
}
got, err := ModuleImports(context.Background(), run, nil, dir, m)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(got.Imports, c.want) {
t.Errorf("imports %v, want %v", got.Imports, c.want)
}
})
}
}
@@ -5,6 +5,7 @@ import (
"path/filepath"
"time"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -32,6 +33,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
}
return steprun.AskSteps{
Fetch: byName["build_node_fetch"], Build: byName["build_node_build"], Test: byName["build_node_test"],
// The npm packages its bundles import, read after the build and said as imports-reported (design 47 H2 H-A-523,
// H-A-532 DQ-6, H-A-539).
Imports: byName[ImportsTool],
Compare: steprun.CompareStep(steprun.GeneratedRootTS, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }),
Toolchain: func(ctx context.Context) (sdkstep.ToolchainUsed, error) {
installed, err := m.Probe(ctx)
@@ -47,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(nodebuildgo.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskNode, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -1,8 +1,12 @@
package main
import (
"context"
"errors"
"slices"
"testing"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +32,43 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// N1/AC1, N1/AC3 (design 47 H2 H-A-517, H-A-523, H-A-534): a done build of a TypeScript module says one imports-reported
// on the Node build seat's subject of the node, naming the mesh npm packages the imports step read; a failed build says
// none.
func TestADoneNodeBuildSaysItsImportSetAndAFailedOneNone(t *testing.T) {
var said []nodebuildgo.ImportsReported
var subjects []string
m := moduleWith(newStates(), "v26.10.0")
m.Outputs = kitObjects{} // a failed build keeps its error text as an output object, never on a bus here
m.SayEvent = func(subject string, body any, _ string) error {
subjects = append(subjects, subject)
said = append(said, body.(nodebuildgo.ImportsReported))
return nil
}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"@novox/mesh-sdk"}}, nil
}})
a := nodeAsk(sdkstep.AskDelivery)
a.Build.Fp = "src2:0456"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
want := "mesh.seat.node-build-node.event.imports-reported.ace"
if len(said) != 1 || subjects[0] != want || said[0].Module != "gitea" || said[0].Fingerprint != "src2:0456" ||
said[0].Commit != askCommit || !slices.Equal(said[0].Imports, []string{"@novox/mesh-sdk"}) {
t.Fatalf("said %v on %v, want one imports-reported of gitea naming @novox/mesh-sdk on %s", said, subjects, want)
}
said = nil
for i := range steps {
if steps[i].Name == "build_node_build" {
steps[i].Run = func(context.Context, map[string]any) (any, error) { return nil, errors.New("tsc failed") }
}
}
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err == nil {
t.Fatal("the failed build passed")
}
if len(said) != 0 {
t.Errorf("a failed build said %v", said)
}
}
@@ -115,6 +115,10 @@ func TestManifestTakesTheBuildCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no scope tells a mesh package apart, so the module declares no setting import-scope.
if _, ok := doc.Config["import-scope"]; ok {
t.Errorf("the manifest declares import-scope, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -89,7 +89,8 @@ var fetchedSDK = map[string]string{
// fixture pass the unit level; a package whose test imports its own build output (as mesh-sdk's do) passes the unit level,
// the test step emitting it with the real tsc, shut off, before the test script runs; and the fixture TypeScript bundle
// importing @novox/mesh-sdk, built twice by the real tsc and esbuild, has equal digests, its archive holding the bundled
// .js, the .serve.mjs launcher and package.json. The unit levels run in w3, so the two builds' workspaces stay alike.
// .js, the .serve.mjs launcher and package.json, and its imports step names the SDK. The unit levels run in w3, so the
// two builds' workspaces stay alike.
func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
m, work := realMachine(t)
out, err := m.test(context.Background(), map[string]any{"workspace": "w3", "module": "modules/m", "level": "unit"})
@@ -130,6 +131,15 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
if digests[0] != digests[1] {
t.Errorf("digests differ: %v", digests)
}
// N1/AC1 (design 47 H2 H-A-523, H-A-532 DQ-6): the real esbuild's metafile of the built bundle names the SDK it
// imports, by its package name.
out, err = m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, []string{"@novox/mesh-sdk"}) {
t.Errorf("the bundle's imports = %v, want [@novox/mesh-sdk]", got)
}
if links := symlinksUnder(t, work); len(links) != 0 {
t.Errorf("symlinks in the workspaces: %v", links)
}
@@ -5,6 +5,7 @@ import (
"bytes"
"compress/gzip"
"context"
"errors"
"io"
"maps"
"os"
@@ -361,3 +362,73 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) {
}
}
}
// N1/AC1, N1/AC2 (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): after a bundle's build, the imports step runs esbuild
// over the staged entrypoint and launcher with a metafile and answers every npm package among its inputs and external
// imports, each by its package name once (the SDK's stdio sub-path is the SDK), with no scope filter: a mesh package is
// told apart by the indexer, never by its scope. Node's own modules (node:module, fs) are no package; a bundle reaching
// only those answers none. Node's own modules are the probed toolchain's module.builtinModules, read at the step
// (principle 11), here holding sqlite, which no fixed list of Node 22 holds.
func TestTheImportsStepNamesTheNpmPackagesABundleReaches(t *testing.T) {
for _, c := range []struct {
name string
metafile string
want []string
}{
{"packages", `{"inputs":{
".mesh-build/tools/tools/index.js":{"imports":[{"path":"../../node_modules/@novox/mesh-sdk/dist/stdio.js"},{"path":"@novox/mesh-other/x","external":true},{"path":"pg","external":true},{"path":"node:module","external":true},{"path":"fs","external":true},{"path":"sqlite","external":true}]},
"../../node_modules/@novox/mesh-sdk/dist/stdio.js":{"imports":[]},
"../../node_modules/@novox/mesh-sdk/dist/index.js":{"imports":[]},
"../../node_modules/nats/lib/index.js":{"imports":[]}}}`, []string{"@novox/mesh-other", "@novox/mesh-sdk", "nats", "pg"}},
{"none", `{"inputs":{".mesh-build/tools/tools/index.js":{"imports":[{"path":"node:module","external":true},{"path":"path","external":true}]}}}`, []string{}},
} {
t.Run(c.name, func(t *testing.T) {
m, f, work := builtMachine(t, `,"external":["pg"]`)
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs", "module", "path", "sqlite"}, nil }
bundled := f.effect
var metaRun []string
f.effect = func(cl call) {
bundled(cl)
for _, a := range cl.args {
if p, ok := strings.CutPrefix(a, "--metafile="); ok {
metaRun = cl.args
write(t, filepath.Join(cl.dir, p), c.metafile, 0o644)
}
}
}
if _, err := m.build(context.Background(), buildArgs()); err != nil {
t.Fatal(err)
}
if metaRun != nil {
t.Fatalf("the build itself ran esbuild with a metafile: %v", metaRun)
}
out, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, c.want) {
t.Errorf("imports %v, want %v", got, c.want)
}
last := f.calls[len(f.calls)-1]
if dir := filepath.Join(work, "w1", "stage-tools", "modules", "module"); last.dir != dir ||
!slices.Contains(last.args, ".mesh-build/tools/tools/index.js") || !slices.Contains(last.args, ".mesh-build/tools/tools/index.serve.mjs") ||
!slices.Contains(last.args, "--external:pg") || !slices.Contains(last.args, "--metafile=.mesh-build/tools.imports.json") {
t.Errorf("esbuild ran in %s as %v", last.dir, last.args)
}
})
}
}
// N1 (H-A-517): a workspace whose bundle was not built has no import set to read, and the step says so; a toolchain whose
// own modules cannot be read fails the step loud, never answering them as packages.
func TestTheImportsStepRefusesABundleNotBuilt(t *testing.T) {
m, _, _ := builtMachine(t, ``)
m.Builtins = func(context.Context) ([]string, error) { return nil, errors.New("no node") }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "Node's own modules") {
t.Errorf("imports with no builtins read: %v", err)
}
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs"}, nil }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "was not built") {
t.Errorf("imports of an unbuilt bundle: %v", err)
}
}
@@ -0,0 +1,185 @@
package main
// The imports step (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): at a build's end the module says which npm packages
// its TypeScript bundles import, so the indexer can take the fingerprint over the ones a module of the module graph
// publishes and no other. It is what esbuild's metafile names as each bundle's inputs, read from the bundle's compiled
// entrypoints and launchers as the build step staged them: every npm package among them, each by its package name once
// (@novox/mesh-sdk, never a sub-path of it), with no scope telling a mesh package apart, and none of Node's own modules.
// A bundle's inputs are what its entrypoints reach, so no test file is among them.
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
)
// ImportsTool reads the npm packages a module's bundles import (design 47 H2 H-A-532 DQ-6).
const ImportsTool = "build_node_imports"
// ImportsResult is what the imports step answers; a BuildAnswer carries Imports as it is.
type ImportsResult struct {
Imports []string `json:"imports"`
}
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the npm packages the TypeScript bundles of a module of a workspace import, after its build: " +
"esbuild's inputs of each bundle's compiled entrypoints and launchers, every npm package among them but Node's own " +
"modules, each by its package name, sorted and each once. It is what a build says at its end " +
"for the fingerprint (design 47 H2 H-A-523). Writes only esbuild's scratch output in the workspace.",
Input: map[string]any{
"type": "object",
"properties": map[string]any{
"workspace": map[string]any{"type": "string", "description": "the workspace id build_node_fetch answered, its bundles built"},
"module": map[string]any{"type": "string", "description": "the module's directory in the workspace, '.' when it is the root"},
},
"required": []string{"workspace", "module"},
},
Run: m.imports,
}
}
func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) {
workspace, _ := args["workspace"].(string)
module, _ := args["module"].(string)
root, dir, err := m.moduleDirOf(workspace, module)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(dir, "module.json"))
if err != nil {
return nil, fmt.Errorf("the module has no module.json: %w", err)
}
var manifest struct {
Build struct {
Artifacts []artifact `json:"artifacts"`
} `json:"build"`
}
if err := json.Unmarshal(raw, &manifest); err != nil {
return nil, fmt.Errorf("module.json is not JSON: %w", err)
}
probe := m.Builtins
if probe == nil {
probe = ProbeBuiltins
}
builtins, err := probe(ctx)
if err != nil {
return nil, fmt.Errorf("the imports cannot be told from Node's own modules: %w", err)
}
seen := map[string]bool{}
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "typescript" {
continue
}
names, err := m.bundleImports(ctx, root, a, builtins)
if err != nil {
return nil, err
}
for _, n := range names {
seen[n] = true
}
}
out := []string{}
for n := range seen {
out = append(out, n)
}
slices.Sort(out)
return ImportsResult{Imports: out}, nil
}
// bundleImports are the npm packages esbuild names as inputs of bundle a, read in the stage its build left
// (build.go: <root>/stage-<artifact>/modules/module), from the same entries and externals the build bundled.
func (m *Module) bundleImports(ctx context.Context, root string, a artifact, builtins []string) ([]string, error) {
dir := filepath.Join(root, "stage-"+a.Name, "modules", "module")
out := Out(a.Name)
if _, err := os.Stat(filepath.Join(dir, out)); err != nil {
return nil, fmt.Errorf("the bundle %s was not built in this workspace, so its imports cannot be read: %w", a.Name, err)
}
var entries []string
for _, e := range a.Entrypoints {
if strings.HasSuffix(e, ".js") {
entries = append(entries, out+"/"+e)
}
}
for _, l := range sortedValues(sdkstep.Launchers(a.Language, a.Entrypoints)) {
entries = append(entries, out+"/"+l)
}
if len(entries) == 0 {
return nil, nil
}
meta := out + ".imports.json"
args := append(append([]string{}, entries...), "--bundle", "--platform=node", "--format=esm", "--target=node22",
"--outbase="+out, "--outdir="+out+".imports", "--log-level=warning", "--metafile="+meta)
for _, x := range a.External {
args = append(args, "--external:"+x)
}
if why := ranFailed(m.runIn(ctx, root, false, dir, nil, m.esbuild(), args...)); why != "" {
return nil, fmt.Errorf("esbuild's inputs of %s: %s", a.Name, why)
}
raw, err := os.ReadFile(filepath.Join(dir, meta))
if err != nil {
return nil, fmt.Errorf("esbuild wrote no metafile for %s: %w", a.Name, err)
}
return packagesOf(raw, builtins)
}
// packagesOf are the npm packages an esbuild metafile names: each input under a node_modules directory and each external
// import, by its package name, but Node's own modules.
func packagesOf(metafile []byte, builtins []string) ([]string, error) {
var meta struct {
Inputs map[string]struct {
Imports []struct {
Path string `json:"path"`
External bool `json:"external"`
} `json:"imports"`
} `json:"inputs"`
}
if err := json.Unmarshal(metafile, &meta); err != nil {
return nil, fmt.Errorf("esbuild's metafile is not JSON: %w", err)
}
var out []string
keep := func(name string) {
if name != "" && !nodeBuiltin(name, builtins) && !slices.Contains(out, name) {
out = append(out, name)
}
}
for input, in := range meta.Inputs {
filePath := filepath.ToSlash(input)
if i := strings.LastIndex(filePath, "node_modules/"); i >= 0 {
keep(packageName(filePath[i+len("node_modules/"):]))
}
for _, imp := range in.Imports {
if imp.External {
keep(packageName(imp.Path))
}
}
}
slices.Sort(out)
return out, nil
}
// packageName is the npm package a module specifier or a path under node_modules names: its first segment, or its
// first two for a scoped package (@novox/mesh-sdk/stdio is @novox/mesh-sdk).
func packageName(spec string) string {
parts := strings.SplitN(spec, "/", 3)
if strings.HasPrefix(spec, "@") {
if len(parts) < 2 {
return ""
}
return parts[0] + "/" + parts[1]
}
return parts[0]
}
// nodeBuiltin says whether name is one of Node's own modules (node:<name>, or a name of the probed toolchain's
// module.builtinModules), which is the runtime's standard library and no npm package.
func nodeBuiltin(name string, builtins []string) bool {
return strings.HasPrefix(name, "node:") || slices.Contains(builtins, name)
}
@@ -45,6 +45,9 @@ type Module struct {
Reload func() (Recipe, error)
// Probe reads the installed Node version (ProbeNode).
Probe func(ctx context.Context) (string, error)
// Builtins reads the installed Node's own module names, its module.builtinModules (ProbeBuiltins), at each imports
// step; nil reads them with ProbeBuiltins.
Builtins func(ctx context.Context) ([]string, error)
// Toolchain installs the toolchain directory; nil in a module that only guards.
Toolchain *Toolchain
// Work is the work directory, outside the home: a workspace is <Work>/<step id>/tree. Run runs the commands of a
@@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
@@ -22,6 +23,22 @@ func ProbeNode(ctx context.Context) (string, error) {
return parseNodeVersion(string(out))
}
// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly
// what the probed toolchain holds (principle 11: read, never a fixed list).
func ProbeBuiltins(ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
defer cancel()
out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output()
if err != nil {
return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err)
}
var names []string
if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 {
return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out)))
}
return names, nil
}
func parseNodeVersion(out string) (string, error) {
v := strings.TrimSpace(out)
if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") {
@@ -25,7 +25,7 @@ type StepTool struct {
// StepTools are the module's step tools. Each step's issue adds its own.
func (m *Module) StepTools() []StepTool {
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool()}
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool(), m.importsTool()}
}
// Tools is every tool the module serves: its step tools behind the guard, its status and its health.
+1 -1
View File
@@ -5,6 +5,7 @@ go 1.26.0
require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
@@ -101,7 +102,6 @@ require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect
)
+1
View File
@@ -78,6 +78,7 @@
"build_node_fetch",
"build_node_test",
"build_node_build",
"build_node_imports",
"build_node_release",
"build_node_step",
"build_node_steps",
@@ -108,10 +108,9 @@ var Homes = map[string]Home{
// An owner's change not said on its views family past its bound (mesh-sdk views.UnsaidFinding, id <owner>.<state>):
// written by each owner of a views family in its own findings (the indexer, the assigner), so no one observer.
"view-unsaid": {Source: "views", Why: "every owner of a views family writes its own"},
// The builder's own (design 51): a build that ended failed, a floor whose holder said nothing past its bound, an old
// form held seven days by a counted node-engine, a tag's removal asked and not done.
// The builder's own (design 51): a build that ended failed, an old form held seven days by a counted node-engine, a tag's
// removal asked and not done. Its floor-silent went with its version floor (design 47 H2 H-A-553 (2)).
"build-failed": {Source: "builder", Observer: builder},
"floor-silent": {Source: "builder", Observer: builder},
"old-form-held": {Source: "builder", Observer: builder},
"tag-removal-not-done": {Source: "builder", Observer: builder},
// The builder's publishing (design 51): a holder refused the publish, or said nothing past its bound (about the name);
@@ -366,7 +366,7 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
}
for kind, observer := range map[string]string{"needs-operator": watchman, "machine-network": watchman, "lease-split": selfCheck,
"data-shrank": selfCheck, "retire-waiting": provisioner, "asks-undelivered": messenger,
"image-missing": artifactStore, "build-failed": builder, "floor-silent": builder, "old-form-held": builder,
"image-missing": artifactStore, "build-failed": builder, "old-form-held": builder,
"tag-removal-not-done": builder, "seat-definition-unparsed": indexer, "generated-types-out-of-step": indexer,
"seat-defined-twice": indexer, "accepted-unsaid": indexer, "manifest-held": indexer, "packages-token-refused": gitea,
"publish-refused": builder, "publish-unanswered": builder, "seat-outcome-unread": builder} {
@@ -374,6 +374,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
t.Errorf("%s's home is %+v", kind, h)
}
}
// Design 47 H2 H-A-553 (2): the builder's floor-silent went with its version floor, so no home names it.
if h, ok := Homes["floor-silent"]; ok {
t.Errorf("floor-silent still has a home: %+v", h)
}
for _, kind := range []string{"resolver-wrong", "holder-silent", "archives-missing", "archives-unheld", "binding-kept",
"binding-moved", "binding-moving", "grant-composes-nothing", "root-not-free", "cleanup-waiting", "data-held-twice"} {
if h := Homes[kind]; !h.Carried || h.Observer != "" || h.Why != Dropped {
@@ -397,9 +401,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
// first view, the owners' view too large, the builder's four, the indexer's four and the package seats' token refused.
// And the builder's three publishing kinds and the delivery parts' family not heard: 103.
// And the owners' changes not said, view-unsaid: 104. And the indexer's mesh-wide hold past its bound, manifest-held
// (ADR 0632 §2): 105. (The bus module's own conditions, nats.status-unwritten among them, are said to the keeper
// directly, never through findings, so they have no home here.)
if len(Homes) != 105 || carried != 37 {
// (ADR 0632 §2): 105. Less the builder's floor-silent, gone with its floor (design 47 H2 H-A-553 (2)): 104. (The bus
// module's own conditions, nats.status-unwritten among them, are said to the keeper directly, never through findings, so
// they have no home here.)
if len(Homes) != 104 || carried != 37 {
t.Errorf("the table holds %d kinds, %d carried", len(Homes), carried)
}
}