Merge pull request 'Import fingerprint: a module moves only when a package it imports changes (issue 721, design 47 H2)' (#356) from fix/fp-imports into main

This commit was merged in pull request #356.
This commit is contained in:
2026-11-23 12:22:42 +00:00
138 changed files with 2542 additions and 6202 deletions
@@ -19,7 +19,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/kept"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/keys"
)
@@ -240,9 +239,6 @@ type BuilderBuild struct {
// its id (novox/hq ADR 0525 §1; issue 1887 A4b): a builder that takes the key over at its start waits for those asks'
// steps and never puts them again. A reader that does not know the field reads the key as before.
Asks map[string]string `json:"asks,omitempty"`
// Imports are, on a done key, the mesh packages the built programs import, as the build module answered them
// (BuildAnswer.Imports; novox/hq ADR 0593 §2): the builder carries them onto the build's end (BuildLogEntry.Imports).
Imports []string `json:"imports,omitempty"`
// Packages are, on a done key only, the mesh packages' versions its Go build was built with, by module path, the ones
// the registry gave a package the entry named with none included (H-A-207): the build step's end reports them, so the
// runner asks the steps that waited for the pins with what the build was built against. A reader that does not know
@@ -272,9 +268,6 @@ func (b BuilderBuild) check() error {
if b.KeptOn != "" && b.State != BuildDone {
return fmt.Errorf("builds: a build is kept on a done key alone, this one is %s", b.State)
}
if err := trunk.CheckImports(b.Imports); err != nil {
return err
}
switch b.State {
case BuildQueued, BuildBuilding, BuildDone, BuildFailed:
default:
+4 -12
View File
@@ -6,7 +6,6 @@ import (
"sort"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/keys"
)
@@ -70,10 +69,6 @@ type BuildLogEntry struct {
// KeptOn is, at the end of a kept build, the build node that keeps it, once for the build (design 47 G §671): every
// artifact in Made is kept there, with its digest. A build not kept carries none.
KeptOn string `json:"kept-on,omitempty"`
// Imports are, at a build's end, the mesh packages (import paths) the built programs import, their tests left out,
// sorted and each once, as the build module answered them (BuildAnswer.Imports; novox/hq ADR 0593 §2): the indexer
// keeps them on the module (KeptInputs2.Imports) when the build's fingerprint is the module's.
Imports []string `json:"imports,omitempty"`
// OutOfStep are, at a build's end, the generated files its test step found out of step with what their generator
// writes, as the build module answered them (its test step's `out-of-step`): the indexer raises a finding naming them
// for a trunk build, and only a clean build of the same module clears it. A start or a narration names none.
@@ -132,9 +127,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
switch {
case e.Module == "" || e.FP == "" || e.At.IsZero() || e.Line == "":
return nil, fmt.Errorf("builds: a build's narration names its module, fingerprint, line and time")
case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 || len(e.OutOfStep) > 0 ||
case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.OutOfStep) > 0 ||
e.Error != "" || e.Step != "":
return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, import, file out of step, error or step")
return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, file out of step, error or step")
}
return json.Marshal(e)
case e.Event != BuildStartedEvent && e.Event != BuildEndedEvent:
@@ -145,12 +140,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
return nil, fmt.Errorf("builds: a build log entry names its module, fingerprint, repository, commit, node and time")
case e.Event == BuildEndedEvent && e.Outcome == "":
return nil, fmt.Errorf("builds: a build's end names its outcome")
case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 ||
case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 ||
len(e.OutOfStep) > 0 || e.Error != "" || e.Step != ""):
return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, import, file out of step, error or step")
}
if err := trunk.CheckImports(e.Imports); err != nil {
return nil, err
return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, file out of step, error or step")
}
return json.Marshal(e)
}
@@ -41,10 +41,10 @@ type queueAsker func(key string, value []byte) (json.RawMessage, error)
// Tools are the builder's tools: stuck reads, askAgain writes the reasks value, queue writes a queues value and waits for
// the builder's read, buildAgain writes a reasks value of mode build and waits for the builder's answer.
//
// builder_versions, asked by a name, answers also what the verb reserved answers for it (reserve; design 47 G §572): the
// bundle calls the seat mesh-builds through its invokes, as any caller does. Nil answers none.
func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time, vs versions.Reader,
fw, of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool {
// builder_versions answers from the reservations alone, what the verb reserved answers for a name (reserve; design 47 G §572,
// H §756): the bundle calls the seat mesh-builds through its invokes, as any caller does.
func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time,
of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool {
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
// handAct writes a reasks value of a versions hand act and answers the builder's answer, or its refusal as an error.
handAct := func(key string, value []byte, err error) (any, error) {
@@ -65,13 +65,6 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
return map[string]any{"key": key, "name": a.Name, "answer": a.Answer}, nil
}
return []stdio.Tool{
{Name: versions.FloorAgainTool, Description: versions.FloorAgainDescription,
Input: map[string]any{"type": "object", "required": []string{"name", "why"}, "properties": map[string]any{
"name": map[string]any{"type": "string", "description": "the numbered name, <module>/<artifact>"},
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
Run: func(args map[string]any) (any, error) {
return handAct(build.NewFloorAgain(str(args, "name"), str(args, "why"), stdio.CallerOf(args), now()))
}},
{Name: versions.OldFormTool, Description: versions.OldFormDescription,
Input: map[string]any{"type": "object", "properties": map[string]any{
"drop": map[string]any{"type": "string", "description": "a retired node to drop from the count by hand"},
@@ -82,25 +75,13 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
}
return versions.AnswerOldForm(of)
}},
{Name: versions.FloorWaitsTool, Description: versions.FloorWaitsDescription,
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(map[string]any) (any, error) { return versions.AnswerFloorWaits(fw) }},
{Name: versions.VersionsTool, Description: versions.VersionsDescription,
Input: map[string]any{"type": "object", "required": []string{"name"}, "properties": map[string]any{
"name": map[string]any{"type": "string", "description": "the package, image, bundle or archive name"},
"version": map[string]any{"type": "string", "description": "one version, to ask whether it is recorded"},
"digest": map[string]any{"type": "string", "description": "with version: the digest the holder received"}}},
Run: func(args map[string]any) (any, error) {
out, err := versions.AnswerVersions(context.Background(), vs, str(args, "name"), str(args, "version"), str(args, "digest"))
if err != nil || reserve == nil {
return out, err
}
ra, err := reserve(out.Name, str(args, "version"))
if err != nil {
return nil, fmt.Errorf("the seat mesh-builds' reserved did not answer for %s: %w", out.Name, err)
}
out.Reserved = &ra
return out, nil
return versions.AnswerVersions(str(args, "name"), str(args, "version"), str(args, "digest"), reserve)
}},
{Name: build.StuckTool,
Description: "Every build key that waits (building or queued), oldest first: its module, fingerprint, step words and since when, and each ask it " +
@@ -358,22 +339,6 @@ func main() {
a, err := build.DecodeReAsk(v)
return err == nil && !a.Answered.IsZero()
})
vs := stdio.State(versions.State)
vr := versions.Reader{Keys: vs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := vs.Get(key)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}}
fs := stdio.State(versions.FloorWaitsState)
fr := versions.Reader{Keys: fs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := fs.Get(key)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}}
ofs := stdio.State(versions.OldFormState)
ofr := versions.Reader{Keys: ofs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
e, err := ofs.Get(key)
@@ -429,7 +394,7 @@ func main() {
var a meshbuilds.ReservedAnswer
return a, json.Unmarshal(raw, &a)
}
tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, vr, fr, ofr, reserve)
tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, ofr, reserve)
tools = append(tools, buildTool(&build.BuildReader{Builds: read(stdio.State("builds")), Entry: entryOf(stdio.State("builds").Get), Asked: read(stdio.State("asked")),
Newest: newestVia(stdio.Ask), Steps: r}))
tools = append(tools, reservedTools(rr, buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
@@ -28,7 +28,7 @@ func TestBuilderVersionsByNameCallsReserved(t *testing.T) {
called = append(called, name+"@"+version)
return want, nil
}
tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, none, none, reserve)
tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, reserve)
for _, tl := range tools {
if tl.Name == versions.VersionsTool {
out, err := tl.Run(map[string]any{"name": "@novox/mesh-sdk", "version": "0.1.2"})
@@ -9,12 +9,12 @@ import (
// ownBuckets are the buckets of the builder's own states, each `<module>_<state>` of the module its credential names, never
// a constant (design 47 G A-296, §428).
type ownBuckets struct {
versions, bounds, reserved, queue, acted, toolchainsHeard, instances string
bounds, reserved, queue, acted, toolchainsHeard, instances string
}
func ownBucketsOf(module string) ownBuckets {
return ownBuckets{
versions: builds.StateBucket(module, versions.State), bounds: builds.StateBucket(module, versions.BoundsState),
bounds: builds.StateBucket(module, versions.BoundsState),
reserved: builds.StateBucket(module, versions.ReservedState), queue: builds.StateBucket(module, versions.PublishQueueState),
acted: builds.StateBucket(module, versions.ActedState), toolchainsHeard: builds.StateBucket(module, buildrun.ToolchainsHeardState),
instances: builds.StateBucket(module, instancesState),
@@ -75,8 +75,6 @@ type catalogHalf struct {
halves map[string]*views.Follower
once sync.Once
ctx context.Context
// floor is told each entry change: a floor whose tags or requirements were silent is asked again (design 47 G A-119).
floor func(context.Context)
// holders is told each entry change: a claim of a build seat may have moved (design 47 G A-82).
holders func()
}
@@ -112,9 +110,6 @@ func (c *catalogHalf) Changed(ctx context.Context) func(branch, module string, e
c.logf("%v", err)
}
c.b.Entry(ctx, origin, e)
if c.floor != nil {
defer c.floor(ctx)
}
c.mu.Lock()
was := c.named[module]
now := namesOf(e)
@@ -1,87 +0,0 @@
package main
import (
"context"
"errors"
"sync/atomic"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
)
// lastKept reads whether the stream keeps a message on a subject: found false when the stream or the message is not there.
type lastKept func(ctx context.Context, subject string) (found bool, err error)
// lastKeptOf reads the seat event's own kept stream (the contract's StreamVersionsFilled, kept by age) the way any kept event
// is heard (design 47 G A-411, A-233): the SDK's hearing of it from its first message, whose start read hands every message
// kept to the handler; the reading is stopped once the read ended, the hub's own hearing following the durable. Nothing of
// EVENTS is read.
func lastKeptOf(js jetstream.JetStream, acct process.Account, logf func(string, ...any)) lastKept {
return func(ctx context.Context, subject string) (bool, error) {
var found atomic.Bool
cc, err := acct.HearSeatEvents(ctx, js, meshcatalog.StreamVersionsFilled, func(m jetstream.Msg) {
if m.Subject() == subject {
found.Store(true)
}
_ = m.Ack() // a message of the durable is taken as the hub takes it; an ordered read's has nothing to acknowledge
}, logf, process.FromFirst())
if err != nil {
if errors.Is(err, jetstream.ErrStreamNotFound) {
return false, nil
}
return false, err
}
cc.Stop()
return found.Load(), nil
}
}
// readFilled reads at the builder's start the last versions-filled the stream keeps (design 47 G §369, §372, A-411) and takes it as heard; the event heard later sets it as before. Nothing found leaves it unset, said; a
// read that failed is said and tried again in the background with backoff, never holding the start.
func (rv *reservations) readFilled(ctx context.Context, read lastKept, wait func(context.Context, time.Duration) bool) {
const first, most = time.Second, time.Minute
try := func() (done bool, err error) {
found, err := read(ctx, meshcatalog.SubjectVersionsFilled)
if err != nil {
return false, err
}
if !found {
rv.logf("the stream keeps no versions-filled yet (read at start): versions are reserved once the catalog says it")
return true, nil
}
rv.filled.Store(true)
rv.logf("the catalog said versions-filled (read at start): versions are reserved from now on")
if rv.wake != nil {
rv.wake(ctx)
}
return true, nil
}
if done, err := try(); done {
return
} else {
rv.logf("the last versions-filled is not read at start: %v; read again in the background", err)
}
go func() {
for d := first; ; d = min(d*2, most) {
if !wait(ctx, d) {
return
}
done, err := try()
if done {
return
}
rv.logf("the last versions-filled is not read: %v; read again in %s", err, min(d*2, most))
}
}()
}
// sleeps waits d, as a context's bound (ADR 0437 §8: the builder holds no timer); false when ctx ended first.
func sleeps(ctx context.Context, d time.Duration) bool {
bound, cancel := context.WithTimeout(ctx, d)
defer cancel()
<-bound.Done()
return ctx.Err() == nil
}
@@ -1,64 +0,0 @@
package main
import (
"context"
"errors"
"reflect"
"sync"
"testing"
"time"
)
func TestTheLastVersionsFilledIsReadAtStart(t *testing.T) {
boom := errors.New("bus down")
for _, tc := range []struct {
name string
results []error // per read: nil found, boom fails
notFound bool
wantFilled bool
wantReads int
waits []time.Duration
}{
{"kept", []error{nil}, false, true, 1, nil},
{"none kept", []error{nil}, true, false, 1, nil},
{"read fails then kept", []error{boom, boom, nil}, false, true, 3, []time.Duration{time.Second, 2 * time.Second}},
} {
t.Run(tc.name, func(t *testing.T) {
rv := newReservations(nil, nil, nil, nil, nil, t.Logf)
var mu sync.Mutex
woke := make(chan struct{}, 1)
rv.wake = func(context.Context) { woke <- struct{}{} }
reads := 0
read := func(_ context.Context, subject string) (bool, error) {
mu.Lock()
defer mu.Unlock()
err := tc.results[reads]
reads++
return !tc.notFound, err
}
var waits []time.Duration
wait := func(_ context.Context, d time.Duration) bool {
mu.Lock()
defer mu.Unlock()
waits = append(waits, d)
return true
}
rv.readFilled(context.Background(), read, wait)
if tc.wantFilled {
select {
case <-woke:
case <-time.After(5 * time.Second):
t.Fatal("the read did not take the fill")
}
}
mu.Lock()
defer mu.Unlock()
if rv.Filled() != tc.wantFilled || reads != tc.wantReads {
t.Fatalf("filled %v reads %d", rv.Filled(), reads)
}
if !reflect.DeepEqual(waits, tc.waits) {
t.Fatalf("backoff %v, want %v", waits, tc.waits)
}
})
}
}
@@ -13,8 +13,6 @@ import (
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-sdk/go/views"
"mesh-delivery-builder/internal/versions"
)
// heldWriter is the builder's finding writer: its findings are raised as they happen, so the writer holds them (design 47 G
@@ -151,19 +149,3 @@ func (f *findings) notHeard(ctx context.Context) heard.Writer {
return f.w.Clear(ctx, scope, rest[:i], rest[i+1:], "the builder hears it")
}}
}
// floorSaid is the floor finding (design 51 *Health and conditions*: a floor source silent): raised for a name waiting on
// its floor, about that name, cleared once all three sources answered.
func (f *findings) floorSaid(ctx context.Context) func(versions.FloorWait, bool) {
return func(w versions.FloorWait, raised bool) {
if !raised {
f.clear(ctx, versions.FloorSilent, mcc.ScopeModule, w.Name)
return
}
f.raise(ctx, finding{kind: versions.FloorSilent, scope: mcc.ScopeModule, id: w.Name, summary: w.Finding(),
headline: "A version's floor is not known",
explanation: "The builder numbers a name only once its registry seat, the forge bridge's tags and the indexer's requirements all answered; one of them did not.",
resolved: "All three answered.",
needs: "builder_floor_waits names the silent source; builder_floor_again asks again by hand."})
}
}
@@ -14,8 +14,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
sweep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshartifactsweep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/process"
)
// A done key whose blob the artifact store no longer holds is built again, by the builder whole against the bus
@@ -194,31 +192,3 @@ func artifactsGoneLeadsTheBuilderToBuildTheKeyAgain(t *testing.T) {
b.fake.count("mesh-build-go.build_go_build"))
}
}
// The last versions-filled is read at the start from the seat event's own kept stream, kept by age, through the SDK's hearing
// from the first message (design 47 G A-411), never from EVENTS: a message the stream keeps is found, an empty one is none.
func TestTheLastVersionsFilledIsReadFromItsKeptStream(t *testing.T) {
b := startBed(t)
acct := process.Account{Node: "n1", Module: "mesh-delivery-builder"}
if err := b.js.DeleteStream(b.ctx, eventsStream); err != nil { // the bus keeps a kept event off EVENTS: its subject is nowhere else
t.Fatal(err)
}
if _, err := b.js.CreateOrUpdateStream(b.ctx, jetstream.StreamConfig{Name: meshcatalog.StreamVersionsFilled,
Subjects: []string{meshcatalog.SubjectVersionsFilled}, MaxAge: 24 * time.Hour}); err != nil {
t.Fatal(err)
}
if _, err := b.js.CreateOrUpdateConsumer(b.ctx, meshcatalog.StreamVersionsFilled, jetstream.ConsumerConfig{
Durable: acct.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy, FilterSubject: meshcatalog.SubjectVersionsFilled}); err != nil {
t.Fatal(err)
}
read := lastKeptOf(b.js, acct, t.Logf)
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || found {
t.Fatalf("empty stream: found %v, %v", found, err)
}
if _, err := b.js.Publish(b.ctx, meshcatalog.SubjectVersionsFilled, []byte(`{"v":1}`)); err != nil {
t.Fatal(err)
}
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || !found {
t.Fatalf("kept message: found %v, %v", found, err)
}
}
@@ -9,10 +9,8 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
@@ -31,6 +29,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry"
@@ -177,6 +176,8 @@ func (f *fakeBuildModules) step(module, name string, args map[string]any) (any,
return json.RawMessage(`{"artifact":"` + fmt.Sprint(args["artifact"]) + `","digest":"` + d + `","reference":"registry.example/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@` + d + `","pushed":true}`), nil
case tool != "build_image_build" && f.refusePush.Load():
return nil, fmt.Errorf("%s%v: the artifact store answered 507 Insufficient Storage", builds.NotStored, args["artifact"])
case tool == "build_go_build" && args["seat"] == "go-package-registry": // a Go package under a reserved version: <name>@<version>
return json.RawMessage(`{"digest":"` + digestOf(fmt.Sprint(args["artifact"])) + `","reference":"git.novox.be/novox/mesh-catalog/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@v` + fmt.Sprint(args["version"]) + `"}`), nil
case tool != "build_image_build": // a bundle or an archive is pushed and its reference answered (ADR 0498 clause 1)
d := digestOf(fmt.Sprint(args["artifact"]))
return json.RawMessage(`{"digest":"` + d + `","reference":"artifact-store://` + filepath.Base(fmt.Sprint(args["module"])) + `/` + fmt.Sprint(args["artifact"]) + `/blobs/` + d + `"}`), nil
@@ -323,7 +324,7 @@ func startBedWith(t *testing.T, closed bool) *bed {
// each have their durable consumer.
b.catalog = newCatalogHolder(t, ctx, js, ctl)
b.catalog.buildSeats(t, ctl, map[string]string{"node-build-go": testGo, "node-build-node": testNode, "node-build-image": testImage,
"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer", // the floor's sources are the holders of git and mesh-catalog
"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer",
"mesh-builds": builds.BuilderModule}) // the builder's own seat, whose verb reserved it answers once its definition is read (A-115, A-278)
readers := []string{"n1_" + builds.BuilderModule, "n2_" + builds.BuilderModule}
// Design 47 G §717, A-298: the catalog half names testAssigner the claimant of mesh-module-assigner, and its seat-holders view
@@ -571,7 +572,7 @@ func isState(state string) func(builds.BuilderBuild) bool {
// the digests of both bundles, both build modules' toolchains, after a fetch and a build on one node (ADR 0478 clause 4).
func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
b := startBed(t)
// The builder's versions, findings and the floor's three sources are on the bus, the seat answering 0.1.4; two merges close
// The builder's findings are on the bus, the seat answering 0.1.4; two merges close
// together, the first replaced before its claim. The builder numbers neither in its state versions (design 47 H H-A-159,
// G §348, §369): the reservation is the one place a version is numbered.
reg := b.registry(t, "n1", "0.1.4")
@@ -584,12 +585,6 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
doneBound := map[string]string{"MESH_BUILDER_STEP_BOUND": testbus.SetupBound(t).String()}
b.start(t, "n1", doneBound)
v := b.await(t, "netcheck", isState(builds.BuildDone))
for _, a := range []string{"tools-go", "tools-typescript"} {
es := reg.of(t, "netcheck/"+a)
if len(es) != 0 {
t.Errorf("versions of netcheck/%s = %+v, want none: the builder numbers nothing of its own (H-A-159)", a, es)
}
}
if v.By != "n1.mesh-delivery-builder" || v.Manifest != digest || len(v.Artifacts) != 2 {
t.Fatalf("build = %+v", v)
}
@@ -622,7 +617,7 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
for _, e := range b.logged(t, "netcheck") {
if e.Event != builds.BuildSaidEvent {
ended = append(ended, e)
} else if e.Why == versions.SaidNumbered || e.Why == versions.SaidKept {
} else if e.Why == "numbered" || e.Why == "kept" { // the narrations of the numbering from before G (design 47 H §756)
t.Errorf("said = %+v, want no version of the builder's own numbered (H-A-159)", e)
}
}
@@ -658,40 +653,6 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
}
// Versions numbered before G, which the state keeps until G §372 removes it: one a holder removes below, one it refuses.
kept, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-typescript", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.5", Module: "netcheck",
Fingerprint: fp, Digest: digestOf("tools-typescript"), Seat: ociartifactregistry.Seat, State: versions.Published, At: time.Now().UTC()})
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-typescript", "0.1.5"), kept); err != nil {
t.Fatal(err)
}
refusable, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-go", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.6", Module: "netcheck",
Fingerprint: "src2:" + strings.Repeat("6", 64), Seat: ociartifactregistry.Seat, State: versions.Numbered, At: time.Now().UTC()})
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-go", "0.1.6"), refusable); err != nil {
t.Fatal(err)
}
// Running-testing note (review round 1): two claims never get one number on the bus's own compare-and-set, as
// the builder's state versions keeps them: eight claims of one name at once, eight versions.
store := versions.Versions{Store: awaitedVersions{b: process.AwaitBucket(b.ctx, b.js, nil, builds.StateBucket(builds.BuilderModule, versions.State), "", t.Logf)}}
numbers := make(chan string, 8)
var claims sync.WaitGroup
for i := range 8 {
claims.Go(func() {
d, _, err := store.Number(b.ctx, versions.Claim{Name: "netcheck/race", Kind: versions.KindBundle, Fingerprint: fmt.Sprintf("f%d", i)})
if err != nil {
t.Error(err)
}
numbers <- d.Version
})
}
claims.Wait()
close(numbers)
got := map[string]bool{}
for v := range numbers {
got[v] = true
}
if len(got) != 8 {
t.Errorf("eight claims of one name at once were numbered %v, want eight versions", slices.Sorted(maps.Keys(got)))
}
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
}
@@ -724,20 +685,114 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, "89abcdef0123456789abcdef0123456789abcdef", third, 3) // the entry moves to a later commit, same fingerprint
b.awaitFP(t, "netcheck", third, isState(builds.BuildDone))
reg.awaitFinding(t, failed, false)
// DLV-B4: the seats' refused and removed, heard on the builder's durable consumer, move a numbered version: a retention
// removal turns the entry removed with its reason, a refusal refused with the holder's reason and the bytes it refused.
reg.outcome(t, ociartifactregistry.SubjectRemoved, versions.Outcome{Name: "netcheck/tools-typescript", Version: "0.1.5", Kind: "bundle", Holder: "distribution", Reason: "retention"})
// DLV-B4: a seat's refused, heard on the builder's durable consumer, is the finding publish-refused about the name with the
// holder's reason; the numbering from before G, which marked its state versions, is gone (design 47 H §756).
reg.outcome(t, ociartifactregistry.SubjectRefused, versions.Outcome{Name: "netcheck/tools-go", Version: "0.1.6", Digest: digestOf("other"), Kind: "bundle", Holder: "distribution", Reason: "the cap"})
reg.awaitOf(t, "netcheck/tools-typescript", func(es []versions.Entry) bool {
return slices.ContainsFunc(es, func(e versions.Entry) bool {
return e.Version == "0.1.5" && e.State == versions.Removed && e.Reason == "retention"
})
})
reg.awaitOf(t, "netcheck/tools-go", func(es []versions.Entry) bool {
return slices.ContainsFunc(es, func(e versions.Entry) bool {
return e.Version == "0.1.6" && e.State == versions.Refused && e.Reason == "the cap" && e.RefusedDigest == digestOf("other")
})
})
reg.awaitFinding(t, meshconditionsclient.Key(meshconditionsclient.ScopeModule, "netcheck/tools-go", versions.PublishRefused), true)
// Issue 721 B4 (design 47 H2 H-A-521, H-A-547 (3), H-A-551): an entry naming a mesh package with no version is built with
// the version its publisher reserved at the source revision of the key's own origin, once that reservation's artifact is
// published, never the newest version a registry seat said published; once the version is released and the reservation
// gone, the next such build takes it from the release record.
const pkg = "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings"
goPublished := func(version, digest string) {
t.Helper()
reg.outcome(t, gopackageregistry.SubjectPublished, versions.Outcome{Name: pkg, Version: version, Digest: digest, Kind: versions.KindPackage, Holder: "go-registry"})
}
// The reservations' states, as the controller makes them from the builder's manifest, and the catalog seat's versions, which
// a first reservation reads (none released yet).
for _, state := range []string{versions.ReservedState, versions.ActedState} { // acted keeps the release record
if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, state)}); err != nil {
t.Fatal(err)
}
}
none, _ := json.Marshal(map[string]any{"result": meshcatalog.VersionsAnswer{Module: "disk-load", Versions: []meshcatalog.VersionEntry{}}, "node": "ctl"})
if s, err := b.js.Conn().Subscribe("mesh.seat."+meshcatalog.Seat+".call.versions.>", func(m *nats.Msg) { _ = m.Respond(none) }); err != nil {
t.Fatal(err)
} else {
defer s.Unsubscribe()
}
goPublished("9.9.9", digestOf("elsewhere")) // the newest a registry seat said published: of no reservation at this origin
b.awaitSaid(t, "the published of "+pkg+"@9.9.9")
const diskLoad = "catalogue-8b8b0f66-disk-load.module.json"
raw, err := os.ReadFile(filepath.Join("testdata", diskLoad))
if err != nil {
t.Fatal(err)
}
pubFP := "src2:" + strings.Repeat("5", 64)
publisher := b.entry("disk-load", "modules/disk-load", commit, pubFP, meshcatalogclient.ManifestDigest(raw), b.manifestOf(t, diskLoad), bothToolchains, 0)
publisher.Artifacts = []meshcatalog.Artifact{{Ref: "disk-load:diskreadings", Kind: versions.KindPackage, Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: pkg}}}
b.catalog.put(t, publisher)
importer := func(fp2 string) {
t.Helper()
e := b.entry("netcheck", "modules/netcheck", commit, fp2, digest, b.manifestOf(t, netcheck), bothToolchains, 0)
e.Packages = map[string]string{pkg: ""}
b.catalog.put(t, e)
}
fourth := "src2:" + strings.Repeat("6", 64)
importer(fourth)
pub := b.awaitFP(t, "disk-load", pubFP, isState(builds.BuildDone))
conn, err := process.Connect(process.Account{URL: b.srvURL, Module: "mesh-delivery-view", User: "ctl", Password: "pw"})
if err != nil {
t.Fatal(err)
}
defer conn.Close()
answer, err := conn.Call("seat:mesh-builds.reserved", meshbuilds.ReservedInput{Module: "disk-load"})
var reserved meshbuilds.ReservedAnswer
if err != nil || json.Unmarshal(answer, &reserved) != nil || reserved.Version == "" {
t.Fatalf("reserved of disk-load = %s, %v; want the version its trunk build reserved", answer, err)
}
pkgDigest := ""
for _, a := range pub.Artifacts {
if a.Name == "diskreadings" {
pkgDigest = a.Digest
}
}
b.awaitSaid(t, "package "+pkg+" has no published version")
goPublished(reserved.Version, pkgDigest)
want := "v" + reserved.Version
if v := b.awaitFP(t, "netcheck", fourth, isState(builds.BuildDone)); v.Packages[pkg] != want {
t.Errorf("netcheck built with %v, want %s at %s, its publisher's reservation at the key's origin (H-A-547 (3))", v.Packages, pkg, want)
}
released, _ := json.Marshal(meshcatalog.VersionReleasedEvent{V: 1, Module: "disk-load", Version: reserved.Version})
msg := nats.NewMsg(meshcatalog.SubjectVersionReleased)
msg.Header.Set("x-event-id", "released-disk-load-"+reserved.Version)
msg.Data = released
if _, err := b.js.PublishMsg(b.ctx, msg); err != nil {
t.Fatal(err)
}
// The release deletes the reservation (H-A-551): what fills the next build is the release record alone.
reservations, err := b.js.KeyValue(b.ctx, builds.StateBucket(builds.BuilderModule, versions.ReservedState))
if err != nil {
t.Fatal(err)
}
// Watched, never polled: the watch gives the keys standing, then a nil, then each change (the delete of the release).
w, err := reservations.WatchFiltered(b.ctx, []string{versions.NameFilter("disk-load")})
if err != nil {
t.Fatal(err)
}
defer func() { _ = w.Stop() }()
held, caughtUp := map[string]bool{}, false
timeout := time.After(20 * time.Second)
for !caughtUp || len(held) > 0 {
select {
case e := <-w.Updates():
switch {
case e == nil:
caughtUp = true
case e.Operation() == jetstream.KeyValuePut:
held[e.Key()] = true
default:
delete(held, e.Key())
}
case <-timeout:
t.Fatalf("disk-load holds %v 20 s after its version-released of %s, want none", held, reserved.Version)
}
}
fifth := "src2:" + strings.Repeat("7", 64)
importer(fifth)
if v := b.awaitFP(t, "netcheck", fifth, isState(builds.BuildDone)); v.Packages[pkg] != want {
t.Errorf("netcheck built with %v once disk-load %s was released, want %s at %s from its release record (H-A-551)", v.Packages, reserved.Version, pkg, want)
}
}
// TestAnArchiveOnlyModuleAndARootModuleAreBuilt: the indexer gives an archive no language, so modules.ca-trust has no
@@ -1154,15 +1209,14 @@ func TestARestartedBuilderPutsNoSecondAsk(t *testing.T) {
}
}
// registry is the part of the bed design 51's builder cases need: the builder's states versions, findings, floor-waits and
// reasks, EVENTS with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's
// own events kept, and the floor's three sources served on the bus as their holders answer through the tool runner
// ({result}): the seat's versions, the seat git's tags and the indexer's indexer_requirements.
// registry is the part of the bed design 51's builder cases need: the builder's states findings and reasks, EVENTS
// with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's own events kept, and
// the seat's versions served on the bus as its holder answers through the tool runner ({result}).
type registry struct {
b *bed
versions, findings, reasks jetstream.KeyValue
mu sync.Mutex
numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349
b *bed
findings, reasks jetstream.KeyValue
mu sync.Mutex
numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349
}
func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *registry {
@@ -1175,8 +1229,7 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
}
return kv
}
r.versions, r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, versions.State)), mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState))
mk(builds.StateBucket(builds.BuilderModule, versions.FloorWaitsState))
r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState))
// EVENTS with two seats' outcomes, and the forge bridge's stream (a branch's end): each with the builder's durable consumer.
for stream, subjects := range map[string][]string{
eventsStream: {"mesh.mod.*.event.>", "mesh.seat.*.event.>"},
@@ -1206,7 +1259,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
}
for subject, answer := range map[string]any{
"mesh.seat." + ociartifactregistry.Seat + ".call.versions.>": map[string]any{"versions": listed},
"mesh.seat.git.call.tags.>": map[string]any{"tags": []string{}},
} {
reply, _ := json.Marshal(map[string]any{"result": answer, "node": "ctl"})
s, err := nc.Subscribe(subject, func(m *nats.Msg) { _ = m.Respond(reply) })
@@ -1218,42 +1270,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
return r
}
// of is every entry versions holds of name.
func (r *registry) of(t *testing.T, name string) []versions.Entry {
t.Helper()
l, err := r.versions.ListKeysFiltered(r.b.ctx, versions.NameFilter(name))
if err != nil {
t.Fatal(err)
}
defer func() { _ = l.Stop() }()
var out []versions.Entry
for k := range l.Keys() {
e, err := r.versions.Get(r.b.ctx, k)
if err != nil {
t.Fatal(err)
}
var v versions.Entry
if err := json.Unmarshal(e.Value(), &v); err != nil {
t.Fatal(err)
}
out = append(out, v)
}
return out
}
// awaitOf reads name's entries until pred holds of them, within 20 s.
func (r *registry) awaitOf(t *testing.T, name string, pred func([]versions.Entry) bool) []versions.Entry {
t.Helper()
var es []versions.Entry
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
if es = r.of(t, name); pred(es) {
return es
}
}
t.Fatalf("versions of %s = %+v within 20 s", name, es)
return es
}
// published says the artifact seat's published for name@version, as its holder does.
func (r *registry) published(t *testing.T, name, version, digest string) {
t.Helper()
@@ -159,26 +159,12 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
conn.SetReconnectHandler(func(*nats.Conn) { hearing.Again(); heard.Nudge("") })
// The builder asks the controller, as its own account, whether the artifact store still holds a done key's blobs
// (the seat verb held, novox/hq issue 1937) before it leaves the key done, on its calls connection.
// The state versions, kept from before G (design 51 *The versions*) and read through builder_versions until G §372 removes
// it, bound once the bus holds it; the builder numbers nothing in it (design 47 H H-A-159).
versionsKV := process.AwaitBucket(ctx, js, conn, own.versions, "builder_versions answers nothing of the versions numbered before G", logger.Printf)
found := &findings{module: cred.Module, w: fw, logf: logger.Printf, now: time.Now}
floorWaits := &versions.FloorWaits{Holder: versions.HolderOf(branches), Logf: logger.Printf, Said: found.floorSaid(context.WithoutCancel(ctx))}
// The names waiting on their floor are kept in the state floor-waits (DLV-B4): a restarted builder takes them in, so
// their silent sources' events still wake them; until the state is bound they are kept here only.
process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, versions.FloorWaitsState), "the names waiting on their floor are kept in memory only, and builder_floor_waits shows none", logger.Printf).
Ready(func(kv jetstream.KeyValue) {
floorWaits.Keep(kvKeeper{ctx: ctx, kv: kv}, heldFloorWaits(ctx, kv, logger.Printf))
})
// A package is numbered under its name in its ecosystem, read from the catalog half's entries (design 32, design 47 G §348).
numberer := &versions.Numberer{Versions: versions.Versions{Store: awaitedVersions{b: versionsKV}}, Floor: floorVia(calls.Call, versions.RequirementsFrom(versions.EntriesOf(branches))), Waits: floorWaits,
Names: versions.NamesFrom(versions.EntriesOf(branches))}
// A publish that ends badly is a finding (design 51 *Health and conditions*): a holder's refused, a version no holder
// answered within its bound (a key of the state bounds with its own time to live), a seat's outcome that does not read.
pubBoundsKV := process.AwaitBucket(ctx, js, conn, own.bounds, "a publish no holder answers, and a node holding the old form seven days, are not raised", logger.Printf)
stepReads.bounds, stepReads.findings = func() jetstream.KeyValue { return pubBoundsKV.KV() }, found
pubs := &publishes{bounds: pubBoundsKV.KV, versions: numberer.Versions, findings: found, bound: versions.PublishBound, logf: logger.Printf}
numberer.Publishing = pubs.arm
pubs := &publishes{findings: found}
stepExpiry := &buildrun.Expiry{}
var b *build.Builder
seatsChanged := func(ctx context.Context) {
@@ -211,9 +197,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
unput := &unputs{bounds: pubBoundsKV.KV, store: b.Claimer.Store, looking: b.Looking, findings: found,
bound: meshconditionsclient.CallUnansweredAfter, now: time.Now, logf: logger.Printf}
b.Left, b.Ended = unput.left, unput.ended
// The builder numbers nothing of its own (design 47 H H-A-159, G §348, §349, §369): b.Numbers stays nil, so no trunk build
// is numbered in the state versions, waits on a floor or arms a publish-unanswered bound of it; the reservation is the one
// place a version is numbered. The state, kept from before G, is still read (builder_versions) until G §372 removes it.
// The builder numbers nothing of its own and asks no floor (design 47 H §756, H H-A-159, G §348, §349, §369): the
// reservation is the one place a version is numbered.
// The builder's toolchain waits (design 47 G §672): its state waits, and wait-held and wait-ended on its stream waits; its
// bound is its setting toolchain-wait-minutes.
waitBound, err := toolchainWaitOf(getenv("MESH_BUILDER_TOOLCHAIN_WAIT_FILE"))
@@ -239,8 +224,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
return err
}
b.RecordBound = time.Duration(recordBound) * time.Second
// Before it waits for an unpinned package, the build reads what the Go package registry seat holds of it (H-A-194).
b.PublishedVersions = publishedVersionsVia(calls.Call)
waitsBucket := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.WaitsState), "the toolchain waits are kept in memory only, and builder_waits shows none", logger.Printf)
b.Waits = newWaitsKept(waitsBucket, func(ctx context.Context, event, id string, body any) error {
return emitEvent(context.WithoutCancel(ctx), js, cred, event, id, body)
@@ -248,10 +231,10 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
waitsBucket.Ready(func(kv jetstream.KeyValue) { b.Waits.(*waitsKept).start(ctx, kv) })
// The plans no seat builds (design 47 H2 §795, H-A-425): kept in the state unbuildable, read by builder_unbuildable.
b.Unbuildables = unbuildableKept{b: process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.UnbuildableState), "the plans no seat builds are said, and builder_unbuildable lists none", logger.Printf)}
// The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's versions-filled
// and version-released heard; nothing is reserved before the fill.
// The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's version-released
// heard (design 47 H2 H-A-552: no fill is waited for).
reservedKV := process.AwaitBucket(ctx, js, conn, own.reserved, "no version is reserved: builds are made unreserved", logger.Printf)
reserved := newReservations(awaitedReserved{awaitedVersions{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, b.Reconsider, logger.Printf)
reserved := newReservations(awaitedReserved{awaitedState{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, logger.Printf)
// The index by digest and by version beside the reservations is written again once the state is bound (H-A-269 (1), H-A-271).
reservedKV.Ready(func(jetstream.KeyValue) { reserved.reindex(ctx) })
// Each artifact the holder says published at a reserved version is said as the seat mesh-builds' package-published (design 47 G §52).
@@ -265,12 +248,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// A take-over of a series' reservation by another fingerprint withdraws the older build (H-A-225).
reserved.withdraw = b.Withdraw
reserved.recordAgain = b.RecordAgain // a done build's digests its end did not record are recorded at the start (H-A-492)
// The last versions-filled the stream keeps is read at the start (design 47 G §369, §372): a restart does not lose it.
reserved.readFilled(ctx, lastKeptOf(js, cred, logger.Printf), sleeps)
// A state bound later numbers the builds looked at without it.
versionsKV.Ready(func(jetstream.KeyValue) { b.Reconsider(ctx) })
// The versions' hand acts (builder_publish_again, builder_floor_again) come through reasks, as builder_build_again.
acts := versions.Acts{Numberer: numberer, DropReserved: reserved.dropped, Reconsider: b.Reconsider}
// The versions' hand acts (builder_publish_again, builder_reserved_drop) come through reasks, as builder_build_again.
acts := versions.Acts{DropReserved: reserved.dropped}
// A reserved version left unpublished is published again, by the builder on an event or by a person's tool (design 47 G
// §588): its items on the work queue publishes, the module's own stream of its old streams section (design 47 H2 §793, H-A-454).
actedKV := process.AwaitBucket(ctx, js, conn, own.acted, "no version is published again on an event or by builder_publish_again", logger.Printf)
@@ -333,7 +312,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
reserved.releasedAtStart(ctx)
items.AskAllDone(ctx)
})
wirePublishItems(reserved, items, awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}}, releasedKept)
wirePublishItems(reserved, items, awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, releasedKept)
acts.Republish = republish.Republish
acts.PublishDrop = func(ctx context.Context, module, version, by, why string) (string, error) {
return pq.drop(ctx, items, module, version, by, why)
@@ -342,7 +321,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
acts.ReserveDone = reserveDoneAct(b.ReserveDone, republish.Republish, logger.Printf)
// The operator is asked once a key's event builds are spent (design 47 G §568): the builder's asker on the seat operator-channel.
decided := &decisions{subject: oc.SubjectDecided(cred.Module)}
retakeActed := awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}}
retakeActed := awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}
asker := &operatorask.Asker[oc.Warrant]{Module: cred.Module, Call: calls.Call, Record: calls.Ask, Publish: publishVia(ctx, js), Subscribe: decided.hear(logger.Printf),
Contract: operatorask.Contract{Seat: oc.Seat, StateAsks: oc.StateAsks},
AskSubject: oc.AcceptSubjectAsk, DecidedSubject: oc.SubjectDecided}
@@ -479,11 +458,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// The seat mesh-artifact-sweep says artifacts-gone when it found a key's blob gone (issue 1937, ADR 0571 §2): the
// builder's durable consumer on EVENTS, made by the grants part from the manifest's consumes. Where it is not there yet the builder says
// so; it still asks held at its start and at every module value.
// The same consumer carries what wakes a floor (design 51 *The floor*): the indexer's take-in.taken (design 47 H H-A-116) and the
// condition keeper's condition-cleared.
floor := floorWake{b: b, waits: floorWaits, logf: logger.Printf}
// And the four registry seats' published, refused and removed (DLV-B4), which move a numbered version.
seatHeard := seatHearer{n: numberer, b: b, logf: logger.Printf, pub: pubs, res: reserved}
seatHeard := seatHearer{b: b, logf: logger.Printf, pub: pubs, res: reserved}
// Each part takes the events it hears in turn; a handling over the setting slow-event is said with the part that took it
// (design 47 H2 §794; H-A-461 (2)).
slow, err := slowEvent()
@@ -496,7 +472,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
{"what a node's engine reads", func(m jetstream.Msg) bool { return reads.heard(m, logger.Printf) }}, // manifest-reads-changed (ADR 0618 §4)
{"the toolchains reported", func(m jetstream.Msg) bool { return heardTools.Reported(ctx, m) }},
{"the toolchains running", func(m jetstream.Msg) bool { return heardTools.Running(ctx, m) }},
{"the floor", func(m jetstream.Msg) bool { return floor.heard(ctx, m) }},
{"the reservations", func(m jetstream.Msg) bool { return reserved.heard(ctx, m) }},
{"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }},
}
@@ -573,20 +548,16 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
b.SayUnbuildable(ctx) // at the start, once the first views are in: the plans no seat builds in one line (§795)
}
branches.Changed = half.Changed(ctx)
// A catalog revision the builder hears wakes a floor whose tags or requirements were silent (design 47 G A-119).
half.floor = func(ctx context.Context) {
(&floorWake{b: b, waits: floorWaits, logf: logger.Printf}).wake(ctx, versions.WakeRevision, "", "")
}
// All of the catalog half's wiring is set before the reader starts: its views are heard on the reader's goroutines from then.
reader.Start(ctx, js, cred, process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, views.StatusState), "builder_first_views reads nothing and builder_first_view_again is not heard", logger.Printf))
// Every part has registered: the hub pulls the module's durable. Where the consumer is not there yet the builder says so
// and binds it at a later change (heard.Writer; ADR 0615 §5).
_ = notHeard.Bind(eventsStream, sweep.EventArtifactsGone+", what wakes a floor, the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again", func() error {
_ = notHeard.Bind(eventsStream, sweep.EventArtifactsGone+", the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again", func() error {
if err := hub.Start(ctx, js, cred); err != nil {
return err
}
// And the kept seat events it handles (the build seats' toolchain-reported, the seat mesh-catalog's versions-filled
// and version-released), each on its own stream: the tool runner reads its own twin there (lead answer A-397).
// And the kept seat events it handles (the build seats' toolchain-reported, the seat mesh-catalog's
// version-released), each on its own stream: the tool runner reads its own twin there (lead answer A-397).
hub.StartKept(ctx, js, cred)
return nil
})
@@ -633,7 +604,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}
return
}
pubs.ended(ctx, e)
}
watchBounds(ctx, kv, each, found.notHeard(ctx), errs, logger.Printf)
})
@@ -8,8 +8,8 @@ import (
const namedTreePrefix = "named:"
// seatEventPatterns are the seats' events the builder's own handler takes off its durable consumer (its manifest's `consumes` of
// them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, condition-cleared, the node-engine
// seat's events, of the seat mesh-catalog, version-released and versions-filled, and the indexer's take-in.taken. The seat mesh-catalog's
// them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, the node-engine
// seat's events, of the seat mesh-catalog, version-released. The seat mesh-catalog's
// catalog-revision and registration-changed and the seat mesh-delivery's source-moved are the views reader's (the branch
// follower's), so no pattern here covers them: a message has one taker.
var seatEventPatterns = func() []string {
@@ -18,9 +18,8 @@ var seatEventPatterns = func() []string {
"mesh-artifact-sweep", "mesh-conditions", "node-engine", "node-build-go", "node-build-image", "node-build-node"} {
out = append(out, "mesh.seat."+seat+".event.>")
}
for _, event := range []string{meshcatalog.EventVersionReleased, meshcatalog.EventVersionsFilled} {
for _, event := range []string{meshcatalog.EventVersionReleased} {
out = append(out, "mesh.seat."+meshcatalog.Seat+".event."+event, "mesh.seat."+meshcatalog.Seat+".event."+event+".>")
}
// And the indexer's take-in.taken, which wakes the floor (design 47 H H-A-116).
return append(out, takenInSubject)
return out
}()
@@ -32,14 +32,11 @@ func TestTheNamesAreTheManifests(t *testing.T) {
t.Errorf("the builder reads %s, its manifest's reads are %v", read, m.Reads)
}
}
// The catalog half (design 47 G §348, §614) is followed through the seat, and no state of the indexer is; the indexer's
// event take-in.taken wakes the floor (design 47 H H-A-116).
if !slices.Contains(m.Consumes, "mesh-delivery-indexer.take-in.taken") {
t.Errorf("the builder's floor wakes on no take-in.taken: its manifest consumes %v", m.Consumes)
}
// The catalog half (design 47 G §348, §614) is followed through the seat, and nothing of the indexer is: with the floor gone
// (design 47 H §756) not its take-in.taken either (H-A-116).
for _, c := range m.Consumes {
if strings.HasPrefix(c, "mesh-delivery-indexer.") && c != "mesh-delivery-indexer.take-in.taken" {
t.Errorf("the builder follows %s, an indexer state, its manifest consumes it", c)
if strings.HasPrefix(c, "mesh-delivery-indexer.") {
t.Errorf("the builder follows %s of the indexer, its manifest consumes it", c)
}
}
for _, view := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "seat:mesh-module-assigner.views.assignments"} {
@@ -51,7 +48,6 @@ func TestTheNamesAreTheManifests(t *testing.T) {
"mesh-build-go_steps": buildrun.StepsBucket("mesh-build-go"),
ownBucketsOf("acme-builder").toolchainsHeard: "acme-builder_toolchains-heard",
ownBucketsOf("acme-builder").bounds: "acme-builder_bounds",
ownBucketsOf("acme-builder").versions: "acme-builder_versions",
ownBucketsOf("acme-builder").instances: "acme-builder_instances",
} {
if want != got {
@@ -2,9 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/nats-io/nats.go/jetstream"
@@ -17,53 +15,15 @@ import (
)
// publishes raises and clears the builder's findings of a publish that ended badly (versions/publish.go): a holder's
// refused, a version unanswered past its bound, kept as a key of the state bounds with its own time to live, and a seat's
// outcome that does not read.
// refused and a seat's outcome that does not read. A reserved version left unpublished is the reservation's bound (design 47
// G §369, design 47 H §756: the numbered version's bound goes with the numbering from before G).
type publishes struct {
bounds func() jetstream.KeyValue
versions versions.Versions
findings *findings
bound time.Duration
logf func(string, ...any)
}
// arm writes the version's bound when none stands, so a standing bound keeps its time. A bound that cannot be written
// would never end, so the version is publish-unanswered at once (review round 2): the finding says why.
func (p *publishes) arm(ctx context.Context, e versions.Entry) {
kv := p.bounds()
var err error
if kv == nil {
err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState)
} else if _, err = kv.Create(ctx, versions.PublishBoundKey(e.Name, e.Version), versions.EncodeBound("the publish of "+e.Name+"@"+e.Version+" to "+e.Seat, time.Now().Add(p.bound)), jetstream.KeyTTL(p.bound)); errors.Is(err, jetstream.ErrKeyExists) {
err = nil
}
if err == nil {
return
}
p.logf("the publish bound of %s@%s is not written, so it is raised unanswered now: %v", e.Name, e.Version, err)
p.unanswered(ctx, e, fmt.Sprintf("its bound could not be written (%v), so the builder cannot wait on the holder's word", err))
}
// unanswered raises publish-unanswered about e's name, saying why.
func (p *publishes) unanswered(ctx context.Context, v versions.Entry, why string) {
p.findings.raise(ctx, finding{kind: versions.PublishUnanswered, scope: meshconditionsclient.ScopeModule, id: v.Name,
summary: fmt.Sprintf("%s said neither published nor refused of %s@%s: %s", v.Seat, v.Name, v.Version, why),
headline: "A registry seat did not answer a publish",
explanation: "The builder built and numbered " + v.Name + " " + v.Version + " and asked " + v.Seat + " to publish it; no word of its holder is known, so the build says done while the version may not be in the registry.",
resolved: "That version is published, or a later version of " + v.Name + " is.",
needs: "a look at the holder of " + v.Seat + " (its health and log); builder_publish_again asks the publish again."})
}
// heard is told each holder's word the numberer took in: published clears the name's findings, refused raises
// publish-refused with the holder's reason, and either ends the version's bound.
// heard is told each holder's word: published clears the name's findings (publish-unanswered too, raised by a builder of
// before the change), refused raises publish-refused with the holder's reason.
func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Outcome) {
if o.Version != "" {
if kv := p.bounds(); kv != nil {
if err := kv.Delete(ctx, versions.PublishBoundKey(o.Name, o.Version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
p.logf("the publish bound of %s@%s is not ended: %v", o.Name, o.Version, err)
}
}
}
switch event {
case versions.HeardPublished:
p.findings.clear(ctx, versions.PublishRefused, meshconditionsclient.ScopeModule, o.Name)
@@ -78,7 +38,7 @@ func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Ou
headline: "A registry seat refused a publish",
explanation: "The builder built and numbered " + o.Name + " " + o.Version + ", and the holder of " + seat + " refused to store it, so that version is not in the registry.",
resolved: "That version is published, or a later version of " + o.Name + " is.",
needs: "builder_versions shows the version and why; builder_publish_again publishes it again once the cause is mended."})
needs: "builder_reserved shows the version and why; builder_publish_again publishes it again once the cause is mended."})
}
}
@@ -96,24 +56,6 @@ func (p *publishes) read(ctx context.Context, seat string) {
p.findings.clear(ctx, versions.SeatOutcomeUnread, meshconditionsclient.ScopeModule, seat)
}
// ended is told each change of the state bounds: a bound whose time ended (the bus's marker) on a version still numbered
// raises publish-unanswered.
func (p *publishes) ended(ctx context.Context, e jetstream.KeyValueEntry) {
key, ok := versions.PublishBoundOf(e.Key())
if e.Operation() != jetstream.KeyValuePurge || !ok {
return
}
raw, _, found, err := p.versions.Store.Get(ctx, key)
if err != nil || !found {
return
}
v, err := versions.Decode(raw)
if err != nil || v.State != versions.Numbered {
return
}
p.unanswered(ctx, v, fmt.Sprintf("nothing within %s of its build", p.bound))
}
// watchBounds watches the state bounds, handing each change to each: a watch that cannot start loses every bound's end,
// so it is the finding family-not-heard naming the state until a later start watches it (review round 2).
func watchBounds(ctx context.Context, kv jetstream.KeyValue, each func(jetstream.KeyValueEntry), w heard.Writer, errs chan<- error, logf func(string, ...any)) {
@@ -300,8 +300,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
}
found := &memFindings{vals: map[string][]byte{}}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, nil, t.Logf)
rv.filled.Store(true)
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, t.Logf)
type oldItem struct {
key string
raw []byte
@@ -284,8 +284,7 @@ func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T)
call := func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf)
rv.filled.Store(true)
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf)
tried := make(chan string, 4)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: time.Now, logf: t.Logf,
reserved: func(ctx context.Context, m, v string) (versions.ReservedVersion, bool, error) {
@@ -65,7 +65,7 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi
released(ctx, b, kv, e, r, logf)
return
}
if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeFloorAgain || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone {
if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone {
// A version's hand act (design 51 *Tools of the builder*) may build again, so it is answered beside the watch.
go versionActed(ctx, acts, kv, e, r, logf)
return
@@ -196,7 +196,7 @@ func emitBuildEnded(ctx context.Context, js jetstream.JetStream, cred process.Ac
return nil
}
// versionActed answers a reasks value of builder_publish_again, builder_floor_again or builder_old_form's drop, a hand act said in the log.
// versionActed answers a reasks value of builder_publish_again, builder_publish_drop, builder_reserve_done, builder_reserved_drop or builder_old_form's drop, a hand act said in the log.
func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk, logf func(string, ...any)) {
var err error
if r.Mode == build.ModeRepublish {
@@ -227,14 +227,10 @@ func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue
} else {
r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.By, r.Why, r.At)
}
} else if r.Mode == build.ModeOldFormDrop {
if acts.DropOldForm == nil {
err = errors.New("this builder keeps no old-form window")
} else {
r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
}
} else if acts.DropOldForm == nil {
err = errors.New("this builder keeps no old-form window")
} else {
r.Answer, err = acts.FloorAgain(ctx, r.Name)
r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
}
if err != nil {
r.Answer, r.Refused = err.Error(), true
@@ -42,7 +42,7 @@ import (
// its grant. The gate over the seat's assignments, and its refusal, are mesh-sdk's (buildrun.PlacedNodes,
// issue 774).
func TestARefusedBucketIsSaidAndThePartGoesOn(t *testing.T) {
t.Run("a floor's wake is heard on the events consumer (design 51 The floor)", aFloorsWakeIsHeard)
t.Run("a registry seat's outcome is heard on the events consumer (DLV-B4)", aSeatsOutcomeIsHeard)
t.Run("a failed trunk build is a finding until a later done one (DLV-B7)", aFailedTrunkBuildIsAFinding)
refused := refusingBus{err: errors.New("nats: permissions violation for publish to $JS.API.CONSUMER.CREATE.KV_mesh-delivery-indexer_modules")}
if _, err := process.EssentialBucket(context.Background(), refusingBus{refuseOpen: true, err: refused.err}, "builder", "mesh-delivery-indexer_modules", "work"); err == nil ||
@@ -250,33 +250,16 @@ func (m *wakeMsg) Headers() nats.Header {
return nil
}
func aFloorsWakeIsHeard(t *testing.T) {
func aSeatsOutcomeIsHeard(t *testing.T) {
var logs bytes.Buffer
holders := map[string]string{"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer"}
waits := &versions.FloorWaits{Holder: func(seat string) (string, bool) { h, ok := holders[seat]; return h, ok }}
waits.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceRequirements}}, nil, time.Unix(0, 0))
waits.Wait("m/img", versions.SeatImages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0))
f := &floorWake{b: &build.Builder{}, waits: waits, logf: log.New(&logs, "", 0).Printf}
accepted := &wakeMsg{subject: takenInSubject}
if !f.heard(context.Background(), accepted) || !accepted.acked || !strings.Contains(logs.String(), "the floor of m/lib is asked again: take-in.taken") {
t.Fatalf("take-in.taken: acked %v, log %q", accepted.acked, logs.String())
}
logs.Reset()
cleared := &wakeMsg{subject: conditionClearedSubject, data: []byte(`{"subject":{"scope":"probe","id":"ace/mesh-delivery-forge-bridge"}}`)}
if !f.heard(context.Background(), cleared) || !strings.Contains(logs.String(), "the floor of m/img is asked again: condition-cleared") {
t.Fatalf("condition-cleared: log %q", logs.String())
}
if f.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
t.Fatal("artifacts-gone was taken as a floor's wake")
}
// DLV-B4: a registry seat's outcome on the same consumer moves a version; a published wakes a name whose seat was
// silent; one the state cannot take is left for the bus to give again.
logs.Reset()
waits.Wait("m/pkg", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceSeat}}, nil, time.Unix(0, 0))
h := &seatHearer{n: &versions.Numberer{Versions: versions.Versions{Store: noVersions{}}, Waits: waits}, b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
// DLV-B4: a registry seat's outcome on the events consumer moves a version; a by-digest publish marks none and is taken.
h := &seatHearer{b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
byDigest := &wakeMsg{subject: "mesh.seat.go-package-registry.event.published", data: []byte(`{"name":"m/other","digest":"sha256:aa","kind":"package","holder":"gitea"}`)}
if !h.heard(context.Background(), byDigest) || !byDigest.acked || !strings.Contains(logs.String(), "the floor of m/pkg is asked again: go-package-registry said published") {
t.Fatalf("published: acked %v, log %q", byDigest.acked, logs.String())
if !h.heard(context.Background(), byDigest) || !byDigest.acked || byDigest.naked {
t.Fatalf("published: acked %v, naked %v, log %q", byDigest.acked, byDigest.naked, logs.String())
}
if h.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
t.Fatal("artifacts-gone was taken as a seat's outcome")
}
// Design 47 G §369, A-415: a published of a version the reservation numbered, which the state versions does not hold, is
// taken: its artifact is marked and package-published said, never left for the bus to give again.
@@ -284,9 +267,8 @@ func aFloorsWakeIsHeard(t *testing.T) {
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil, t.Logf)
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, t.Logf)
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { saidPub = append(saidPub, p); return nil }
rv.filled.Store(true)
res, err := rv.Reserve(context.Background(), "m", "0.1", []string{"m:program"}, versions.Source{})
if err != nil {
t.Fatal(err)
@@ -299,9 +281,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
if !h.heard(context.Background(), published) || !published.acked || published.naked || len(saidPub) != 1 || saidPub[0].Artifact != "m:program" {
t.Fatalf("a published of a reserved version: acked %v, naked %v, said %+v, log %q", published.acked, published.naked, saidPub, logs.String())
}
if h.heard(context.Background(), &wakeMsg{subject: takenInSubject}) {
t.Fatal("take-in.taken was taken as a seat's outcome")
}
// Design 47 G A-420: a message left for the bus is said given up on the last delivery its consumer allows, never before.
for _, n := range []uint64{4, EventDeliveries} {
logs.Reset()
@@ -313,27 +292,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
}
}
// noVersions is a state versions that holds nothing.
type noVersions struct{}
func (noVersions) Get(context.Context, string) ([]byte, uint64, bool, error) {
return nil, 0, false, nil
}
func (noVersions) Create(context.Context, string, []byte) (uint64, error) {
return 0, errors.New("read only")
}
func (noVersions) Update(context.Context, string, []byte, uint64) (uint64, error) {
return 0, errors.New("read only")
}
func (noVersions) KeysOf(context.Context, string) ([]string, error) { return nil, nil }
// failingVersions is a state versions that cannot be read.
type failingVersions struct{ noVersions }
func (failingVersions) KeysOf(context.Context, string) ([]string, error) {
return nil, errors.New("down")
}
func aFailedTrunkBuildIsAFinding(t *testing.T) {
st := &memFindings{vals: map[string][]byte{}}
f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
@@ -354,30 +312,11 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
if _, ok := st.vals[key]; ok {
t.Error("a later done trunk build leaves build-failed")
}
// The floor finding: raised while a name waits on its floor, cleared once it is known.
fw := &versions.FloorWaits{Said: f.floorSaid(context.Background())}
fw.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0))
floorKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/lib", versions.FloorSilent)
if got, err := decodeFinding(st.vals[floorKey]); err != nil || !strings.Contains(got.Summary, "git.tags did not answer") {
t.Fatalf("the floor finding = %+v, %v", got, err)
}
fw.Answered("m/lib")
if _, ok := st.vals[floorKey]; ok {
t.Error("a known floor leaves floor-silent")
}
// Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a version
// no holder answered within its bound publish-unanswered, a seat's outcome that does not read seat-outcome-unread;
// a later published of the name clears the first two, the seat's next outcome that reads the third.
vs := versions.Versions{Store: memVersions{}}
for _, v := range []string{"0.1.3", "0.1.4"} {
raw, err := versions.Encode(versions.Entry{Name: "m/program", Kind: versions.KindBundle, Series: "0.1", Version: v, Seat: "oci-artifact-registry", State: versions.Numbered})
if err != nil {
t.Fatal(err)
}
vs.Store.(memVersions)[versions.Key("m/program", v)] = raw
}
pubs := &publishes{bounds: func() jetstream.KeyValue { return nil }, versions: vs, findings: f, bound: versions.PublishBound, logf: t.Logf}
h := &seatHearer{n: &versions.Numberer{Versions: vs}, b: &build.Builder{}, logf: t.Logf, pub: pubs}
// Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a seat's outcome
// that does not read seat-outcome-unread; a later published of the name clears the first, the seat's next outcome that
// reads the second. The numbered version's bound goes with the numbering from before G (design 47 H §756).
pubs := &publishes{findings: f}
h := &seatHearer{b: &build.Builder{}, logf: t.Logf, pub: pubs}
refusedKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishRefused)
refused := &wakeMsg{subject: "mesh.seat.oci-artifact-registry.event.refused", data: []byte(`{"name":"m/program","version":"0.1.3","digest":"sha256:bb","reason":"bytes differ"}`)}
if !h.heard(context.Background(), refused) || !refused.acked {
@@ -386,18 +325,10 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
if got, err := decodeFinding(st.vals[refusedKey]); err != nil || !strings.Contains(got.Summary, "refused to publish m/program@0.1.3") || !strings.Contains(got.Summary, "bytes differ") {
t.Fatalf("a holder's refused: the finding = %+v, %v", got, err)
}
pubs.ended(context.Background(), purged{key: versions.PublishBoundKey("m/program", "0.1.4")})
// A publish-unanswered a builder of before the change raised is cleared by the name's next published.
unansweredKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishUnanswered)
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "neither published nor refused of m/program@0.1.4") {
t.Fatalf("a bound ended unanswered: the finding = %+v, %v", got, err)
}
// Review round 2: a bound that cannot be written is publish-unanswered at once; a watch of bounds that cannot start
// is family-not-heard naming the state.
delete(st.vals, unansweredKey)
pubs.arm(context.Background(), versions.Entry{Name: "m/program", Version: "0.1.4", Seat: "oci-artifact-registry"})
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "its bound could not be written") {
t.Fatalf("a bound not written: the finding = %+v, %v", got, err)
}
st.vals[unansweredKey] = st.vals[refusedKey]
// A watch of bounds that cannot start is family-not-heard naming the state (review round 2).
watchBounds(context.Background(), refusedWatch{err: errors.New("permissions violation")}, func(jetstream.KeyValueEntry) {}, f.notHeard(context.Background()), nil, t.Logf)
if got, err := decodeFinding(st.vals[heard.Key(builds.BuilderModule, versions.BoundsState)]); err != nil || !strings.Contains(got.Summary, "permissions violation") {
t.Fatalf("bounds not watched: the finding = %+v, %v", got, err)
@@ -8,7 +8,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"slices"
"strings"
"sync/atomic"
"time"
"github.com/nats-io/nats.go/jetstream"
@@ -22,10 +21,10 @@ import (
)
// The reservations (design 47 G §369): the builder's state reserved, the catalog's versions it numbers from, and the
// catalog's version-released and versions-filled it hears.
// catalog's version-released it hears.
// awaitedReserved is the state reserved as versions.ReserveStore: bound once the bus holds it.
type awaitedReserved struct{ awaitedVersions }
type awaitedReserved struct{ awaitedState }
func (s awaitedReserved) Delete(ctx context.Context, key string) error {
kv, err := s.kv()
@@ -48,11 +47,9 @@ type reservations struct {
// ended ends the publish item of a build withdrawn, superseded or dropped, its held items terminated; heard acknowledges the
// held items of a version a published newly marked (design 47 H2 §793). Nil are none.
itemEnded, itemHeard func(ctx context.Context, module, version string)
filled atomic.Bool
bounds func() jetstream.KeyValue
found *findings
bound time.Duration
wake func(context.Context)
logf func(string, ...any)
// withdraw ends the running build of a module's fingerprint, superseded, with why (H-A-225); nil ends none.
withdraw func(module, fingerprint, why string)
@@ -116,9 +113,9 @@ func sayReservedOn(js jetstream.JetStream, cred process.Account) func(context.Co
// newReservations makes the reserving over store; the released versions of a module are asked of the seat mesh-catalog's
// verb versions through call (design 47 G §348), the only source numbering reads them from.
func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, wake func(context.Context), logf func(string, ...any)) *reservations {
rv := &reservations{bounds: bounds, found: found, bound: versions.UnreleasedBound, wake: wake, logf: logf}
rv.r = &versions.Reserver{Store: store, Filled: rv.filled.Load, ReleasedOf: func(_ context.Context, module string) ([]string, error) {
func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, logf func(string, ...any)) *reservations {
rv := &reservations{bounds: bounds, found: found, bound: versions.UnreleasedBound, logf: logf}
rv.r = &versions.Reserver{Store: store, ReleasedOf: func(_ context.Context, module string) ([]string, error) {
raw, err := call("seat:"+meshcatalog.Seat+".versions", meshcatalog.VersionsInput{Module: module})
if err != nil {
return nil, err
@@ -189,7 +186,10 @@ func (rv *reservations) TakenOver(ctx context.Context, module, fingerprint strin
return rv.r.TakenOver(ctx, module, fingerprint)
}
func (rv *reservations) Filled() bool { return rv.filled.Load() }
// VersionAt is the version module's artifact is published at from the source revision of branch (H-A-547 (3), H-A-551).
func (rv *reservations) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) {
return rv.r.VersionAt(ctx, module, artifact, branch, source)
}
func (rv *reservations) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) {
return rv.r.Reserve(ctx, module, series, artifacts, src)
@@ -292,16 +292,10 @@ func (rv *reservations) dropBound(ctx context.Context, key string) {
}
}
// heard takes the catalog's version-released and versions-filled in, and a registry seat's published (published): a
// heard takes the catalog's version-released in, and a registry seat's published (published): a
// message that is none of them is left to the others. A state that cannot take one leaves it for the bus to give again.
func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
switch m.Subject() {
case meshcatalog.SubjectVersionsFilled:
rv.filled.Store(true)
rv.logf("the catalog said versions-filled: versions are reserved from now on")
if rv.wake != nil {
rv.wake(ctx)
}
case meshcatalog.SubjectVersionReleased:
var ev meshcatalog.VersionReleasedEvent
if err := json.Unmarshal(m.Data(), &ev); err != nil || ev.Module == "" || ev.Version == "" {
@@ -79,33 +79,23 @@ func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDelete
return nil
}
// TestTheCatalogsWordsMoveTheReservations: design 47 G §369, §372 (test 102) — versions-filled opens the reserving and wakes
// the builds that wait; a built reservation arms its bound and its end raises version-unreleased naming the artifacts
// TestTheCatalogsWordsMoveTheReservations: design 47 G §369 (test 102) — a built reservation arms its bound and its end raises version-unreleased naming the artifacts
// missing; the catalog's version-released deletes the key and the bound and clears the finding; builder_reserved_drop drops one.
func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
ctx := context.Background()
st := &memFindings{vals: map[string][]byte{}}
found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
bounds := &boundsKV{keys: map[string]bool{}}
woke := 0
call := func(addr string, body any) (json.RawMessage, error) {
if addr != "seat:mesh-catalog.versions" {
t.Errorf("the released versions were asked of %q", addr)
}
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m", Versions: []meshcatalog.VersionEntry{{Module: "m", Version: "1.4.2"}}})
}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found,
func(context.Context) { woke++ }, t.Logf)
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, t.Logf)
var items []string // design 47 G A-457a: the end of a build asks its publish, the release ends it
rv.built = func(_ context.Context, m, v string) error { items = append(items, "asked "+m+" "+v); return nil }
rv.released = func(_ context.Context, m, v string) { items = append(items, "ended "+m+" "+v) }
if _, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}); err == nil || rv.Filled() {
t.Fatalf("a version was reserved before versions-filled (%v)", err)
}
filled := &wakeMsg{subject: meshcatalog.SubjectVersionsFilled, data: []byte(`{"v":1}`)}
if !rv.heard(ctx, filled) || !filled.acked || !rv.Filled() || woke != 1 {
t.Fatalf("versions-filled: acked %v, filled %v, woke %d", filled.acked, rv.Filled(), woke)
}
var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
@@ -181,8 +171,7 @@ func TestAReleasedVersionWritesNoTag(t *testing.T) {
fw := &memFindings{vals: map[string][]byte{}}
found := &findings{module: builds.BuilderModule, w: fw, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
store := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
rv := newReservations(store, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf)
rv.filled.Store(true)
rv := newReservations(store, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf)
rv.names = func(_ context.Context, _, artifact string) (string, bool, error) {
return "git.example/o/r/go", artifact == "lib", nil
}
@@ -321,10 +310,9 @@ func TestAPublishedHeardBeforeTheDigestsIsSaidWhenTheBuildRecordsThem(t *testing
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, logf)
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, logf)
var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
rv.filled.Store(true)
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
if err != nil {
t.Fatal(err)
@@ -370,9 +358,7 @@ func TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo(t *testing.T)
call := func(string, any) (json.RawMessage, error) {
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found,
nil, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
rv.filled.Store(true)
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
var withdrawn []string
rv.withdraw = func(module, fp, why string) { withdrawn = append(withdrawn, module+" "+fp+": "+why) }
older, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: "fp-old"})
@@ -499,7 +485,7 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
}
bounds := &boundsKV{keys: map[string]bool{}}
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return bounds },
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, t.Logf)
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, t.Logf)
var said []meshbuilds.PackagePublished
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
var asked, ended []string
@@ -508,7 +494,6 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
rv.itemEnded = rv.released // a build withdrawn or superseded ends its publish item too (§793)
registry := []string{"0.1.37"}
rv.r.HeldNumbers = func(context.Context, string, string, []string) ([]string, error) { return registry, nil }
rv.filled.Store(true)
res, err := rv.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, versions.Source{Fingerprint: "fp1"})
if err != nil || res.Version != "0.1.0" {
t.Fatalf("reserved %q (%v)", res.Version, err)
@@ -594,9 +579,8 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
var logs []string
rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil,
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now},
func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) })
rv.filled.Store(true)
for i := range 14 {
m := fmt.Sprintf("m%02d", i)
res, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "fp" + m})
@@ -689,8 +673,8 @@ func TestEventsAreHandledByAWorkerPerName(t *testing.T) {
if got := eventKey(&wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"module":"m","version":"0.1.0"}`)}); got != "module m" {
t.Errorf("a version-released's key is %q, want its module", got)
}
if got := eventKey(&wakeMsg{subject: takenInSubject, data: []byte(`{}`)}); got != "" {
t.Errorf("a take-in's key is %q, want the shared worker's", got)
if got := eventKey(&wakeMsg{subject: "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", data: []byte(`{}`)}); got != "" {
t.Errorf("an event naming no name has the key %q, want the shared worker's", got)
}
release := make(chan struct{})
handled := make(chan string, 4)
@@ -4,9 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"github.com/nats-io/nats.go/jetstream"
@@ -44,10 +42,9 @@ var seatEvents = map[string]seatEvent{
npmpackageregistry.SubjectKept: {npmpackageregistry.Seat, npmpackageregistry.EventKept},
}
// seatHearer takes the registry seats' outcomes in: each moves a numbered version (versions.Numberer.Heard), and a
// `published` that wakes a name waiting on its floor looks at every module again.
// seatHearer takes the registry seats' outcomes in: the publishes' findings and the reservations hear them (design 47 G §369,
// A-415); the numbering from before G, which marked its state versions with them, is gone (design 47 H §756).
type seatHearer struct {
n *versions.Numberer
b *build.Builder
logf func(string, ...any)
// pub raises and clears the findings of a publish that ended badly; nil raises none.
@@ -79,26 +76,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
if h.pub != nil {
h.pub.read(ctx, se.seat)
}
id := ""
if m.Headers() != nil {
id = m.Headers().Get("x-event-id")
}
wake, err := h.n.Heard(ctx, se.seat, se.event, id, o)
if errors.Is(err, versions.ErrNotNumbered) {
// The version is no entry of the state versions, design 51's numbering by name, which G keeps only until it is removed
// (§372); the reservation numbers a version (§369, §52) and takes the outcome in (A-415). Heard again it would stay
// unnumbered there, so it is taken, not left for the bus.
h.logf("%v in the state versions; the reservations take it (design 47 G §369, A-415)", err)
err = nil
}
if err != nil {
h.logf("%v; heard again (delivery %s)", err, deliveryOf(m))
if nakErr := m.Nak(); nakErr != nil {
h.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
}
givenUp(m, fmt.Sprintf("%s's %s of %s@%s", se.seat, se.event, o.Name, o.Version), err, h.logf)
return true
}
if h.pub != nil {
h.pub.heard(ctx, se.seat, se.event, o)
}
@@ -115,10 +92,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
h.b.PackagePublished(o.Name, o.Version)
}
h.ack(m)
if len(wake) > 0 {
h.logf("the floor of %s is asked again: %s said %s", strings.Join(wake, ", "), se.seat, se.event)
h.b.Reconsider(ctx)
}
return true
}
@@ -150,7 +123,7 @@ func (h *seatHearer) ack(m jetstream.Msg) {
}
}
// kvKeeper is the state floor-waits as versions.FloorKeeper.
// kvKeeper is a state of the builder as a keeper of keys: Put a key's value, Delete its key.
type kvKeeper struct {
ctx context.Context
kv jetstream.KeyValue
@@ -168,27 +141,3 @@ func (k kvKeeper) Delete(key string) error {
}
return err
}
// heldFloorWaits are the waits floor-waits holds at the builder's start; a value that is no wait is said and left.
func heldFloorWaits(ctx context.Context, kv jetstream.KeyValue, logf func(string, ...any)) []versions.FloorWait {
l, err := kv.ListKeys(ctx)
if err != nil {
logf("%s cannot be listed, so a restart's waits are asked at their next claim: %v", versions.FloorWaitsState, err)
return nil
}
defer func() { _ = l.Stop() }()
var out []versions.FloorWait
for k := range l.Keys() {
e, err := kv.Get(ctx, k)
if err != nil {
continue
}
w, err := versions.DecodeFloorWait(e.Value())
if err != nil {
logf("%s.%s holds what is no floor wait, left: %v", versions.FloorWaitsState, k, err)
continue
}
out = append(out, w)
}
return out
}
@@ -0,0 +1,50 @@
{
"module": "disk-load",
"version": "0.1",
"class": "leaf",
"tools": [
"disk_load",
"disk_top",
"disk_filesystems",
"disk_folders",
"disk_devices",
"cpu_top",
"disk_readings",
"disk_round",
"disk_measure"
],
"build": {
"artifacts": [
{
"name": "tools-go",
"kind": "bundle",
"language": "go",
"system": "arch",
"from": "cmd/disk-load",
"binary": "disk-load",
"loads": [
"disk-load"
]
},
{
"name": "diskreadings",
"kind": "package",
"language": "go",
"paths": [
"diskreadings"
],
"series": "0.1"
}
]
},
"state": [
"readings",
{
"name": "rounds",
"per-machine": true
}
],
"reads": [
"mesh-host.data"
]
}
@@ -4,43 +4,31 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-builder/internal/build"
"mesh-delivery-builder/internal/versions"
)
// awaitedVersions is the state versions as versions.Store: bound once the bus holds it (the grants part makes it, issue
// 1790); until then every use is an error, so a trunk build is built unnumbered and said (build.Builder.number).
type awaitedVersions struct {
b *process.AwaitedBucket
// bucket names the state in the error of one not on the bus yet; empty is the versions'.
// awaitedState is one of the builder's states as versions.Store: bound once the bus holds it (the grants part makes it,
// issue 1790); until then every use is an error naming the state's bucket.
type awaitedState struct {
b *process.AwaitedBucket
bucket string
}
var errVersionsMissing = errors.New("the state " + versions.State + " is not on the bus yet")
func (s awaitedVersions) kv() (jetstream.KeyValue, error) {
func (s awaitedState) kv() (jetstream.KeyValue, error) {
if kv := s.b.KV(); kv != nil {
return kv, nil
}
if s.bucket != "" {
return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
}
return nil, errVersionsMissing
return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
}
func (s awaitedVersions) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
func (s awaitedState) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
kv, err := s.kv()
if err != nil {
return nil, 0, false, err
@@ -62,7 +50,7 @@ func versionsConflict(err error) error {
return err
}
func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (uint64, error) {
func (s awaitedState) Create(ctx context.Context, key string, value []byte) (uint64, error) {
kv, err := s.kv()
if err != nil {
return 0, err
@@ -71,7 +59,7 @@ func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (
return rev, versionsConflict(err)
}
func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
func (s awaitedState) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
kv, err := s.kv()
if err != nil {
return 0, err
@@ -80,7 +68,7 @@ func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, r
return rev, versionsConflict(err)
}
func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, error) {
func (s awaitedState) KeysOf(ctx context.Context, filter string) ([]string, error) {
kv, err := s.kv()
if err != nil {
return nil, err
@@ -97,92 +85,6 @@ func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, e
return out, nil
}
// publishedVersionsVia asks the Go package registry seat's verb versions for one package path (design 47 H H-A-194): its
// versions, newest first.
func publishedVersionsVia(call toolCaller) func(context.Context, string) ([]string, error) {
return func(_ context.Context, path string) ([]string, error) {
raw, err := call("seat:"+gopackageregistry.Seat+"."+gopackageregistry.VerbVersions, gopackageregistry.VersionsInput{Name: path})
if err != nil {
return nil, err
}
var a gopackageregistry.VersionsAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", gopackageregistry.Seat, err)
}
var out []string
for _, v := range a.Versions {
if v.Version != "" {
out = append(out, v.Version)
}
}
return out, nil
}
}
// floorVia is the floor's three sources as calls of the builder's own account (design 51 *The floor*): the seat's verb
// versions, the seat git's tags and the requirements the catalog half's entries name (A-119). A call that fails is that source
// silent.
func floorVia(call toolCaller, requirements func(context.Context, string) ([]string, error)) versions.FloorSources {
return versions.FloorSources{
Seat: func(_ context.Context, seat, name string) ([]string, error) {
raw, err := call("seat:"+seat+".versions", map[string]any{"name": name})
if err != nil {
return nil, err
}
var a struct {
Versions []struct {
Version string `json:"version"`
} `json:"versions"`
}
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", seat, err)
}
var out []string
for _, v := range a.Versions {
if v.Version != "" {
out = append(out, v.Version)
}
}
return out, nil
},
Tags: func(ctx context.Context, repository, prefix string) ([]string, error) {
tags, _, err := tagsVia(call)(ctx, repository, prefix)
out := make([]string, 0, len(tags))
for _, t := range tags {
out = append(out, t.Tag)
}
return out, err
},
Requirements: requirements,
}
}
// tagsVia reads a repository's tags starting with prefix, each with the commit it names, through the seat git's verb tags,
// whichever module holds the seat (design 47 G §7, A-82), page by page; its answer is read tolerantly, form 2 naming each tag's
// commit (design 47 H2 §796, §780). away says the read met a transport fault or the error kind away (§776).
func tagsVia(call toolCaller) func(ctx context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
return func(_ context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
var out []gitseat.Tag
for page := int64(1); ; page++ {
raw, err := call("seat:"+gitseat.Seat+"."+gitseat.VerbTags, gitseat.TagsInput{Repository: repository, Prefix: prefix, Page: page})
if err != nil {
return nil, true, err
}
a, _, err := gitseat.DecodeTagsAnswer(raw)
if err != nil {
return nil, false, fmt.Errorf("the seat git's tags answered what is no list of tags: %w", err)
}
if a.Error != "" {
return nil, a.ErrorKind == gitseat.ErrorKindAway, fmt.Errorf("the seat git's tags: %s (%s)", a.Error, a.ErrorKind)
}
out = append(out, a.Tags...)
if !a.More {
return out, false, nil
}
}
}
}
// emitEvent says one of the builder's events, mesh.mod.<module>.event.<event>, with the SDK's envelope headers and id as
// the bus's dedup id.
func emitEvent(ctx context.Context, js jetstream.JetStream, cred process.Account, event, id string, body any) error {
@@ -221,65 +123,3 @@ func emitSeatEvent(ctx context.Context, js jetstream.JetStream, cred process.Acc
_, err = js.PublishMsg(pub, msg, jetstream.WithMsgID(id))
return err
}
// The events on the builder's consumer of EVENTS that wake a floor (design 51 *The floor*, DLV-B3b).
var (
// The indexer's take-in.taken, which the builder consumes in place of the retired manifest-accepted (design 47 H H-A-116).
takenInSubject = "mesh.mod.mesh-delivery-indexer.event.take-in.taken"
conditionClearedSubject = meshconditions.SubjectConditionCleared
)
// floorWake asks the floor of the names an event wakes again, by looking at every module again: a trunk build is
// numbered before its claim (build.Builder.number).
type floorWake struct {
b *build.Builder
waits *versions.FloorWaits
logf func(string, ...any)
}
// heard takes a message of the consumer in when it is one that wakes a floor, acknowledged, and answers whether it was.
func (f *floorWake) heard(ctx context.Context, m jetstream.Msg) bool {
switch m.Subject() {
case takenInSubject:
f.ack(m)
f.wake(ctx, versions.WakeTakenIn, "", "")
case conditionClearedSubject:
f.ack(m)
var e meshconditions.ConditionEvent
if err := json.Unmarshal(m.Data(), &e); err != nil {
f.logf("%s holds what is no condition, left: %v", m.Subject(), err)
return true
}
if e.Subject == nil {
return true
}
for _, module := range conditionModules(e.Subject.ID) {
f.wake(ctx, versions.WakeCleared, "", module)
}
default:
return false
}
return true
}
func (f *floorWake) ack(m jetstream.Msg) {
if err := m.Ack(); err != nil {
f.logf("acknowledging %s: %v", m.Subject(), err)
}
}
// wake looks at every module again when the event wakes a name, and says which.
func (f *floorWake) wake(ctx context.Context, kind, seat, module string) {
names := f.waits.Wake(kind, seat, module, "")
if len(names) == 0 {
return
}
f.logf("the floor of %s is asked again: %s", strings.Join(names, ", "), kind)
f.b.Reconsider(ctx)
}
// conditionModules are the tokens of a condition's subject id (`<node>/<module>`, `<module>.<check>`): a module named
// among them is the one whose condition cleared.
func conditionModules(id string) []string {
return strings.FieldsFunc(id, func(r rune) bool { return r == '/' || r == '.' || r == ':' })
}
@@ -23,11 +23,6 @@ func TestAnEntryOfTheCatalogHalfIsTheFormTheBuilderBuildsBy(t *testing.T) {
!reflect.DeepEqual(got.Inputs2.Paths, map[string]string{"a/b": "lib", "c": "lib"}) {
t.Errorf("ModuleOf = %+v", got)
}
// A module value carries no source stamp (design 47 H H-A-48): its claim is numbered per fingerprint, naming no source
// revision and no merge.
if c := ClaimOf("netcheck", got, Plan{}); c.Revision != "" || c.Merge != 0 || c.Fingerprint != "src2:f" {
t.Errorf("ClaimOf = %+v", c)
}
if bare := ModuleOf(meshcatalog.CatalogEntry{Module: "m"}); bare.Inputs2 != nil || bare.Fp2 != "" {
t.Errorf("ModuleOf of an entry with none = %+v, want nothing set", bare)
}
@@ -10,9 +10,9 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
)
// ADR 0593 §2 (F3): the imports a Go build module answers at a build's end reach the done key and the log's end entry,
// where the indexer keeps them on the module.
func importsABuildAnswersReachTheDoneKeyAndTheLog(t *testing.T) {
// B2/AC1 (design 47 H2 H-A-517, H-A-532 DQ-7): the imports a Go build module answers at a build's end reach neither the done
// key nor the log's end entry; the build module says them as imports-reported, its own build seat's event.
func importsABuildAnswersReachNeitherTheDoneKeyNorTheLog(t *testing.T) {
r := newRig(t, goBundle)
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/announce"}
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -24,15 +24,32 @@ func importsABuildAnswersReachTheDoneKeyAndTheLog(t *testing.T) {
}
return step
}
var logged []builds.BuildLogEntry
var logged [][]byte
var mu sync.Mutex
r.b.Node, r.b.Log = "novox", func(e builds.BuildLogEntry) { mu.Lock(); logged = append(logged, e); mu.Unlock() }
v := r.consider(t, "modules/m")
if v.State != builds.BuildDone || strings.Join(v.Imports, ",") != strings.Join(imports, ",") {
t.Fatalf("done key %+v, want the imports", v)
r.b.Node, r.b.Log = "novox", func(e builds.BuildLogEntry) {
raw, err := builds.EncodeBuildLogEntry(e)
if err != nil {
t.Errorf("a log entry does not encode: %v", err)
}
mu.Lock()
logged = append(logged, raw)
mu.Unlock()
}
if len(logged) != 2 || strings.Join(logged[1].Imports, ",") != strings.Join(imports, ",") || len(logged[0].Imports) != 0 {
t.Fatalf("log %+v, want the imports on the end alone", logged)
if v := r.consider(t, "modules/m"); v.State != builds.BuildDone {
t.Fatalf("done key %+v, want it done", v)
}
if raw := string(r.st.vals[r.key]); strings.Contains(raw, `"imports"`) || strings.Contains(raw, "announce") {
t.Errorf("the done key %s carries the imports", raw)
}
mu.Lock()
defer mu.Unlock()
if len(logged) != 2 {
t.Fatalf("log %d entries, want the start and the end", len(logged))
}
for _, raw := range logged {
if strings.Contains(string(raw), `"imports"`) || strings.Contains(string(raw), "announce") {
t.Errorf("a log entry %s carries the imports", raw)
}
}
}
@@ -11,93 +11,10 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"mesh-delivery-builder/internal/versions"
)
// Numbers numbers a trunk build at its claim (novox/hq design 51 *The versions*, ADR 0606, ADR 0617 §1) and records the
// digests it was built with. Nil numbers nothing.
type Numbers interface {
// done is the digests of the build's key when it is done already (versions.BuildClaim.Done), nil otherwise.
Number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, done map[string]string) (versions.Numbering, error)
Built(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, got versions.Numbering, made []builds.BuiltArtifact) error
}
// VersionNumbers is Numbers over the builder's state versions.
type VersionNumbers struct {
N *versions.Numberer
}
// ClaimOf is the claim a module value's trunk build is numbered by, per fingerprint: a module value carries no source stamp
// (design 47 H H-A-48), so the claim names no source revision and no merge.
func ClaimOf(module string, m meshcatalog.ModulesByModuleValue, plan Plan) versions.BuildClaim {
c := versions.BuildClaim{Module: module, Path: m.Path, Repository: trunk.RepositoryName(m.Repository), Fingerprint: m.Fp2,
Commit: m.Commit}
for _, t := range plan.Tasks {
c.Artifacts = append(c.Artifacts, versions.ClaimArtifact{Artifact: t.Artifact, Kind: t.Kind, Language: t.Language})
}
return c
}
func (v VersionNumbers) Number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, done map[string]string) (versions.Numbering, error) {
c := ClaimOf(module, m, plan)
c.Done = done
return v.N.Number(ctx, c)
}
func (v VersionNumbers) Built(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, got versions.Numbering, made []builds.BuiltArtifact) error {
digests := map[string]string{}
for _, a := range made {
digests[a.Name] = a.Digest
}
return v.N.Built(ctx, ClaimOf(module, m, plan), got, digests)
}
// number numbers a trunk build's artifacts before its claim: false
// when it waits for its floor (a package, design 51 *The floor*), and then nothing is claimed; the floor's wake looks at
// the module again.
func (b *Builder) number(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan) (versions.Numbering, bool) {
if b.Numbers == nil {
return versions.Numbering{}, true
}
done := b.doneDigests(ctx, module, m.Fp2)
got, err := b.Numbers.Number(ctx, module, m, plan, done)
for _, s := range got.Said {
b.logf("%s at %s: %s", module, m.Fp2, s.Line)
// And in the build log (design 51 *The versions*: it says a version was kept, and why), between the build's start and end.
// A look at a key already done builds nothing and has no start or end: a version kept there says nothing new, and is
// not logged (each later look, a first view answered or a name heard, would add one).
if b.Log != nil && !(done != nil && s.Why == versions.SaidKept) {
b.Log(builds.BuildLogEntry{Event: builds.BuildSaidEvent, Module: module, FP: m.Fp2, Commit: m.Commit, Node: b.Node,
At: time.Now().UTC(), Line: s.Line, Why: s.Why})
}
}
if err != nil {
// Said, and built as before: an unnumbered build is published by its digest (ADR 0617 §1), numbered at its next look.
b.logf("%s at %s: %v", module, m.Fp2, fmt.Errorf("not numbered, the versions cannot be used: %w", err))
return versions.Numbering{}, true
}
if done != nil && len(got.Versions) > 0 && b.Reserved != nil {
// A late look numbered a done build: G §349 retires numbering at a look, so one with no reservation and no release is
// said aloud with the recovery that reserves it (A-455), never taken in silently.
_, reserved, rerr := b.Reserved.ReservedFor(ctx, module, m.Fp2)
released, derr := b.Reserved.ReleasedFor(ctx, module, m.Fp2)
if rerr == nil && derr == nil && !reserved && !released {
b.logf("%s at %s: a late look numbered this done build (%v) and no version is reserved for it: builder_reserve_done reserves one and queues its publish", module, m.Fp2, got.Versions)
}
}
if got.Refused != "" {
b.logf("%s at %s: %s", module, m.Fp2, got.Refused)
return got, true
}
if got.Wait != "" {
b.logf("%s at %s is not built yet: %s", module, m.Fp2, got.Wait)
return got, false
}
return got, true
}
// doneDigests are the digests of a trunk build's key by artifact when the key is done, nil otherwise or when it cannot be
// read: a look at a done build numbers what it left unnumbered with them (versions.BuildClaim.Done).
func (b *Builder) doneDigests(ctx context.Context, module, fp string) map[string]string {
@@ -181,9 +98,8 @@ func (b *Builder) RecordAgain(ctx context.Context, module, fp, when string) (str
return res.Version, nil
}
// PackageNamed looks at a module again when the indexer's packages state names a name for one of its packages
// (versions.NamedModule): a done trunk build that left the package unnumbered, its name not known at its claim, is
// numbered then with the done build's digests, and version.numbered says them for its build module's late publish.
// PackageNamed looks at a module again when the catalog half's entry of it names a package's name in its ecosystem
// (design 47 G §348): a done build is looked at and nothing is built again.
func (b *Builder) PackageNamed(ctx context.Context, module string) {
b.init()
b.mu.Lock()
@@ -197,8 +113,6 @@ func (b *Builder) PackageNamed(ctx context.Context, module string) {
// Reservations reserves the version of a trunk build at its start and records each artifact's digest (design 47 G §369).
// Nil reserves nothing.
type Reservations interface {
// Filled says the catalog said versions-filled: nothing is reserved before it.
Filled() bool
// Reserve reserves module's next version in series for the artifacts (their references, <module>:<artifact>).
Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error)
// Built records the digests of the artifacts built under the reserved version, by reference, and what each resolved and was
@@ -211,6 +125,9 @@ type Reservations interface {
// TakenOver is the reservation of module's series that took the series over from the build of fingerprint, whose number
// it keeps withdrawn (design 47 H H-A-226), and whether one does (H-A-244).
TakenOver(ctx context.Context, module, fingerprint string) (versions.ReservedVersion, bool, error)
// VersionAt is the version module's artifact is published at from the source revision of branch: its reservation of that
// origin with the artifact published, else its release recorded at that source revision (design 47 H2 H-A-547 (3), H-A-551).
VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error)
}
// reserves says whether a look at a trunk build is one that reserves: the build has a series of the form MAJOR.MINOR
@@ -232,23 +149,6 @@ func (b *Builder) reservesVersion(plan Plan) bool {
return len(plan.Tasks) > 0 && strings.Count(plan.Series, ".") == 1
}
// waitFill holds a build that would reserve until the catalog says versions-filled, saying wait-held naming the fill once
// (design 47 G §369, §372). It answers whether the build waits.
func (b *Builder) waitFill(module string, m meshcatalog.ModulesByModuleValue) bool {
if b.Reserved.Filled() {
return false
}
if _, said := b.fillWaits.LoadOrStore(module+"."+m.Fp2, true); !said {
line := module + " at " + m.Fp2 + " is not built yet: wait-held, the catalog has not said versions-filled, and nothing is reserved before it"
b.logf("%s", line)
if b.Log != nil {
b.Log(builds.BuildLogEntry{Event: builds.BuildSaidEvent, Module: module, FP: m.Fp2, Commit: m.Commit, Node: b.Node,
At: time.Now().UTC(), Line: line, Why: "wait-held"})
}
}
return true
}
// reserve reserves the version of the build that starts; a reservation that cannot be made is said and the build goes on
// unreserved: the caller fails the key, which a look takes again (A-490).
func (b *Builder) reserve(ctx context.Context, module string, m meshcatalog.ModulesByModuleValue, plan Plan, o Origin, rebuild bool) (versions.ReservedVersion, bool) {
@@ -317,9 +217,6 @@ func (b *Builder) ReserveDone(ctx context.Context, module, fp string) (versions.
} else if ok {
return versions.ReservedVersion{}, fmt.Errorf("%s at %s holds the reservation of %s already", module, fp, cur.Version)
}
if !b.Reserved.Filled() {
return versions.ReservedVersion{}, versions.ErrNotFilled
}
res, ok := b.reserve(ctx, module, m, plan, b.originOf(key), false)
if !ok {
return versions.ReservedVersion{}, fmt.Errorf("no version could be reserved for %s at %s (the builder's journal says why)", module, fp)
@@ -8,6 +8,7 @@ import (
"reflect"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -22,7 +23,6 @@ import (
// fakeReservations answers a fill and keeps what the builder reserved and recorded.
type fakeReservations struct {
filled bool
released map[string]bool
reserved [][]string
series []string
@@ -34,6 +34,25 @@ type fakeReservations struct {
tookBy map[string]versions.ReservedVersion // by fingerprint, the reservation that took its series over (H-A-244)
held map[string]versions.ReservedVersion // by fingerprint, the reservation ReservedFor answers as it stands (H-A-492)
lost error // the record of the digests fails, as a store refusing it would
atMu sync.Mutex
at map[string]string // by "<module>:<artifact>@<branch>.<source>", the version VersionAt answers (H-A-547 (3))
}
func (f *fakeReservations) VersionAt(_ context.Context, module, artifact, branch string, source int64) (string, bool, error) {
f.atMu.Lock()
defer f.atMu.Unlock()
v, ok := f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)]
return v, ok, nil
}
// publishAt makes VersionAt answer version for module's artifact at the origin branch and source.
func (f *fakeReservations) publishAt(module, artifact, branch string, source int64, version string) {
f.atMu.Lock()
defer f.atMu.Unlock()
if f.at == nil {
f.at = map[string]string{}
}
f.at[fmt.Sprintf("%s:%s@%s.%d", module, artifact, branch, source)] = version
}
func (f *fakeReservations) TakenOver(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) {
@@ -45,8 +64,6 @@ func (f *fakeReservations) ReleasedFor(_ context.Context, _, fp string) (bool, e
return f.released[fp], nil
}
func (f *fakeReservations) Filled() bool { return f.filled }
func (f *fakeReservations) ReservedFor(_ context.Context, _, fp string) (versions.ReservedVersion, bool, error) {
if v, ok := f.held[fp]; ok {
return v, true, nil
@@ -85,8 +102,8 @@ func (f *fakeReservations) Built(ctx context.Context, _, version string, digests
return nil
}
// TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled: design 47 G §369, §372 (test 102) — nothing is reserved before
// versions-filled and the build waits saying wait-held naming the fill; after it the build reserves one version in the
// TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled: design 47 G §369 (test 102), H2 H-A-552 — the build waits for no
// fill and says no wait-held: it reserves one version in the
// manifest's MAJOR.MINOR for its artifacts and records their digests; a done key reserves nothing again; a manifest whose
// version is no MAJOR.MINOR reserves nothing.
func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
@@ -97,22 +114,6 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
var said []builds.BuildLogEntry
r.b.Log = func(e builds.BuildLogEntry) { said = append(said, e) }
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
if _, ok := r.st.vals[r.key]; ok || len(res.reserved) != 0 {
t.Fatalf("before versions-filled the build was claimed (%v) or reserved %v", ok, res.reserved)
}
var waits []string
for _, e := range said {
if e.Event == builds.BuildSaidEvent && e.Why == "wait-held" {
waits = append(waits, e.Line)
}
}
if len(waits) != 1 || !slices.ContainsFunc(waits, func(l string) bool { return strings.Contains(l, "versions-filled") }) {
t.Fatalf("wait-held lines = %q, want one naming versions-filled", waits)
}
res.filled = true
// Design 47 G §573: the build's ask carries the reserved version.
var askedVersions []string
r.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -126,11 +127,16 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
if v.State != builds.BuildDone || len(res.reserved) != 1 || !slices.Equal(res.reserved[0], []string{"m:tool"}) || res.series[0] != "0.1" {
t.Fatalf("build %+v reserved %v in %v, want done and one reservation of m:tool in 0.1", v.State, res.reserved, res.series)
}
for _, e := range said {
if e.Event == builds.BuildSaidEvent && e.Why == "wait-held" {
t.Errorf("the build said wait-held %q, want no wait for a fill (H-A-552)", e.Line)
}
}
if res.built["m:tool"] != digest || len(res.built) != 2 {
t.Errorf("recorded %v, want the digest of m:tool under the reserved version", res.built)
}
// H-A-486: an upstream artifact is reserved for the record and named as upstream, so its publish is never awaited.
up := &fakeReservations{filled: true}
up := &fakeReservations{}
plan := Plan{Series: "0.1", Tasks: []Task{{Artifact: "server", Kind: catalogue.ArtifactUpstream}, {Artifact: "tools", Kind: catalogue.ArtifactBundle}}}
if _, ok := (&Builder{Reserved: up}).reserve(context.Background(), "nats", meshcatalog.ModulesByModuleValue{Fp2: "f"}, plan, Origin{}, false); !ok ||
!slices.Equal(up.reserved[0], []string{"nats:server", "nats:tools"}) || !slices.Equal(up.sources[0].Upstream, []string{"nats:server"}) {
@@ -143,7 +149,7 @@ func TestABuildReservesItsVersionAtItsStartOnceTheCatalogFilled(t *testing.T) {
// A manifest whose version is no MAJOR.MINOR reserves nothing and is built as before.
r2 := newRig(t, goBundle)
res2 := &fakeReservations{filled: true}
res2 := &fakeReservations{}
r2.b.Reserved = res2
var unversioned []string
r2.asks.Answer = func(a buildstep.StepAsk) buildstep.Step {
@@ -172,7 +178,7 @@ func TestAVersionsDigestsAreRecordedUnderTheBuildersOwnBound(t *testing.T) {
t.Run("a build's context cancelled at its end still records", func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = manifest
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -220,7 +226,7 @@ func TestAVersionsDigestsAreRecordedUnderTheBuildersOwnBound(t *testing.T) {
t.Run("a done key whose digests are not recorded is recorded at the next look", func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = manifest
res := &fakeReservations{filled: true, lost: errors.New("context canceled")}
res := &fakeReservations{lost: errors.New("context canceled")}
r.b.Reserved = res
var journal []string
r.b.Logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
@@ -289,7 +295,7 @@ func TestOnlyABuildOfTheFirstWatchedBranchReservesAndItCarriesItsCatalogRevision
t.Run(c.name, func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
r.b.Entry(context.Background(), c.origin, meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m",
Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1, ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}})
@@ -310,7 +316,7 @@ func TestOnlyABuildOfTheFirstWatchedBranchReservesAndItCarriesItsCatalogRevision
func TestAReservedBuildKeepsWhatItsStepResolvedAndWasBuiltWith(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
var journal []string
r.b.Logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
@@ -358,7 +364,7 @@ func TestAModuleWhoseOnlyArtifactIsAGoPackageIsBuiltUnderItsReservedVersion(t *t
t.Run(c.name, func(t *testing.T) {
r := newRig(t, goPackage)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.series, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goPackage}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
r.bm.packages["go-overlay"] = "git.novox.be/novox/mesh-networking/go@v0.1.5" // the Go build module's published reference
var asked []buildstep.StepAsk
@@ -390,7 +396,7 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) {
return r
}
t.Run("a reservation that cannot be made fails the key and asks nothing", func(t *testing.T) {
r := setup(t, &fakeReservations{filled: true, fail: errors.New("the catalog's versions cannot be read")})
r := setup(t, &fakeReservations{fail: errors.New("the catalog's versions cannot be read")})
v := r.consider(t, "modules/m")
if v.State != builds.BuildFailed || !strings.Contains(v.Error, "no version is reserved") || len(r.asks.Asks()) != 0 {
t.Fatalf("key %+v with %d asks; want failed saying no version is reserved, nothing asked", v, len(r.asks.Asks()))
@@ -412,7 +418,7 @@ func TestAReservingTrunkBuildNeverEndsDoneWithoutItsVersion(t *testing.T) {
if v := r.consider(t, "modules/m"); v.State != builds.BuildDone {
t.Fatalf("first build = %+v, want done", v)
}
res := &fakeReservations{filled: true, released: map[string]bool{fp1: c.released}}
res := &fakeReservations{released: map[string]bool{fp1: c.released}}
if c.standing {
res.sources, res.next = []versions.Source{{Fingerprint: fp1}}, "0.1.17" // ReservedFor answers a held reservation
}
@@ -446,7 +452,6 @@ type realReserve struct {
reservations map[string][]byte
}
func (r *realReserve) Filled() bool { return true }
func (r *realReserve) ReleasedFor(context.Context, string, string) (bool, error) {
return false, nil
}
@@ -491,7 +496,7 @@ func TestABuildAgainKeepsItsOwnStandingNumber(t *testing.T) {
t.Fatalf("first build = %+v, want done", v)
}
store := reserveMap{newMem()}
real := &realReserve{Reserver: &versions.Reserver{Store: store, Filled: func() bool { return true },
real := &realReserve{Reserver: &versions.Reserver{Store: store,
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }}}
raw, _ := json.Marshal(versions.ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: "0.1.30", Fingerprint: fp1, Artifacts: map[string]string{"m:tool": "d"}})
if _, err := store.Create(context.Background(), versions.ReservedKey("m", "0.1"), raw); err != nil {
@@ -19,7 +19,7 @@ func TestADoneTrunkBuildThatReservedNoneIsGivenAVersionByHand(t *testing.T) {
ctx := context.Background()
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
if _, err := r.b.ReserveDone(ctx, "m", fp1); err == nil {
t.Fatal("a version was reserved for a key that is not built")
@@ -5,7 +5,6 @@ import (
"fmt"
"maps"
"slices"
"strconv"
"strings"
"time"
@@ -190,14 +189,13 @@ func (b *Builder) awaitRevision(ctx context.Context, run meshbuilds.StepRun) (ou
}
}
// **A package with no pin waits for its publish** (design 47 H H-A-192, H-A-165, H-A-183, H-A-184, H-A-185): an entry
// keeps a mesh package the registry has not published within the series its module accepts with an empty version. Its
// build, a step ask's or a lane's, first reads the versions the registry seat holds of the path (its verb versions,
// H-A-194), then waits for the registry seat's published of that package path in that series (the
// series the module's manifest names in `packages`, else the default; catalogue.Manifest.AcceptedSeries), up to
// PackageWait (the setting package-wait-minutes), and pins the version that event carries; the builder never derives a
// pin (no release number of the module that holds the package). Past the bound the build fails, naming the package, and
// nothing is built.
// **A package with no pin is built against its publisher's version at the key's origin** (design 47 H2 H-A-521, H-A-547 (3),
// H-A-551; H-A-165): an entry names a mesh package with no version when a mover of the same take-in publishes it (DMC-1). Its
// build, a step ask's or a lane's, fills that version from the reservation of the module that publishes it (Members) at the
// source revision of the build key's own origin, once that reservation's artifact is published, and else from that module's
// release recorded at that source revision; never from the newest a registry seat said published. It waits for one, woken by
// each registry seat's published heard (PackagePublished), up to PackageWait (the setting package-wait-minutes). Past the bound
// the build fails, naming the package, and nothing is built.
// DefaultPackageWait is the bound of a build's wait for a package's publish, its setting package-wait-minutes' default.
const DefaultPackageWait = 10 * time.Minute
@@ -209,44 +207,46 @@ func (b *Builder) packageWait() time.Duration {
return DefaultPackageWait
}
// PackagePublished takes the Go package registry seat's published of one package path in (its name and the version the
// event carries, H-A-192): the newest published in the version's series is kept, and a build waiting for the package
// wakes. A version that is no MAJOR.MINOR.PATCH (a group's tagged version) pins nothing.
func (b *Builder) PackagePublished(path, version string) {
v := strings.TrimPrefix(version, "v")
series, ok := seriesOfVersion(v)
if path == "" || !ok {
// PackagePublished is told each registry seat's published of a package (its name and the version the event carries): a build
// waiting for a package's version looks again at the reservations, which the published marked before it is told.
func (b *Builder) PackagePublished(name, version string) {
if name == "" {
return
}
b.init()
b.mu.Lock()
in := b.publishedPins[path]
if in == nil {
in = map[string]string{}
b.publishedPins[path] = in
}
if old := in[series]; old == "" || compareVersions(v, old) > 0 {
in[series] = v
}
b.mu.Unlock()
b.pictureMoved()
}
// publishedPin is the pin the registry seat's published gave the package path in the series, as Go names it; "" for none.
func (b *Builder) publishedPin(path, series string) string {
b.mu.Lock()
v := b.publishedPins[path][series]
b.mu.Unlock()
if v == "" {
return ""
// versionAtOrigin is the version, as Go names it, the module that publishes the package holds at the source revision of the
// key's origin (H-A-547 (3), H-A-551), and words saying why there is none.
func (b *Builder) versionAtOrigin(ctx context.Context, key, pkg string) (version, none string) {
if b.Members == nil || b.Reserved == nil {
return "", "no module that publishes it can be read"
}
return "v" + v
module, artifact, found, err := b.Members(ctx, pkg)
if err != nil || !found {
if err != nil {
return "", fmt.Sprintf("the module that publishes it cannot be read: %v", err)
}
return "", "no entry names the module that publishes it"
}
b.mu.Lock()
o := b.origin[key]
b.mu.Unlock()
v, found, err := b.Reserved.VersionAt(ctx, module, artifact, o.Branch, o.Source)
if err != nil {
return "", fmt.Sprintf("the version %s holds at source revision %d cannot be read: %v", module, o.Source, err)
}
if !found {
return "", fmt.Sprintf("%s publishes no version of it at source revision %d of %s", module, o.Source, o.Branch)
}
return "v" + strings.TrimPrefix(v, "v"), ""
}
// awaitPublished fills each package of packages with no pin from the published of its path within the series the manifest
// with this digest accepts, waiting for one (H-A-192, H-A-165). It answers the packages with every pin, or an outcome and
// its words: failed past the bound naming the package, could not run when the manifest cannot be read or the builder stops.
func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string, packages map[string]string) (map[string]string, string, string) {
// awaitPublished fills each package of packages with no pin from the version its publisher holds at the key's origin
// (versionAtOrigin), waiting for one (H-A-521, H-A-165). It answers the packages with every pin, or an outcome and its words:
// failed past the bound naming the package, could not run when the builder stops.
func (b *Builder) awaitPublished(ctx context.Context, module, fp string, packages map[string]string) (map[string]string, string, string) {
var unpinned []string
for p, v := range packages {
if v == "" {
@@ -257,26 +257,9 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
return packages, "", ""
}
slices.Sort(unpinned)
if b.Manifests == nil {
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the series %s accepts of %s cannot be read: no manifests", module, unpinned[0])
}
man, err := b.Manifests.Manifest(ctx, digest)
key, err := builds.BuilderBuildKey(module, fp)
if err != nil {
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the series %s accepts of %s cannot be read: its manifest %s: %v", module, unpinned[0], digest, err)
}
// What the registry seat holds is read once before the wait (H-A-194): the publishes heard are a cache of it.
for _, p := range unpinned {
if b.PublishedVersions == nil || b.publishedPin(p, man.AcceptedSeries(p)) != "" {
continue
}
vs, err := b.PublishedVersions(ctx, p)
if err != nil {
b.logf("%s at %s: the versions the registry seat holds of %s cannot be read, so the build waits for its publish: %v", module, fp, p, err)
continue
}
for _, v := range vs {
b.PackagePublished(p, v)
}
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, err.Error()
}
bound := b.packageWait()
wait, stop := context.WithTimeout(ctx, bound) // a context's bound, no timer (ADR 0437 §8)
@@ -287,12 +270,12 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
moved := b.moved
b.mu.Unlock()
pins := map[string]string{}
missing, missingSeries := "", ""
missing, why := "", ""
for _, p := range unpinned {
series := man.AcceptedSeries(p)
pins[p] = b.publishedPin(p, series)
if pins[p] == "" && missing == "" {
missing, missingSeries = p, series
v, none := b.versionAtOrigin(wait, key, p)
pins[p] = v
if v == "" && missing == "" {
missing, why = p, none
}
}
if missing == "" {
@@ -303,58 +286,19 @@ func (b *Builder) awaitPublished(ctx context.Context, module, fp, digest string,
}
return out, "", ""
}
notReleased := fmt.Sprintf("package %s has no released version in the series %s", missing, missingSeries)
notPublished := fmt.Sprintf("package %s has no published version: %s", missing, why)
if !told {
b.logf("%s at %s: %s yet: the build waits for its publish, at most %s", module, fp, notReleased, bound)
b.logf("%s at %s: %s yet: the build waits for its publish, at most %s", module, fp, notPublished, bound)
told = true
}
select {
case <-moved:
case <-wait.Done():
if ctx.Err() != nil {
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, notReleased + ": the builder stopped before it was"
return nil, meshbuilds.StepEndedOutcomeCouldNotRun, notPublished + ": the builder stopped before it was"
}
b.logf("%s at %s: %s within %s: the build fails, nothing is built", module, fp, notReleased, bound)
return nil, meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notReleased, bound)
b.logf("%s at %s: %s within %s: the build fails, nothing is built", module, fp, notPublished, bound)
return nil, meshbuilds.StepEndedOutcomeFailed, fmt.Sprintf("%s within %s", notPublished, bound)
}
}
}
// seriesOfVersion is a MAJOR.MINOR.PATCH version's series, MAJOR.MINOR; false for any other form.
func seriesOfVersion(v string) (string, bool) {
if _, ok := versionParts(v); !ok {
return "", false
}
major, rest, _ := strings.Cut(v, ".")
minor, _, _ := strings.Cut(rest, ".")
return major + "." + minor, true
}
// versionParts are a MAJOR.MINOR.PATCH version's numbers; false for any other form.
func versionParts(v string) ([3]int, bool) {
var out [3]int
parts := strings.Split(v, ".")
if len(parts) != 3 {
return out, false
}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 {
return out, false
}
out[i] = n
}
return out, true
}
// compareVersions orders two MAJOR.MINOR.PATCH versions numerically.
func compareVersions(a, b string) int {
x, _ := versionParts(a)
y, _ := versionParts(b)
for i := range x {
if x[i] != y[i] {
return x[i] - y[i]
}
}
return 0
}
@@ -104,9 +104,6 @@ type Builder struct {
// time.Now. Node is the node the builder runs on, which asked the build.
Now func() time.Time
Node string
// Numbers numbers each trunk build at its claim and records what it was built with (design 51 *The versions*); nil
// numbers nothing, as the builder's program leaves it (design 47 H H-A-159: the reservation numbers, G §369).
Numbers Numbers
// Reserved reserves the version of a trunk build at its start (design 47 G §369); nil reserves nothing.
Reserved Reservations
// Picture answers the source revision the builder's picture of a watched branch holds, false while it holds none (design 47
@@ -124,27 +121,22 @@ type Builder struct {
// when 0.
RevisionWait time.Duration
// PackageWait bounds a build's wait for the publish of a package its entry names with no pin, its setting
// package-wait-minutes (H-A-165); DefaultPackageWait when 0. Only a registry seat's published heard (PackagePublished)
// gives a pin (H-A-192).
// package-wait-minutes (H-A-165); DefaultPackageWait when 0. The version is its publisher's at the key's origin
// (H-A-547 (3), H-A-551).
PackageWait time.Duration
// RecordBound bounds the record of a reservation's digests after a build ends, its setting record-bound-seconds (design 47
// H2 H-A-492): the builder's own bound, never the build's context; DefaultRecordBound when 0.
RecordBound time.Duration
// PublishedVersions asks the Go package registry seat's verb versions for one package path, its versions newest first
// (H-A-194): read once before a build waits for that package. Nil reads none.
PublishedVersions func(ctx context.Context, path string) ([]string, error)
// Forms answers what each node's engine states it reads (ADR 0618 §2, ADR 0624 §1): present, the nodes whose engine
// answered when last asked, and counted, every node the assignments names, present or away, a node with no statement
// stating nothing (the baseline's first forms). A done key names each artifact in the forms these keep, the oldest in
// its single reference, and its needs. Nil: no node states anything, and the first forms are kept.
Forms func() (present, counted map[string][]string)
once sync.Once
sem chan struct{}
wg sync.WaitGroup
mu sync.Mutex
// fillWaits are the builds that said wait-held for the fill (module.fingerprint), so it is said once.
fillWaits sync.Map
once sync.Once
sem chan struct{}
wg sync.WaitGroup
mu sync.Mutex
known map[string]meshcatalog.ModulesByModuleValue // by modules key: the first watched branch's
heard map[string]meshcatalog.ModulesByModuleValue // by branch and module (take): what supersedes what
heardAt map[string]Origin // by branch and module (take): the revision the heard entry came from (H-A-557)
@@ -178,9 +170,6 @@ type Builder struct {
builds map[string]context.CancelCauseFunc
// moved is closed and made again at each entry the picture takes in or drops: the step asks waiting for a revision wake.
moved chan struct{}
// publishedPins are the newest version a registry seat said published, by package path and series (PackagePublished):
// a package with no pin waits for one (H-A-192).
publishedPins map[string]map[string]string
// supersededSaid are the build keys refused as superseded (H-A-489), so each is said once.
supersededSaid sync.Map
// passedOverSaid are the build keys and heard fingerprints passed over as not newer (H-A-557), so each is said once.
@@ -216,7 +205,6 @@ func (b *Builder) init() {
b.hands, b.events = map[string]*handWatch{}, map[string]bool{}
b.builds = map[string]context.CancelCauseFunc{}
b.moved = make(chan struct{})
b.publishedPins = map[string]map[string]string{}
})
}
@@ -759,14 +747,6 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
byEvent := b.events[key]
delete(b.events, key)
b.mu.Unlock()
var numbering versions.Numbering
if trunk && planErr == nil && !nothing {
var goOn bool
if numbering, goOn = b.number(ctx, module, m, plan); !goOn {
end("is not built yet: it waits for its package's floor, nothing is claimed")
return
}
}
// Only a build of the registration's first watched branch reserves and releases a version (design 47 G §371).
reserving := trunk && b.originOf(key).First && planErr == nil && !nothing && b.reserves(ctx, module, m, plan)
if trunk && b.originOf(key).First && planErr == nil && !nothing && !reserving {
@@ -775,10 +755,6 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
b.logf("%v", err)
}
}
if reserving && b.waitFill(module, m) {
end("is not built yet: wait-held, the catalog has not said versions-filled")
return
}
// A key built again by hand is taken over as it stands too: one left building by a look that ended without its write
// (issue 1966) is the hand tool's to finish.
// A done key a person builds again whose reserved version is not released is built whole, under a version reserved afresh (A-490b).
@@ -827,9 +803,7 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
// Reserved as A-490b amended by H-A-225 has it: this fingerprint's standing reservation is kept while it is unreleased
// and above the highest the catalog's versions answers, else the next above that highest is taken (A-455); the build's
// own publish then runs.
if b.Reserved.Filled() {
reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), true)
}
reserved, hasReserved = b.reserve(ctx, module, m, plan, b.originOf(key), true)
reserving = true
} else if reserving && cl.Build.State != builds.BuildDone {
// Looked at again just before it reserves (H-A-489): a newer entry heard since the claim is not taken over.
@@ -845,10 +819,6 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
// A trunk build that reserves is never built without its version: it would end done and publish nothing, and its key would
// stay done, never built again (A-490). The key fails with why and is taken again at the next look or by builder_build_again.
result = failed("no version is reserved for this build: the builder's journal says why, and it is built again once one can be")
} else if numbering.Refused != "" && cl.Build.State != builds.BuildDone {
// Refused, naming the state it could not read, and built against no guess (ADR 0666 §15; design 47, test 70): the key
// fails with why, and is taken again at the next look.
result = failed("%s", numbering.Refused)
} else if nothing {
// A manifest with no artifact is built by building nothing: its key is done with no artifact, claimed and written as
// any other, so the controller has a done key to register it from (issue 1613, ADR 0478 clause 1, ADR 0501 clause 1).
@@ -898,11 +868,6 @@ func (b *Builder) try(ctx context.Context, module string, m meshcatalog.ModulesB
ended := LogEnded(module, m, "", b.Node, b.now(), result)
ended.OutOfStep = b.takeOutOfStep(key) // the generated files the build module's compare found out of step (design 26)
b.logBuild(ended)
if result.State == builds.BuildDone && b.Numbers != nil && len(numbering.Versions) > 0 {
if err := b.Numbers.Built(ctx, module, m, plan, numbering, result.Artifacts); err != nil {
b.logf("%s: %v", cl.Key, err)
}
}
if result.State == builds.BuildDone && hasReserved {
digests := map[string]string{}
for _, a := range result.Artifacts {
@@ -966,7 +931,6 @@ type lane struct {
toolchain *builds.ToolchainUsed
digests map[string]string // artifact -> digest
references map[string]string // artifact -> the reference an image was pushed to (a trunk build only)
imports []string // the mesh packages the lane's programs import, as its build module answered them
resolved map[string][]sdkstep.AskResolved // artifact -> the mesh packages its build resolved (design 47 G §466)
tcDigest string // the digest of the toolchain program the building node ran, kind 3's (design 47 G §466, §472)
tcVersion string // and the version it ran
@@ -1122,7 +1086,7 @@ func (b *Builder) build(ctx context.Context, module string, m meshcatalog.Module
used = nil
}
done := builds.BuilderBuild{State: builds.BuildDone, By: b.Claimer.By, Manifest: m.Manifest, Step: step, Artifacts: artifacts, Toolchains: used,
Imports: importsOf(lanes), Needs: forms.Current.Needs(artifacts), Packages: pinsOf(lanes)} // the forms it is written in (ADR 0618 §1)
Needs: forms.Current.Needs(artifacts), Packages: pinsOf(lanes)} // the forms it is written in (ADR 0618 §1)
for _, l := range lanes {
if l.kept != "" {
done.KeptOn = l.node // design 47 G §671: the build node that keeps the build
@@ -1273,9 +1237,9 @@ func (b *Builder) runLane(ctx context.Context, l *lane, repository string, m mes
if language == sdkstep.AskGo && job.Fetch != nil && len(m.Packages) > 0 {
// The versions of the mesh packages the fingerprint was computed with (novox/hq ADR 0573 §2): the build module writes
// them into the workspace, whatever the repository's go.mod names. A package the entry names with no pin waits for
// its publish and is built with the version that publish carries; past the bound the lane fails naming it, and no
// ask is put (H-A-192, H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Manifest, m.Packages)
// its publish and is built with the version its publisher holds at the key's origin; past the bound the lane fails
// naming it, and no ask is put (H-A-521, H-A-547 (3), H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, module, m.Fp2, m.Packages)
if outcome != "" {
l.err = errors.New(said)
return
@@ -1347,7 +1311,6 @@ func (b *Builder) runLane(ctx context.Context, l *lane, repository string, m mes
l.err = fmt.Errorf("the ask of %s on %s answered what is not a build: %s", l.module, step.Node, step.Result)
return
}
l.imports = answer.Imports
l.kept = answer.Kept
if answer.Toolchain != nil {
l.tcDigest, l.tcVersion = answer.Toolchain.Digest, answer.Toolchain.Version
@@ -1428,8 +1391,7 @@ func LogEnded(module string, m meshcatalog.ModulesByModuleValue, ref, by string,
}
e.Made = append([]builds.BuiltArtifact(nil), result.Artifacts...)
e.KeptOn = result.KeptOn
e.Imports = append([]string(nil), result.Imports...) // the indexer keeps them on the module (novox/hq ADR 0593 §2)
e.Error, e.Step = result.Error, result.Step // a failed build's reason, not only its outcome
e.Error, e.Step = result.Error, result.Step // a failed build's reason, not only its outcome
e.Needs = append([]string(nil), result.Needs...)
return e
}
@@ -1464,9 +1426,6 @@ func (b *Builder) takeOutOfStep(key string) []string {
return files
}
// importsOf are the mesh packages the lanes' programs import, as their build modules answered them (novox/hq ADR 0593
// §2): sorted and each once; nil when none answered any. A lane kept from a prior build answered none, so a build that
// kept one reports only what it built.
// pinsOf is the mesh packages' versions the lanes were built with (H-A-207), nil when none was pinned.
func pinsOf(lanes []*lane) map[string]string {
var out map[string]string
@@ -1481,19 +1440,6 @@ func pinsOf(lanes []*lane) map[string]string {
return out
}
func importsOf(lanes []*lane) []string {
seen := map[string]bool{}
for _, l := range lanes {
for _, p := range l.imports {
seen[p] = true
}
}
if len(seen) == 0 {
return nil
}
return slices.Sorted(maps.Keys(seen))
}
// SittingOutWords says, per node that is not on the agreed toolchain of a language, that it sits out and which version
// it has against the agreed one: "ace sits out: typescript 26.12.1, agreed 26.13.0" (novox/hq ADR 0584 clause 2).
func SittingOutWords(language string, a sdkstep.Agreement) []string {
@@ -23,8 +23,6 @@ import (
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-builder/internal/versions"
)
// buildModules simulates the two build modules on the nodes: a long tool answers a step and key at once and writes the
@@ -229,7 +227,7 @@ var (
)
func TestABundleAndAnArchiveAreBuiltOnOneNodeAndDone(t *testing.T) { // 1607/AC7, ADR 0478 clauses 1, 4
t.Run("the imports a build answers reach the done key and the log", importsABuildAnswersReachTheDoneKeyAndTheLog)
t.Run("the imports a build answers reach neither the done key nor the log", importsABuildAnswersReachNeitherTheDoneKeyNorTheLog)
t.Run("a kept build names its node in its end", aKeptBuildNamesItsNodeInItsEnd)
t.Run("the out-of-step files a build answers reach the log", outOfStepFilesABuildAnswersReachTheLog)
t.Run("ADR 0624: a done key keeps each form a counted node reads", aDoneKeyKeepsEachFormACountedNodeReads)
@@ -374,7 +372,7 @@ func TestAWithdrawnBuildEndsWithdrawn(t *testing.T) {
func TestANewerEntryHeardBeforeTheReservationIsNotTakenOver(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
newer, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp2: fp2, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains)})
@@ -443,14 +441,12 @@ func TestAnOlderFingerprintAskedAfterANewerEntryIsRefused(t *testing.T) {
func TestATrunkFingerprintIsOneAskOnTheDeliveryStream(t *testing.T) {
r := newRig(t, goBundle)
r.asks.Answer = nil // no node has pulled it yet
// Issue 1585 (ADR 0573 §2): the ask carries the module's pins; a package the entry keeps with no version (none
// published, design 47 H-A-161) is pinned at the version the registry seat's published carries (H-A-192), never
// asked without it.
r.b.PackagePublished("git.novox.be/novox/mesh-contracts/go/seats/x", "v0.1.7")
// Issue 1585 (ADR 0573 §2): the ask carries the module's pins (a package with none is filled at the key's origin, the
// step tests' H-A-547 (3)).
sdk := buildstep.PackageVersions{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": "v0.1.7"}
data, err := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Repository: "novox/mesh-catalog", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20",
Fp2: fp1, Manifest: mdigest('a'), Path: "modules/m", Toolchains: CatalogToolchains(agreedToolchains),
Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": ""}})
Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.20", "git.novox.be/novox/mesh-contracts/go/seats/x": "v0.1.7"}})
if err != nil {
t.Fatal(err)
}
@@ -552,88 +548,21 @@ func TestABundleAndAnImageOfOneModuleBuildOnOneNodeEach(t *testing.T) { // 1705a
}
}
func TestATrunkImageCallCarriesPublish(t *testing.T) { // 1705b; design 51 *The versions*: numbered at the claim
func TestATrunkImageCallCarriesPublish(t *testing.T) { // 1705b; design 47 H §756: a trunk build is claimed and built, asking no floor
r := newRig(t, imageArt)
r.puller = "ace"
nums := &fakeNumbers{wait: "m/img: the package waits for its floor"}
r.b.Numbers = nums
r.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
r.b.Wait()
if _, ok := r.st.vals[r.key]; ok || nums.numbered != 1 {
t.Fatalf("a build waiting for its floor was claimed (numbered %d times)", nums.numbered)
}
nums.wait, nums.versions = "", map[string]string{"img": "0.1.4"}
r.consider(t, "modules/m")
calls := r.bm.callsOf("build_image_build")
if len(calls) != 1 || calls[0].body.(map[string]any)["publish"] != true {
t.Errorf("calls = %+v, want publish true", calls)
}
if nums.built["img"] != digest {
t.Errorf("the built digest recorded = %v, want %s for img", nums.built, digest)
}
if nums.done != nil {
t.Errorf("a build still to make was numbered with done digests %v", nums.done)
}
// The indexer's packages state names a package of the module (PackageNamed): the done build is looked at again and
// numbered with its key's digests, so version.numbered carries them for the late publish; nothing is built again.
looks := nums.numbered
// nothing is built again.
r.b.PackageNamed(context.Background(), "m")
r.b.Wait()
if nums.numbered != looks+1 || nums.done["img"] != digest || len(r.bm.callsOf("build_image_build")) != 1 {
t.Errorf("a named package's done build: numbered %d more times with %v, %d image builds; want once with img %s and no build",
nums.numbered-looks, nums.done, len(r.bm.callsOf("build_image_build")), digest)
if n := len(r.bm.callsOf("build_image_build")); n != 1 {
t.Errorf("a named package's done build was built again: %d image builds, want 1", n)
}
// A late look that numbers a done build with no reservation is said aloud, naming builder_reserve_done (G §349, A-455).
late := &logged{}
r.b.Logf, r.b.Reserved = late.logf, &fakeReservations{filled: true}
r.b.PackageNamed(context.Background(), "m")
r.b.Wait()
if !late.has("late look numbered", "builder_reserve_done") {
t.Errorf("a late look numbered a done build with no reservation and said %v", late.lines)
}
r.b.Reserved = nil
looks = nums.numbered
r.b.PackageNamed(context.Background(), "other")
r.b.Wait()
if nums.numbered != looks {
t.Errorf("a module the builder does not know was looked at")
}
// D-B5 (ADR 0666 §15; design 47, test 70): a build whose published packages cannot be read is refused, naming the
// state: its key fails with why, and nothing is built.
unread := newRig(t, imageArt)
unread.puller = "ace"
unread.b.Numbers = &fakeNumbers{refused: "m/img: refused: the builder's state versions (bucket mesh-delivery-builder_versions) cannot be read"}
unread.b.Module(context.Background(), "m", moduleValue(t, "modules/m"))
unread.b.Wait()
if v := valueOf(t, unread.st, unread.key); v.State != builds.BuildFailed || !strings.Contains(v.Error, "state versions") || len(unread.bm.callsOf("build_image_build")) != 0 {
t.Errorf("a build with its versions unread: key %+v, %d builds; want failed naming the state, none built", v, len(unread.bm.callsOf("build_image_build")))
}
}
// fakeNumbers is Numbers that answers what it is set to and keeps the digests a done build recorded.
type fakeNumbers struct {
wait string
versions map[string]string
numbered int
built map[string]string
done map[string]string // the done key's digests the last look numbered with
refused string // answered as Numbering.Refused
}
func (f *fakeNumbers) Number(_ context.Context, _ string, _ meshcatalog.ModulesByModuleValue, _ Plan, done map[string]string) (versions.Numbering, error) {
f.done = done
f.numbered++
return versions.Numbering{Wait: f.wait, Versions: f.versions, Refused: f.refused}, nil
}
func (f *fakeNumbers) Built(_ context.Context, _ string, _ meshcatalog.ModulesByModuleValue, _ Plan, got versions.Numbering, made []builds.BuiltArtifact) error {
f.built = map[string]string{}
for _, a := range made {
if got.Versions[a.Name] != "" {
f.built[a.Name] = a.Digest
}
}
return nil
}
func TestAnUnpinnedUpstreamFailsNotPinnedAndIsNeverBuiltAgain(t *testing.T) { // B3, ADR 0498 clause 4
@@ -146,8 +146,9 @@ func (b *Builder) buildEntry(ctx context.Context, pipeline string, e meshbuilds.
if entry.Module != e.Module || (e.Commit != "" && entry.Commit != e.Commit) {
return meshbuilds.StepEndedOutcomeCouldNotRun, fmt.Sprintf("the entry of %s at %s is of %s at %s", e.Module, e.Fingerprint, entry.Module, entry.Commit)
}
// A package the entry names with no pin is built against its publish, waited for (H-A-192, H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, meshcatalogclient.BareManifestDigest(entry.ManifestDigest), entry.Packages)
// A package the entry names with no pin is built against its publisher's version at the key's origin, waited for
// (H-A-521, H-A-547 (3), H-A-165).
pinned, outcome, said := b.awaitPublished(ctx, entry.Module, entry.Fp, entry.Packages)
if outcome != "" {
return outcome, said
}
@@ -145,7 +145,7 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T)
t.Run(c.name, func(t *testing.T) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: c.version, Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true, released: map[string]bool{fp1: c.released}}
res := &fakeReservations{released: map[string]bool{fp1: c.released}}
if c.takenOver {
res.tookBy = map[string]versions.ReservedVersion{fp1: {Module: "m", Series: "0.1", Version: "0.1.7", Fingerprint: fp2}}
}
@@ -188,20 +188,26 @@ func TestABuildStepPassesAReservingBuildOnlyWithItsReservedVersion(t *testing.T)
t.Run("H-A-557: an entry the picture heard of an older revision supersedes no ask of a newer one", anOlderHeardEntrySupersedesNoNewerAsk)
t.Run("H-A-557: an entry heard of an older revision withdraws no running build of a newer one", anOlderHeardEntryWithdrawsNoNewerBuild)
t.Run("H-A-162: a revision held that changes no entry wakes the ask", aRevisionHeldWakesTheAsk)
t.Run("H-A-165: a package with no pin waits for its release and is built with it", aPackageWithNoPinWaitsForItsRelease)
t.Run("H-A-165: past its bound a package with no release fails the step", aPackageWithNoReleaseFailsPastItsBound)
t.Run("H-A-192: a lane waits for an unpinned package's publish and fails past its bound", aLaneWaitsForAnUnpinnedPackage)
t.Run("H-A-194: what the registry seat holds pins the package before any wait", theSeatsVersionsPinBeforeTheWait)
t.Run("H-A-547 (3): a package with no pin waits for its publisher's version at the key's origin and is built with it", aPackageWithNoPinWaitsForItsRelease)
t.Run("H-A-165: past its bound a package with no version at the origin fails the step", aPackageWithNoReleaseFailsPastItsBound)
t.Run("H-A-547 (3): a lane waits for an unpinned package's version at its origin and fails past its bound", aLaneWaitsForAnUnpinnedPackage)
}
// unpinnedRig is a rig whose step entry m names the package x with no version. Its manifest names no `packages`, so it
// accepts x in the default series 0.1. waiting is told when a build starts its wait for a package's publish.
func unpinnedRig(t *testing.T) (*rig, meshcatalog.CatalogEntry, <-chan struct{}) {
// unpinnedRig is a rig whose step entry m names the package x with no version, x published by the artifact x of the module xm,
// its key's origin source revision 41 of main. waiting is told when a build starts its wait for a package's publish.
func unpinnedRig(t *testing.T) (*rig, *fakeReservations, meshcatalog.CatalogEntry, <-chan struct{}) {
var held atomic.Int64
r, _, entry := revisionRig(t, &held, make(chan struct{}, 1))
r, res, entry := revisionRig(t, &held, make(chan struct{}, 1))
r.b.Picture = nil // no revision to wait for here
entry.Packages = map[string]string{unpinnedX: "", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"}
r.b.StepEntry = func(context.Context, string) (meshcatalog.CatalogEntry, error) { return entry, nil }
r.b.Members = func(_ context.Context, pkg string) (string, string, bool, error) {
return "xm", "x", pkg == unpinnedX, nil
}
r.b.init()
r.b.mu.Lock()
r.b.origin[r.key] = Origin{Branch: "main", Source: 41, First: true}
r.b.mu.Unlock()
waiting := make(chan struct{}, 1)
r.b.Logf = func(format string, args ...any) {
t.Logf(format, args...)
@@ -212,7 +218,7 @@ func unpinnedRig(t *testing.T) (*rig, meshcatalog.CatalogEntry, <-chan struct{})
}
}
}
return r, entry, waiting
return r, res, entry, waiting
}
const unpinnedX = "git.novox.be/novox/mesh-contracts/go/seats/x"
@@ -229,10 +235,10 @@ func awaitWaiting[T any](t *testing.T, waiting <-chan struct{}, ended <-chan T)
}
}
// H-A-192: the pin is the version the registry seat's published carries for the path in the accepted series; a publish in
// another series and the module's release number pin nothing.
// H-A-547 (3), H-A-551: the pin is the version the module publishing the package holds at the source revision of the key's
// origin; a version of another source revision and the newest a registry seat said published pin nothing.
func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
r, _, waiting := unpinnedRig(t)
r, res, _, waiting := unpinnedRig(t)
// Each entry's answer from a build is one journal line, built now or existing, beside the ask's answer (H-A-320 (1), H-A-333).
var mu sync.Mutex
var answers []string
@@ -245,8 +251,8 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
mu.Unlock()
}
}
r.b.PackagePublished(unpinnedX, "v0.2.9") // another series than the 0.1 the module accepts: no pin
r.b.PackagePublished(unpinnedX, "0.1.4-feat-x.2") // a group's tagged version: no pin
res.publishAt("xm", "x", "main", 40, "0.1.2") // another source revision than the key's origin: no pin
r.b.PackagePublished(unpinnedX, "v0.1.9") // the newest heard: no pin (H-A-547 (3))
ended := make(chan meshbuilds.StepEnded, 1)
go func() {
ended <- r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
@@ -256,6 +262,7 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
if _, ok := r.st.vals[r.key]; ok {
t.Fatal("the build was made before the package was published")
}
res.publishAt("xm", "x", "main", 41, "0.1.3")
r.b.PackagePublished(unpinnedX, "v0.1.3")
var end meshbuilds.StepEnded
select {
@@ -273,8 +280,8 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
if !reflect.DeepEqual(end.Packages, map[string]string{unpinnedX: "v0.1.3", "git.novox.be/novox/mesh-sdk/go": "v0.1.20"}) {
t.Errorf("the end reports the pins %v; want the ones it was built with", end.Packages)
}
// A done key reports the pins it keeps it was built with, never the newer one a publish gives now (H-A-207).
r.b.PackagePublished(unpinnedX, "v0.1.5")
// A done key reports the pins it keeps it was built with, never a newer one published now (H-A-207).
res.publishAt("xm", "x", "main", 41, "0.1.5")
again := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
if again.Outcome != meshbuilds.StepEndedOutcomePassed || again.Packages[unpinnedX] != "v0.1.3" {
@@ -304,59 +311,27 @@ func aPackageWithNoPinWaitsForItsRelease(t *testing.T) {
}
func aPackageWithNoReleaseFailsPastItsBound(t *testing.T) {
r, _, _ := unpinnedRig(t)
r, res, _, _ := unpinnedRig(t)
r.b.PackageWait = time.Nanosecond
end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
r.b.Wait()
if _, built := r.st.vals[r.key]; end.Outcome != meshbuilds.StepEndedOutcomeFailed || built ||
!strings.Contains(end.Said, "package "+unpinnedX+" has no released version in the series 0.1") {
!strings.Contains(end.Said, "package "+unpinnedX+" has no published version: xm publishes no version of it at source revision 41 of main") {
t.Errorf("end = %+v, built %v; want failed naming the package, nothing built", end, built)
}
// A publish heard before gives the pin at once.
r.b.PackagePublished(unpinnedX, "v0.1.2")
// A version its publisher holds at the origin gives the pin at once.
res.publishAt("xm", "x", "main", 41, "0.1.2")
if end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}); strings.Contains(end.Said, "no released version") {
t.Errorf("a publish heard did not pin the package: %+v", end)
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}}); strings.Contains(end.Said, "no published version") {
t.Errorf("a version at the origin did not pin the package: %+v", end)
}
}
// H-A-194: the build reads the registry seat's versions of the path once before it waits: a version in the accepted series
// pins the package with no event heard; one only in another series leaves the build waiting for a publish.
func theSeatsVersionsPinBeforeTheWait(t *testing.T) {
r, _, _ := unpinnedRig(t)
r.b.PackageWait = time.Nanosecond // no wait: the seat's answer alone gives the pin
var read []string
r.b.PublishedVersions = func(_ context.Context, path string) ([]string, error) {
read = append(read, path)
return []string{"0.2.1", "0.1.9", "0.1.8"}, nil // newest first
}
end := r.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
r.b.Wait()
asks := r.asks.Asks()
if end.Outcome != meshbuilds.StepEndedOutcomePassed || len(asks) == 0 || asks[0].Packages[unpinnedX] != "v0.1.9" || !slices.Equal(read, []string{unpinnedX}) {
t.Errorf("end = %+v, asks %+v, read %v; want passed, built with x at v0.1.9 read once from the seat", end, asks, read)
}
r2, _, waiting := unpinnedRig(t)
r2.b.PublishedVersions = func(context.Context, string) ([]string, error) { return []string{"0.2.1"}, nil }
ended := make(chan meshbuilds.StepEnded, 1)
go func() {
ended <- r2.b.BuildStep(t.Context(), "a1", meshbuilds.StepRun{Pipeline: "main.9.m", Step: meshbuilds.StepRunStepBuild, Branch: "main", Source: 41,
Entries: []meshbuilds.BuildEntry{{Module: "m", Fingerprint: fp1}}})
}()
awaitWaiting(t, waiting, ended)
r2.b.PackagePublished(unpinnedX, "0.1.10")
if end := <-ended; end.Outcome != meshbuilds.StepEndedOutcomePassed {
t.Errorf("end = %+v, want passed once x was published in its series", end)
}
r2.b.Wait()
}
// H-A-192, H-A-165: the lane of an entry taken in waits the same way, never asking a build without the pin, and fails the
// H-A-547 (3), H-A-165: the lane of an entry taken in waits the same way, never asking a build without the pin, and fails the
// key past the bound naming the package.
func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
r, entry, waiting := unpinnedRig(t)
r, res, entry, waiting := unpinnedRig(t)
done := make(chan struct{})
go func() {
r.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry)
@@ -367,6 +342,7 @@ func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
if asks := r.asks.Asks(); len(asks) != 0 {
t.Fatalf("a build was asked without the package's pin: %+v", asks)
}
res.publishAt("xm", "x", "main", 41, "0.1.5")
r.b.PackagePublished(unpinnedX, "0.1.5")
select {
case <-done:
@@ -377,11 +353,11 @@ func aLaneWaitsForAnUnpinnedPackage(t *testing.T) {
t.Errorf("asks %+v; want one asked with x at v0.1.5", asks)
}
// Past its bound the key fails naming the package, and nothing is asked.
r2, entry2, _ := unpinnedRig(t)
r2, _, entry2, _ := unpinnedRig(t)
r2.b.PackageWait = time.Nanosecond
r2.b.Entry(t.Context(), Origin{Branch: "main", Source: 41, First: true}, entry2)
r2.b.Wait()
if asks := r2.asks.Asks(); len(asks) != 0 || !strings.Contains(string(r2.st.vals[r2.key]), "package "+unpinnedX+" has no released version") {
if asks := r2.asks.Asks(); len(asks) != 0 || !strings.Contains(string(r2.st.vals[r2.key]), "package "+unpinnedX+" has no published version") {
t.Errorf("asks %+v, key %s; want none asked and the key failed naming the package", asks, r2.st.vals[r2.key])
}
}
@@ -421,7 +397,7 @@ func aRevisionHeldWakesTheAsk(t *testing.T) {
func revisionRig(t *testing.T, held *atomic.Int64, asked chan struct{}) (*rig, *fakeReservations, meshcatalog.CatalogEntry) {
r := newRig(t, goBundle)
r.mf.byDigest[mdigest('a')] = catalogue.Manifest{Module: "m", Version: "0.1", Build: &catalogue.Build{Artifacts: []catalogue.Artifact{goBundle}}}
res := &fakeReservations{filled: true}
res := &fakeReservations{}
r.b.Reserved = res
entry := meshcatalog.CatalogEntry{Module: "m", Repository: "novox/mesh-catalog", Path: "modules/m", Commit: "7a74cee83f88e6585a5511c3cc53bdf0f5303d20", Fp: fp1,
ManifestDigest: mdigest('a'), Inputs: &meshcatalog.EntryInputs{Toolchains: CatalogToolchains(agreedToolchains)}}
@@ -56,7 +56,7 @@ type ReAsk struct {
Failed string `json:"failed,omitempty"`
Revision uint64 `json:"revision,omitempty"`
Asks map[string]string `json:"asks,omitempty"`
// Name is the numbered name (`<module>/<artifact>`) of a ModeFloorAgain value; Version is a ModeRepublish value's
// Name is the module or node a hand act names; Version is a ModeRepublish value's
// request and Queued the builder's answer to it: the versions it queued, `<module> <version>`.
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
@@ -92,9 +92,6 @@ func NewPublishAct(mode, module, version, why, by string, at time.Time) (string,
return mode + "." + strconv.FormatInt(at.UnixNano(), 10), data, err
}
// ModeFloorAgain is the Mode of a reasks value of builder_floor_again (design 51 *The floor*).
const ModeFloorAgain = "floor-again"
// NewRepublish is the value builder_publish_again writes (design 47 G §588): its key, `republish.<unix nanoseconds>`
// (a call is one value, never a build key), and the value. Module and version are each optional.
func NewRepublish(module, version, why, by string, at time.Time) (string, []byte, error) {
@@ -109,20 +106,6 @@ func NewRepublish(module, version, why, by string, at time.Time) (string, []byte
return "republish." + strconv.FormatInt(at.UnixNano(), 10), data, err
}
// NewFloorAgain is the value builder_floor_again writes for a name: the key `floor.<name escaped>`, never a build key,
// and the value.
func NewFloorAgain(name, why, by string, at time.Time) (string, []byte, error) {
name = strings.TrimSpace(name)
if module, artifact, ok := strings.Cut(name, "/"); !ok || module == "" || artifact == "" {
return "", nil, fmt.Errorf("name %q is not a numbered name, <module>/<artifact>, as builder_versions lists it", name)
}
if strings.TrimSpace(why) == "" {
return "", nil, errors.New("say why the floor is asked again (why)")
}
data, err := json.Marshal(ReAsk{V: 1, Why: strings.TrimSpace(why), By: by, At: at.UTC(), Mode: ModeFloorAgain, Name: name})
return "floor." + versions.EscapeToken(name), data, err
}
// ModeOldFormDrop is the Mode of a reasks value of builder_old_form's drop (design 51 *Every build keeps the old
// reference form*): a retired node dropped from the count by hand; Name is the node.
const ModeOldFormDrop = "old-form-drop"
@@ -2,22 +2,11 @@ package versions
import (
"context"
"fmt"
"time"
)
// The tools' descriptions.
const (
FloorAgainDescription = "Refused for every name: the builder numbers nothing of its own and asks no floor (design 47 H H-A-159); " +
"a version is numbered by the reservation (design 47 G §369, builder_reserved). Kept until design 47 G §372 removes it with " +
"the state versions."
)
// Acts are the builder's hand acts on its versions, answered by its program (the tools bundle writes them to reasks).
type Acts struct {
Numberer *Numberer
// Reconsider looks at every module again, so a claim asks a name's floor.
Reconsider func(ctx context.Context)
// Republish queues the reserved versions builder_publish_again names (design 47 G §588): the versions it queued.
Republish func(ctx context.Context, module, version string) ([]string, error)
// DropOldForm drops a retired node from the old form's count by hand (builder_old_form): its answer, or why not.
@@ -30,10 +19,3 @@ type Acts struct {
// PublishDrop terminates one publish item (builder_publish_drop, design 47 H2 §793): the answer, or why not.
PublishDrop func(ctx context.Context, module, version, by, why string) (string, error)
}
// FloorAgain is builder_floor_again of name: refused, since the builder numbers nothing of its own and no claim asks a floor
// (design 47 H H-A-159; the reservation numbers, G §369). The tool stays until G §372 removes it with the state versions.
func (a Acts) FloorAgain(_ context.Context, name string) (string, error) {
return "", fmt.Errorf("the floor of %s is not asked: the builder numbers nothing of its own and asks no floor (design 47 H H-A-159); "+
"a version is numbered by the reservation (G §369, builder_reserved)", name)
}
@@ -2,10 +2,7 @@ package versions
import (
"context"
"fmt"
"sort"
"strings"
"time"
)
// The registry seats a version is published to (design 51 *The seats*), by what is published.
@@ -54,207 +51,3 @@ func TagPrefix(path string) string {
}
return path + "/v"
}
// ClaimArtifact is one artifact of a trunk build to number.
type ClaimArtifact struct {
Artifact, Kind, Language string
}
// BuildClaim is a trunk build at its claim: what Numberer.Number numbers.
type BuildClaim struct {
Module, Path, Repository, Fingerprint, Commit, Series string
// Revision is the source revision of the merge (a package is numbered per revision); Merge its sequence, for order.
Revision string
Merge uint64
Artifacts []ClaimArtifact
// Done are the digests of the build's done key, by artifact, when the claim is a look at a build already done: what it
// left unnumbered (a package whose name was not known yet, a floor that was silent) is numbered with them, so
// version.numbered carries the digest its build module publishes late. Nil for a build still to make.
Done map[string]string
}
// Numbering is what the claim got.
type Numbering struct {
// Versions are each artifact's version, by artifact; an artifact built unnumbered (its floor not known) has none.
Versions map[string]string
// Unnumbered are the artifacts built and published by digest, numbered once their floor answers (ADR 0617 §1).
Unnumbered []string
// Wait is why the build waits: a package whose floor is not known (design 51 *The floor*). Nothing is claimed.
Wait string
// Said are the builder's narrations of each decision, for its process log and its build log (build.said).
Said []Narration
// Names are the names each numbered artifact was numbered under, by artifact (NameOf, or a package's name in its
// ecosystem).
Names map[string]string
// Refused is why the build is refused: a package's published versions could not be read (ADR 0666 §15). Nothing else
// is numbered.
Refused string
}
// NameOf is the name artifact of module was numbered under in this numbering.
func (g Numbering) NameOf(module, artifact string) string {
if name := g.Names[artifact]; name != "" {
return name
}
return NameOf(module, artifact)
}
// Narration is one line the builder says in its build log (design 51: the build log says a version was kept, and
// why), and what it narrates.
type Narration struct{ Line, Why string }
// What a narration of the build log narrates (the build.said entry's why).
const (
SaidNumbered = "numbered"
SaidKept = "kept"
SaidWaiting = "waiting"
SaidUnnumbered = "unnumbered"
SaidOldFormClosed = "old-form-closed"
)
// narrationOf is a decision's narration.
func narrationOf(name string, d Decision) Narration {
why := SaidNumbered
switch {
case d.Keep:
why = SaidKept
case d.Wait:
why = SaidWaiting
case d.Unnumbered:
why = SaidUnnumbered
}
return Narration{Line: name + ": " + d.Why, Why: why}
}
// Numberer numbers trunk builds at their claim (design 51 *The versions*, DLV-B2, B3): it asks a name's floor only
// when versions holds nothing for it, and records a silent floor as a wait (FloorWaits, woken by its source's event).
type Numberer struct {
Versions Versions
Floor FloorSources
Waits *FloorWaits
// Holder is the module holding a seat, whose health condition's clear wakes a silent seat source; nil names none.
Holder func(seat string) string
// Names answers a package's name in its ecosystem; nil numbers a package as NameOf names it.
Names PackageNames
// Publishing is told each version Built recorded that is still numbered, its holder's word not heard yet: the
// builder arms its publish bound (publish.go); nil arms none.
Publishing func(ctx context.Context, e Entry)
Now func() time.Time
}
// Number numbers every numbered artifact of c. An error is a store that cannot be read or written: the claim is then
// built as before, unnumbered, and said.
func (n *Numberer) Number(ctx context.Context, c BuildClaim) (Numbering, error) {
out := Numbering{Versions: map[string]string{}, Names: map[string]string{}}
arts := append([]ClaimArtifact(nil), c.Artifacts...)
sort.Slice(arts, func(i, j int) bool { return arts[i].Artifact < arts[j].Artifact })
for _, a := range arts {
seat, kind, ok := SeatOf(a.Kind, a.Language)
if !ok {
continue
}
name := NameOf(c.Module, a.Artifact)
if kind == KindPackage && n.Names != nil {
// A package is numbered, asked for its floor and published under its name in its ecosystem (design 32), the
// name the holder's builder_versions question and the seat's versions name it by.
named, known, err := n.Names(ctx, c.Module, a.Artifact)
if err != nil || !known {
why := "the indexer's packages state names no name of it in its ecosystem yet (it writes one at the module's next trunk merge)"
if err != nil {
why = "the indexer's packages state cannot be read: " + err.Error()
}
out.Unnumbered = append(out.Unnumbered, a.Artifact)
out.Said = append(out.Said, Narration{Line: name + ": built unnumbered: " + why, Why: SaidUnnumbered})
continue
}
name = named
}
out.Names[a.Artifact] = name
entries, err := n.Versions.Of(ctx, name)
if err != nil && kind == KindPackage {
// A build that cannot read the published packages refuses, naming the unread state, never building against a
// guess (ADR 0666 §15; design 51 *The versions*, line 287).
out.Refused = fmt.Sprintf("%s: refused: the builder's state %s cannot be read, so its published versions are not known: %v", name, State, err)
return out, nil
}
if err != nil {
return out, err
}
var floor Floor
var why map[string]string
if len(entries) == 0 {
floor, why = n.askFloor(ctx, seat, name, c)
}
d, _, err := n.Versions.Number(ctx, Claim{Name: name, Kind: kind, Series: c.Series, Module: c.Module, Fingerprint: c.Fingerprint,
Commit: c.Commit, Revision: c.Revision, Digest: c.Done[a.Artifact], Seat: seat, Merge: c.Merge, Floor: floor})
if err != nil {
return out, err
}
out.Said = append(out.Said, narrationOf(name, d))
switch {
case d.Wait:
n.wait(name, seat, floor, why)
out.Wait = name + ": " + d.Why
return out, nil
case d.Unnumbered:
n.wait(name, seat, floor, why)
out.Unnumbered = append(out.Unnumbered, a.Artifact)
continue
}
if n.Waits != nil {
n.Waits.Answered(name)
}
out.Versions[a.Artifact] = d.Version
}
return out, nil
}
func (n *Numberer) askFloor(ctx context.Context, seat, name string, c BuildClaim) (Floor, map[string]string) {
return n.Floor.Ask(ctx, FloorOf{Seat: seat, Name: name, Repository: c.Repository, Prefix: TagPrefix(c.Path)})
}
func (n *Numberer) wait(name, seat string, f Floor, why map[string]string) {
if n.Waits == nil {
return
}
holder := ""
if n.Holder != nil {
holder = n.Holder(seat)
}
now := time.Now()
if n.Now != nil {
now = n.Now()
}
n.Waits.Wait(name, seat, holder, f, why, now)
}
// Built records the digest each numbered artifact was built with, on an entry that holds none yet or was never published: what the holder's
// builder_versions question compares (ADR 0605 §4).
func (n *Numberer) Built(ctx context.Context, c BuildClaim, got Numbering, digests map[string]string) error {
var errs []string
for artifact, version := range got.Versions {
d := digests[artifact]
if d == "" {
continue
}
e, err := n.Versions.Mark(ctx, got.NameOf(c.Module, artifact), version, func(e *Entry) {
// The new digest replaces the recorded one only while no published was said for the number (design 51
// *Tools of the builder*): a rebuild of a gone file under the same number.
if e.Digest == "" || e.State == Numbered || e.State == Refused {
e.Digest = d
}
})
if err != nil {
errs = append(errs, err.Error())
continue
}
if e.State == Numbered && n.Publishing != nil {
n.Publishing(ctx, e)
}
}
if len(errs) > 0 {
sort.Strings(errs)
return fmt.Errorf("the built digests could not be recorded: %s", strings.Join(errs, "; "))
}
return nil
}
@@ -122,20 +122,3 @@ func EntriesOf(branches *meshcatalogclient.Branches) Entries {
func HolderOf(branches *meshcatalogclient.Branches) func(seat string) (string, bool) {
return branches.Claimant
}
// RequirementsFrom answers the versions of a package the entries of every followed half require, each once, in order: what a
// consumer's entry names for it in its packages (design 47 G A-119), the floor's third source.
func RequirementsFrom(all Entries) func(ctx context.Context, name string) ([]string, error) {
return func(_ context.Context, name string) ([]string, error) {
seen := map[string]bool{}
var out []string
for _, e := range all() {
if v := e.Packages[name]; v != "" && !seen[v] {
seen[v] = true
out = append(out, v)
}
}
sort.Strings(out)
return out, nil
}
}
@@ -66,22 +66,3 @@ func TestPackageNamesAreReadFromTheCatalogHalfsEntries(t *testing.T) {
t.Errorf("CarriersFrom(twin) = %v, want %v", got, want)
}
}
// Design 47 G A-119: the floor's requirements are what the catalog half's entries name for the package, each version once.
func TestRequirementsFromAreTheVersionsEntriesNameForAPackage(t *testing.T) {
entries := func() []meshcatalog.CatalogEntry {
return []meshcatalog.CatalogEntry{
{Module: "a", Packages: map[string]string{"x/sdk": "v0.0.0-2026-aaa", "y": "v1.0.0"}},
{Module: "b", Packages: map[string]string{"x/sdk": "v0.0.0-2026-bbb"}},
{Module: "c", Packages: map[string]string{"x/sdk": "v0.0.0-2026-aaa"}},
{Module: "d"},
}
}
got, err := RequirementsFrom(entries)(context.Background(), "x/sdk")
if err != nil || !reflect.DeepEqual(got, []string{"v0.0.0-2026-aaa", "v0.0.0-2026-bbb"}) {
t.Errorf("requirements = %v, %v", got, err)
}
if got, _ := RequirementsFrom(entries)(context.Background(), "none"); len(got) != 0 {
t.Errorf("a package no entry names has requirements %v", got)
}
}
@@ -1,332 +0,0 @@
package versions
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
)
// FloorSources are the three sources of a name's floor (design 51 *The floor*): each a tool call that answers the
// versions it knows of a name, or an error when it does not answer.
type FloorSources struct {
// Seat is `seat:<registry>.versions` of the registry seat the name is published to.
Seat func(ctx context.Context, seat, name string) ([]string, error)
// Tags is the seat git's tags: the git tags of the repository the name is built from, under prefix.
Tags func(ctx context.Context, repository, prefix string) ([]string, error)
// Requirements are the versions of a package the catalog half's entries require (design 47 G A-119).
Requirements func(ctx context.Context, name string) ([]string, error)
}
// FloorOf names what a floor is asked for: the name on its seat, and the repository and tag prefix of its git tags.
type FloorOf struct{ Seat, Name, Repository, Prefix string }
// Ask asks the three sources of a name; a source that errs, or is not wired, is named in Silent with its error in why.
func (s FloorSources) Ask(ctx context.Context, of FloorOf) (Floor, map[string]string) {
seat, name := of.Seat, of.Name
var f Floor
why := map[string]string{}
ask := func(source string, call func() ([]string, error), into *[]string) {
if call == nil {
f.Silent, why[source] = append(f.Silent, source), "not asked: the builder has no path to it"
return
}
got, err := call()
if err != nil {
f.Silent, why[source] = append(f.Silent, source), err.Error()
return
}
*into = got
}
var seatCall, tagsCall, reqCall func() ([]string, error)
if s.Seat != nil {
seatCall = func() ([]string, error) { return s.Seat(ctx, seat, name) }
}
if s.Tags != nil {
tagsCall = func() ([]string, error) { return s.Tags(ctx, of.Repository, of.Prefix) }
}
if s.Requirements != nil {
reqCall = func() ([]string, error) { return s.Requirements(ctx, name) }
}
ask(SourceSeat, seatCall, &f.Seat)
ask(SourceTags, tagsCall, &f.Tags)
ask(SourceRequirements, reqCall, &f.Requirements)
return f, why
}
// What wakes a name waiting on its floor, never a timer (design 51, DLV-B3b): the source that was silent saying
// something, or its module's health condition clearing.
const (
// WakePublished is the holder's `published` on the builder's durable consumer of `<seat>.events`.
WakePublished = "published"
// WakeRevision is a catalog revision the builder hears (the catalog half's entry changed): tags and requirements are asked again.
WakeRevision = "catalog-revision"
// WakeTakenIn is the indexer's next `take-in.taken`, in place of the retired manifest-accepted: the floor looks at every
// module again (design 47 H H-A-116).
WakeTakenIn = "take-in.taken"
// WakeCleared is the condition keeper's clear of a silent module's health condition on `mesh-conditions`.
WakeCleared = "condition-cleared"
// WakeByHand is builder_floor_again, a hand act.
WakeByHand = "by hand"
)
// sourceOfWake is the floor source each event says something of; a clear names the source by its module.
var sourceOfWake = map[string]string{WakePublished: SourceSeat, WakeTakenIn: SourceRequirements}
// SourceSeats are the seats whose holders are the floor's tag and requirement sources (design 47 G A-82): the seat git (tags)
// and the seat mesh-catalog (requirements), the holders read from the seat list and the catalog half.
var SourceSeats = map[string]string{SourceTags: "git", SourceRequirements: "mesh-catalog"}
// FloorWait is one name waiting on its floor: the sources still silent and why, since when; the finding the builder
// writes names them, cleared once all three answer.
type FloorWait struct {
Name string `json:"name"`
Seat string `json:"seat"`
Silent []string `json:"silent"`
Why map[string]string `json:"why,omitempty"`
Since time.Time `json:"since"`
// Holder is the module holding the name's seat: its condition's clear wakes the seat source.
Holder string `json:"holder,omitempty"`
}
// Finding is the floor finding's words.
func (w FloorWait) Finding() string {
var parts []string
for _, s := range w.Silent {
p := s
if why := w.Why[s]; why != "" {
p += " (" + why + ")"
}
parts = append(parts, p)
}
return fmt.Sprintf("the floor of %s is not known since %s: %s did not answer; nothing of it is numbered until all three answer",
w.Name, w.Since.UTC().Format(time.RFC3339), strings.Join(parts, ", "))
}
// The builder's state floor-waits (DLV-B4): each name waiting on its floor, keyed by its escaped name, so a restarted
// builder still knows which names its silent sources' events wake; builder_floor_waits reads it.
const (
FloorWaitsState = "floor-waits"
FloorWaitsTool = "builder_floor_waits"
)
// FloorWaitKey is a wait's key in floor-waits.
func FloorWaitKey(name string) string { return EscapeToken(name) }
// FloorKeeper keeps the waits on the bus: Put a wait's value, Delete its key.
type FloorKeeper interface {
Put(key string, value []byte) error
Delete(key string) error
}
// FloorWaits are the names waiting on their floor. Wake answers which names to ask again for an event, Answered drops
// a name once all three answered; the builder's finding for each is the wait's Finding. Once Kept, every change is
// written to the state floor-waits as well.
type FloorWaits struct {
mu sync.Mutex
waits map[string]FloorWait
keeper FloorKeeper
// Logf says a wait that could not be kept; nil says nothing.
Logf func(string, ...any)
// Holder finds the module holding a seat (the catalog half's claim); a source's module is the holder of its SourceSeats seat.
Holder func(seat string) (string, bool)
// Said is told each wait recorded (raised) and each answered (not raised): the builder's finding floor-silent.
Said func(w FloorWait, raised bool)
}
// FloorSilent is the kind of the floor finding.
const FloorSilent = "floor-silent"
// Keep binds the state: the waits it holds that are not known here are taken in (a restarted builder's), every wait
// known here is written to it, and every change from now on is.
func (fw *FloorWaits) Keep(k FloorKeeper, held []FloorWait) {
fw.mu.Lock()
if fw.waits == nil {
fw.waits = map[string]FloorWait{}
}
for _, w := range held {
if _, had := fw.waits[w.Name]; !had && w.Name != "" {
fw.waits[w.Name] = w
}
}
fw.keeper = k
all := make([]FloorWait, 0, len(fw.waits))
for _, w := range fw.waits {
all = append(all, w)
}
fw.mu.Unlock()
for _, w := range all {
fw.put(k, w)
}
}
func (fw *FloorWaits) put(k FloorKeeper, w FloorWait) {
if k == nil {
return
}
data, err := json.Marshal(w)
if err == nil {
err = k.Put(FloorWaitKey(w.Name), data)
}
if err != nil && fw.Logf != nil {
fw.Logf("the floor wait of %s is not kept in %s (a restart forgets it until its next claim): %v", w.Name, FloorWaitsState, err)
}
}
// DecodeFloorWait reads one value of floor-waits.
func DecodeFloorWait(raw []byte) (FloorWait, error) {
var w FloorWait
if err := json.Unmarshal(raw, &w); err != nil {
return FloorWait{}, err
}
if w.Name == "" {
return FloorWait{}, errors.New("a floor wait names no name")
}
return w, nil
}
// Wait records that name's floor is not known.
func (fw *FloorWaits) Wait(name, seat, holder string, f Floor, why map[string]string, now time.Time) FloorWait {
fw.mu.Lock()
if fw.waits == nil {
fw.waits = map[string]FloorWait{}
}
w, had := fw.waits[name]
if !had {
w.Since = now
}
w.Name, w.Seat, w.Holder, w.Silent, w.Why = name, seat, holder, slices.Clone(f.Silent), why
fw.waits[name] = w
k := fw.keeper
fw.mu.Unlock()
fw.put(k, w)
if fw.Said != nil {
fw.Said(w, true)
}
return w
}
// Answered drops name: its floor is known. It says whether the name waited, so its finding is cleared.
func (fw *FloorWaits) Answered(name string) bool {
fw.mu.Lock()
w, had := fw.waits[name]
delete(fw.waits, name)
k := fw.keeper
fw.mu.Unlock()
if had && fw.Said != nil {
fw.Said(w, false)
}
if had && k != nil {
if err := k.Delete(FloorWaitKey(name)); err != nil && fw.Logf != nil {
fw.Logf("the floor wait of %s is not cleared from %s: %v", name, FloorWaitsState, err)
}
}
return had
}
// FloorWaitsAnswer is what builder_floor_waits answers: every name waiting on its floor, oldest first, with its finding.
type FloorWaitsAnswer struct {
Waits []FloorWaitRead `json:"waits"`
}
// FloorWaitRead is one wait as builder_floor_waits shows it.
type FloorWaitRead struct {
FloorWait
Finding string `json:"finding"`
}
// AnswerFloorWaits is builder_floor_waits, read from the state floor-waits.
func AnswerFloorWaits(r Reader) (FloorWaitsAnswer, error) {
keys, err := r.Keys()
if err != nil {
return FloorWaitsAnswer{}, err
}
out := FloorWaitsAnswer{Waits: []FloorWaitRead{}}
for _, k := range keys {
raw, ok, err := r.Get(k)
if err != nil {
return FloorWaitsAnswer{}, err
}
if !ok {
continue
}
w, err := DecodeFloorWait(raw)
if err != nil {
return FloorWaitsAnswer{}, fmt.Errorf("%s.%s: %w", FloorWaitsState, k, err)
}
out.Waits = append(out.Waits, FloorWaitRead{FloorWait: w, Finding: w.Finding()})
}
sort.Slice(out.Waits, func(i, j int) bool {
if !out.Waits[i].Since.Equal(out.Waits[j].Since) {
return out.Waits[i].Since.Before(out.Waits[j].Since)
}
return out.Waits[i].Name < out.Waits[j].Name
})
return out, nil
}
// FloorWaitsDescription is builder_floor_waits' description.
const FloorWaitsDescription = "The names waiting on their floor (the builder's state floor-waits, design 51 *The floor*), oldest first: " +
"each name, its registry seat, the sources still silent and why, since when, and the finding the builder says for it. " +
"Nothing of a waiting name is numbered until all three sources answer; builder_floor_again asks one again by hand. Read-only."
// Wake answers the names to ask their floor again on an event: kind one of the Wake constants; seat the seat a
// `published` came on; module the module whose condition cleared. A name is woken only when the event says something
// of a source it waits on; WakeByHand with a name wakes that name alone.
func (fw *FloorWaits) Wake(kind, seat, module, name string) []string {
fw.mu.Lock()
defer fw.mu.Unlock()
var out []string
for n, w := range fw.waits {
switch kind {
case WakeByHand:
if n == name {
out = append(out, n)
}
case WakeCleared:
for _, s := range w.Silent {
if fw.holds(SourceSeats[s], module) || (s == SourceSeat && w.Holder != "" && w.Holder == module) {
out = append(out, n)
break
}
}
default:
src := sourceOfWake[kind]
if kind == WakeRevision {
if slices.Contains(w.Silent, SourceTags) || slices.Contains(w.Silent, SourceRequirements) {
out = append(out, n)
}
} else if slices.Contains(w.Silent, src) && (kind != WakePublished || seat == "" || seat == w.Seat) {
out = append(out, n)
}
}
}
sort.Strings(out)
return out
}
// Waiting is every wait, by name.
func (fw *FloorWaits) Waiting() []FloorWait {
fw.mu.Lock()
defer fw.mu.Unlock()
out := make([]FloorWait, 0, len(fw.waits))
for _, w := range fw.waits {
out = append(out, w)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// holds is whether module holds seat on the catalog half.
func (fw *FloorWaits) holds(seat, module string) bool {
if seat == "" || module == "" || fw.Holder == nil {
return false
}
holder, ok := fw.Holder(seat)
return ok && holder == module
}
@@ -1,10 +1,5 @@
package versions
import (
"context"
"fmt"
)
// The registry seats' events the builder hears on its durable consumer of each `<seat>.events` (design 51 *How a
// publish ends*, DLV-B4).
const (
@@ -26,56 +21,3 @@ type Outcome struct {
// Tags are, on kept, the other tags still naming its digest.
Tags []string `json:"tags,omitempty"`
}
// Heard takes one seat event in: a numbered version's entry turns published (with its digest when it held none),
// refused with the holder's reason, removed with its reason and the event's id, or kept (another tag names its digest)
// with the other tags; a by-digest publish (no version)
// marks nothing. It answers the names waiting on their floor that the event wakes: a `published` says the seat
// answers (design 51 *The floor*).
func (n *Numberer) Heard(ctx context.Context, seat, event, id string, o Outcome) ([]string, error) {
var wake []string
if event == HeardPublished && n.Waits != nil {
wake = n.Waits.Wake(WakePublished, seat, "", "")
}
if o.Version == "" {
return wake, nil
}
var change func(*Entry)
switch event {
case HeardPublished:
// A published of other bytes than an entry records under its number is no publish of that entry: the reservation
// numbered it and takes it in (design 47 H H-A-159, G §369, A-415; ADR 0605 §4), and the entry stays as it is.
if e, ok, _, err := n.Versions.Recorded(ctx, o.Name, o.Version, o.Digest); err == nil && !ok && e.Digest != "" && o.Digest != "" && e.Digest != o.Digest {
return wake, fmt.Errorf("%s@%s is recorded with digest %s, so %s's published of %s is %w", o.Name, o.Version, e.Digest, seat, o.Digest, ErrNotNumbered)
}
change = func(e *Entry) {
e.State, e.Reason = Published, ""
if e.Digest == "" {
e.Digest = o.Digest
}
}
case HeardRefused:
change = func(e *Entry) {
if e.State != Published {
e.State, e.Reason, e.RefusedDigest = Refused, o.Reason, o.Digest
}
}
case HeardRemoved:
change = func(e *Entry) { e.State, e.Reason, e.RemovedBy = Removed, o.Reason, id }
case HeardKept:
change = func(e *Entry) {
if e.State != Removed {
e.State, e.Reason, e.KeptWith = Kept, o.Reason, append([]string(nil), o.Tags...)
if e.Reason == "" {
e.Reason = "shared-digest"
}
}
}
default:
return wake, fmt.Errorf("%s says %q, which the builder does not hear", seat, event)
}
if _, err := n.Versions.Mark(ctx, o.Name, o.Version, change); err != nil {
return wake, fmt.Errorf("%s's %s of %s@%s: %w", seat, event, o.Name, o.Version, err)
}
return wake, nil
}
@@ -4,121 +4,15 @@ import (
"context"
"errors"
"fmt"
"sort"
"strings"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
)
// PackagesState is the indexer's packages state as the builder reads it (its manifest's reads grant): its keys, and one
// key's value (found false when it holds none).
type PackagesState interface {
Keys(ctx context.Context) ([]string, error)
Get(ctx context.Context, key string) (value []byte, found bool, err error)
}
// NamesIn are a package's names in its ecosystem as the indexer's packages state holds them (design 32): the name of the
// series key that names module and artifact as what it is built from. A series key is named `<name>.<series>`; a key
// with no dot is a mesh Go module's published packages, not a series. A value that does not decode is passed over.
func NamesIn(s PackagesState) PackageNames {
return func(ctx context.Context, module, artifact string) (string, bool, error) {
keys, err := s.Keys(ctx)
if err != nil {
return "", false, err
}
sort.Strings(keys)
built := NameOf(module, artifact)
for _, key := range keys {
if !isSeriesKey(key) {
continue
}
value, found, err := s.Get(ctx, key)
if err != nil {
return "", false, err
}
if !found {
continue
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value) // the indexer's value of a series key (mesh-sdk's contract, J4)
if err != nil || v.Package != built {
continue
}
return v.Name, true, nil
}
return "", false, nil
}
}
// NamedModule is the module a value of the indexer's packages state names a package's name for (design 32), and that
// name: a series key whose value names a name and the <module>/<artifact> it is built from. The builder looks at that module again when
// the value is heard, so a done build that left the package unnumbered (its name not known at its claim) is numbered then.
func NamedModule(key string, value []byte) (module, name string, ok bool) {
if !isSeriesKey(key) {
return "", "", false
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value)
if err != nil || v.Name == "" {
return "", "", false
}
module, artifact, cut := strings.Cut(v.Package, "/")
if !cut || module == "" || artifact == "" {
return "", "", false
}
return module, v.Name, true
}
// isSeriesKey says whether a key of the indexer's packages state is a series key (`<package>.<series>`), not a per-module one.
func isSeriesKey(key string) bool {
_, _, ok := meshcatalog.ParsePackagesByPackageSeriesKey(key)
return ok
}
// Built is a module's artifact, which a package's name is the name of.
type Built struct{ Module, Artifact string }
// Carriers are the module artifacts a package's name in its ecosystem is the name of, as the catalog half's packages view
// holds them (the inverse of NamesIn; design 47 G §572, §478): each distinct module and artifact of a series key whose value
// names that name, sorted. A name no entry carries answers none.
func Carriers(s PackagesState) func(ctx context.Context, name string) ([]Built, error) {
return func(ctx context.Context, name string) ([]Built, error) {
keys, err := s.Keys(ctx)
if err != nil {
return nil, err
}
sort.Strings(keys)
seen := map[Built]bool{}
var out []Built
for _, key := range keys {
if !isSeriesKey(key) {
continue
}
value, found, err := s.Get(ctx, key)
if err != nil {
return nil, err
}
if !found {
continue
}
v, _, err := meshcatalog.DecodePackagesByPackageSeriesValue(value)
if err != nil || v.Name != name {
continue
}
if module, artifact, cut := strings.Cut(v.Package, "/"); cut && module != "" && artifact != "" && !seen[Built{module, artifact}] {
seen[Built{module, artifact}] = true
out = append(out, Built{module, artifact})
}
}
return out, nil
}
}
// ModuleOf is the module and artifact a package's name is built from (Carriers), found false for a name no entry carries; more
// than one entry carrying it is an error naming them.
func ModuleOf(s PackagesState) func(ctx context.Context, name string) (module, artifact string, found bool, err error) {
return moduleOfCarriers(Carriers(s))
}
// moduleOfCarriers is ModuleOf over one way of finding the carriers.
// moduleOfCarriers is the module and artifact a package's name is built from, found false for a name no entry carries; more
// than one entry carrying it is an error naming them. The carriers are read from the catalog half's entries (CarriersFrom,
// design 47 G §348), never from the indexer's state.
func moduleOfCarriers(carriers func(ctx context.Context, name string) ([]Built, error)) func(ctx context.Context, name string) (module, artifact string, found bool, err error) {
return func(ctx context.Context, name string) (string, string, bool, error) {
got, err := carriers(ctx, name)
@@ -25,6 +25,8 @@ import (
const (
OldFormState = "old-form"
OldFormKey = "window"
// SaidOldFormClosed is the why of the build log's line saying the window closed (build.said).
SaidOldFormClosed = "old-form-closed"
)
// OldFormHeld is the finding of a node holding the window open for FindingAfter, about that node, cleared when the
@@ -9,23 +9,14 @@ import (
)
// **A publish that ends badly is loud** (design 51 *Health and conditions*; review round 1): the builder raises the
// finding publish-refused when a holder says refused, and publish-unanswered when a version it built and numbered is
// neither published nor refused within PublishBound. Each is about the name, so a later published of any version of it
// clears both. A seat's outcome that does not read is the finding seat-outcome-unread about the seat, cleared by its
// next outcome that reads.
//
// The bound is a key of the builder's state bounds per version (PublishBoundKey), written with its own time to live
// when the build is done and the version is still numbered, deleted at the holder's word; the bus's marker of its end,
// heard on the watch, is what raises publish-unanswered while the version is still numbered. No timer.
// finding publish-refused when a holder says refused, about the name, so a later published of any version of it clears
// it. A seat's outcome that does not read is the finding seat-outcome-unread about the seat, cleared by its next outcome
// that reads. A reserved version left unpublished past its bound is the reservation's finding (version-unreleased,
// design 47 G §369); the numbered version's bound goes with the numbering from before G (design 47 H §756).
const (
// BoundsState is the builder's state of its expiring keys, each with its own time to live: a publish's bound
// (PublishBoundKey), a node's seven days holding the old form's window (OldFormBoundKey) and a build key left
// BoundsState is the builder's state of its expiring keys, each with its own time to live: a node's seven days holding the old form's window (OldFormBoundKey) and a build key left
// building unput (UnputBoundKey). Its end, the bus's marker heard on the watch, is what acts.
BoundsState = "bounds"
// PublishBound is the build module's own wait for the holder's word (design 51 *How a publish ends*: at most
// 10 minutes), so a version unanswered past it is one the holder never answered.
PublishBound = 10 * time.Minute
BoundsState = "bounds"
PublishRefused = "publish-refused"
PublishUnanswered = "publish-unanswered"
SeatOutcomeUnread = "seat-outcome-unread"
@@ -33,7 +24,6 @@ const (
// The prefixes of the keys of BoundsState.
const (
publishBoundPrefix = "publish."
oldFormBoundPrefix = "old-form."
unputBoundPrefix = "unput."
stepsBoundPrefix = "steps."
@@ -62,16 +52,9 @@ func StepsBoundOf(key string) (module, askID string, ok bool) {
// UnputBoundOf is the build key an unput bound names, and whether key is one.
func UnputBoundOf(key string) (string, bool) { return strings.CutPrefix(key, unputBoundPrefix) }
// PublishBoundKey is the bound of name's version: `publish.<versions key>`.
func PublishBoundKey(name, version string) string { return publishBoundPrefix + Key(name, version) }
// OldFormBoundKey is the bound of node's seven days holding the old form's window: `old-form.<node>`.
func OldFormBoundKey(node string) string { return oldFormBoundPrefix + EscapeToken(node) }
// PublishBoundOf is the versions key a publish's bound names, and whether key is one; a key that is no publish's
// bound is an old form's (IsOldFormBound) or nothing the builder wrote.
func PublishBoundOf(key string) (string, bool) { return strings.CutPrefix(key, publishBoundPrefix) }
// IsOldFormBound says key is a node's bound of the old form's window: its end steps the window, which raises the
// finding for every node past FindingAfter.
func IsOldFormBound(key string) bool { return strings.HasPrefix(key, oldFormBoundPrefix) }
@@ -81,7 +64,7 @@ const BoundsTool = "builder_bounds"
// BoundsDescription is builder_bounds' description.
const BoundsDescription = "The builder's expiring keys, its state " + BoundsState + " (design 51 *Health and conditions*): each key with what it " +
"bounds (a version's publish, whose end unanswered is the finding " + PublishUnanswered + "; or a node's seven days holding the old " +
"bounds (a node's seven days holding the old " +
"form's window, whose end is the finding " + OldFormHeld + "; or a build key left building because its end could not be written, " +
"whose end is the finding call-unanswered; or a dependent's wait for a package member of a group's run, whose end fails its " +
"step), when it ends, and how long is left. The bus ends each key by its own time to live."
@@ -133,9 +133,6 @@ type Source struct {
// ReservedKey is the key of module's reservation of series (MAJOR.MINOR).
func ReservedKey(module, series string) string { return Key(module, series) }
// ErrNotFilled is what Reserve answers before the catalog says versions-filled: nothing is reserved until then (§369).
var ErrNotFilled = errors.New("versions-filled is not heard: nothing is reserved before the catalog's versions are filled")
// ReserveStore is the reservations' bucket: compare-and-set, and deletion.
type ReserveStore interface {
Store
@@ -147,8 +144,6 @@ type Reserver struct {
Store ReserveStore
// ReleasedOf are the patch versions (MAJOR.MINOR.PATCH) the catalog holds released for module, from its verb versions.
ReleasedOf func(ctx context.Context, module string) ([]string, error)
// Filled says the catalog said versions-filled.
Filled func() bool
// Took is told when a build took over the series' reservation of an older build never released (design 47 G A-455): the
// older reservation, which no want follows any more, is gone from the key, replaced by the newer's. Nil is told none.
Took func(ctx context.Context, older, newer ReservedVersion)
@@ -236,9 +231,6 @@ func SplitVersion(version string) (series string, patch int, err error) {
// alike (design 47 H H-A-225, which amends G A-490b): the run already building carries that number. A reservation another
// fingerprint takes over is withdrawn: its version is kept in Withdrawn, and Took is told so the older build is ended.
func (r *Reserver) Reserve(ctx context.Context, module, series string, artifacts []string, src Source) (ReservedVersion, error) {
if r.Filled != nil && !r.Filled() {
return ReservedVersion{}, ErrNotFilled
}
released, err := r.ReleasedOf(ctx, module)
if err != nil {
return ReservedVersion{}, fmt.Errorf("the released versions of %s cannot be read: %w", module, err)
@@ -427,6 +419,11 @@ type ReleasedBuild struct {
// Withdrawn are the fingerprints whose numbers the released version took over, by the number withdrawn (H-A-226), so a
// takeover still answers once the release deleted the series key (H-A-508); absent for a release that took none over.
Withdrawn map[string]string `json:"withdrawn,omitempty"`
// Branch and Source are the source revision of the catalog revision the released build came from, as the key's origin names
// it (its watched branch with it), as its reservation kept them (design 47 H2 H-A-551, H-A-558 (2)): an importer's build of
// that origin is filled from it once the reservation is gone; empty for a release kept before.
Branch string `json:"branch,omitempty"`
Source int64 `json:"source,omitempty"`
}
// ReleasedFor says whether the builder saw a version released for the build of fingerprint among the module's last releases.
@@ -496,8 +493,49 @@ func (r *Reserver) PublishedOf(ctx context.Context, module, artifact, fingerprin
return meshbuilds.PublishedAnswer{Published: false}, nil
}
// VersionAt answers the version artifact of module is published at from the source revision of branch (design 47 H2 H-A-547
// (3), H-A-551): the standing reservation of that branch and source revision whose artifact a registry seat said published, its
// number not withdrawn, first; else the module's release recorded at that branch and source revision (H-A-558 (2)), the newest such. A reservation of
// that origin not yet published answers none, so the importer's build waits for the publish (H-A-521).
func (r *Reserver) VersionAt(ctx context.Context, module, artifact, branch string, source int64) (string, bool, error) {
if module == "" || artifact == "" || source <= 0 {
return "", false, nil
}
ref := module + ":" + artifact
keys, err := r.Store.KeysOf(ctx, NameFilter(module))
if err != nil {
return "", false, fmt.Errorf("the reservations of %s cannot be listed: %w", module, err)
}
sort.Strings(keys)
for _, k := range keys {
cur, _, found, err := r.get(ctx, k)
if err != nil {
return "", false, err
}
if found && cur.Module == module && cur.Branch == branch && cur.Source == source && cur.Published[ref] && !hasKey(cur.Withdrawn, cur.Version) {
return cur.Version, true, nil
}
}
if r.Releases == nil {
return "", false, nil
}
raw, _, found, err := r.Releases.Get(ctx, ReleasedKey(module))
if err != nil {
return "", false, fmt.Errorf("the releases of %s cannot be read: %w", module, err)
}
var rec ReleasedRecord
if found && json.Unmarshal(raw, &rec) == nil {
for i := len(rec.Kept) - 1; i >= 0; i-- {
if rec.Kept[i].Branch == branch && rec.Kept[i].Source == source {
return rec.Kept[i].Version, true, nil
}
}
}
return "", false, nil
}
// keepRelease adds a release to the module's record, dropping the oldest past ReleasedKept.
func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version string, digests, withdrawn map[string]string) error {
func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version string, digests, withdrawn map[string]string, branch string, source int64) error {
n := r.ReleasedKept
if n < 1 {
n = DefaultReleasedKept
@@ -517,7 +555,7 @@ func (r *Reserver) keepRelease(ctx context.Context, module, fingerprint, version
kept = append(kept, k)
}
}
kept = append(kept, ReleasedBuild{Fingerprint: fingerprint, Version: version, Digests: digests, Withdrawn: maps.Clone(withdrawn)})
kept = append(kept, ReleasedBuild{Fingerprint: fingerprint, Version: version, Digests: digests, Withdrawn: maps.Clone(withdrawn), Branch: branch, Source: source})
if len(kept) > n {
kept = kept[len(kept)-n:]
}
@@ -567,7 +605,7 @@ func (r *Reserver) Released(ctx context.Context, module, version string) ([]stri
continue
}
if cur.Version == version && cur.Fingerprint != "" && r.Releases != nil {
if err := r.keepRelease(ctx, module, cur.Fingerprint, version, cur.Artifacts, cur.Withdrawn); err != nil {
if err := r.keepRelease(ctx, module, cur.Fingerprint, version, cur.Artifacts, cur.Withdrawn, cur.Branch, cur.Source); err != nil {
return gone, fmt.Errorf("the release of %s %s cannot be recorded: %w", module, version, err)
}
}
@@ -33,27 +33,16 @@ func (m *reserveMem) Update(ctx context.Context, key string, value []byte, rev u
}
// TestReservation: design 47 G §369 (test 102): two builds close together reserve two versions, the key goes on
// version-released, a built reservation with an artifact unpublished past the bound is unreleased, and nothing is reserved
// before versions-filled.
// version-released, a built reservation with an artifact unpublished past the bound is unreleased.
func TestReservation(t *testing.T) {
ctx := context.Background()
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
released := []string{"0.1.18", "0.1.19", "0.2.7"}
filled := true
store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Filled: func() bool { return filled }, Now: func() time.Time { return now },
r := &Reserver{Store: store, Now: func() time.Time { return now },
ReleasedOf: func(context.Context, string) ([]string, error) { return released, nil }}
arts := []string{"m:a", "m:b"}
filled = false
if _, err := r.Reserve(ctx, "m", "0.1", arts, Source{}); !errors.Is(err, ErrNotFilled) {
t.Fatalf("before versions-filled: %v, want ErrNotFilled", err)
}
if got, _ := r.All(ctx); len(got) != 0 {
t.Fatalf("a reservation was written before the fill: %v", got)
}
filled = true
first, err := r.Reserve(ctx, "m", "0.1", arts, Source{})
if err != nil || first.Version != "0.1.20" {
t.Fatalf("first build reserves %q (%v), want 0.1.20 after the highest released 0.1.19", first.Version, err)
@@ -196,7 +185,7 @@ func TestReservationIsReadAndMarkedPublished(t *testing.T) {
func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) {
ctx := context.Background()
rel := &reserveMem{mem: newMem()}
r := &Reserver{Store: &reserveMem{mem: newMem()}, Releases: rel, ReleasedKept: 2, Filled: func() bool { return true },
r := &Reserver{Store: &reserveMem{mem: newMem()}, Releases: rel, ReleasedKept: 2,
ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }}
v, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:aa"})
if err != nil {
@@ -217,6 +206,44 @@ func TestAReleaseIsRecordedByFingerprintBeforeItsReservationGoes(t *testing.T) {
if all, _ := r.All(ctx); len(all) != 0 {
t.Errorf("reservations left: %v", all)
}
// Design 47 H2 H-A-547 (3), H-A-551: an importer's version at the source revision of its key's origin is the standing
// reservation of that origin once its artifact is published, then the release recorded at that source revision.
w, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: "src2:cc", Branch: "main", Revision: 41})
if err != nil {
t.Fatal(err)
}
at := func(branch string, source int64) string {
v, found, err := r.VersionAt(ctx, "m", "a", branch, source)
if err != nil || found != (v != "") {
t.Fatalf("VersionAt %s.%d: %q %v %v", branch, source, v, found, err)
}
return v
}
if v := at("main", 41); v != "" {
t.Errorf("a reservation not yet published answers %q, want none", v)
}
if _, err := r.Built(ctx, "m", w.Version, "m:a", "sha256:cc", nil); err != nil {
t.Fatal(err)
}
if _, _, err := r.Published(ctx, "m/a", w.Version, "sha256:cc"); err != nil {
t.Fatal(err)
}
if v := at("main", 41); v != w.Version {
t.Errorf("the published reservation at main.41 answers %q, want %s", v, w.Version)
}
if v, v2 := at("main", 40), at("feat", 41); v != "" || v2 != "" {
t.Errorf("another source revision or branch answers %q %q, want none", v, v2)
}
if _, err := r.Released(ctx, "m", w.Version); err != nil {
t.Fatal(err)
}
if v := at("main", 41); v != w.Version {
t.Errorf("once released, main.41 answers %q, want %s from the release's record", v, w.Version)
}
// H-A-558 (2): the record keeps the origin's branch with its source revision, so another branch's equal number never meets it.
if v := at("feat", 41); v != "" {
t.Errorf("once released, feat.41 answers %q, want none", v)
}
// One key per module holds the last releases, the oldest dropped (A-456b).
for _, fp := range []string{"src2:b1", "src2:b2"} {
n, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp})
@@ -245,7 +272,7 @@ func TestPublishedAnswersByTheBuildFingerprint(t *testing.T) {
ctx := context.Background()
heard := time.Date(2026, 11, 21, 19, 0, 0, 0, time.UTC)
store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()}, ReleasedKept: 2, Filled: func() bool { return true },
r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()}, ReleasedKept: 2,
ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }, Now: func() time.Time { return heard }}
v, err := r.Reserve(ctx, "mesh-grants", "0.1", []string{"mesh-grants:busgrants", "mesh-grants:grantsstate"}, Source{Fingerprint: "src2:aa"})
if err != nil {
@@ -326,7 +353,7 @@ func TestTheWithdrawnVersionsAreDroppedOnceReleasedPast(t *testing.T) {
ctx := context.Background()
store := &reserveMem{mem: newMem()}
highest := "0.1.3"
r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()}, Filled: func() bool { return true },
r := &Reserver{Store: store, Releases: &reserveMem{mem: newMem()},
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{highest}, nil }}
for _, fp := range []string{"src2:a", "src2:b", "src2:c"} {
if _, err := r.Reserve(ctx, "m", "0.1", []string{"m:a"}, Source{Fingerprint: fp}); err != nil {
@@ -390,7 +417,7 @@ func TestARebuildReservesAboveTheCatalogsHighestWhateverItsStandingNumberWas(t *
} {
t.Run(c.name, func(t *testing.T) {
store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, Filled: func() bool { return true },
r := &Reserver{Store: store,
ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.16"}, nil }}
raw, _ := json.Marshal(ReservedVersion{V: 1, Module: "m", Series: "0.1", Version: c.standing, Fingerprint: c.standingFp, Artifacts: map[string]string{"m:a": "d"}})
if _, err := store.Create(ctx, ReservedKey("m", "0.1"), raw); err != nil {
@@ -12,17 +12,20 @@ import (
)
// TestReservedByNameAnswersFromTheViewAndTheCatalog: design 47 G §572, §582, A-70 — a package's name (an npm name or a Go
// module path) is mapped to its module from the catalog half's view; the reserved version answers as for the module, a version
// module path) is mapped to its module from the catalog half's entries (design 47 G §348); the reserved version answers as for the module, a version
// no reservation holds is asked of the catalog's versions and answers released with the release's digests, and a name no entry
// carries, one more than one carries, or a version neither reserved nor released answers error, set alone.
func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
ctx := context.Background()
view := packagesMem{
"git=2enovox=2ebe/novox/mesh-sdk/go.0.1": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.1"}`),
"git=2enovox=2ebe/novox/mesh-sdk/go.0.2": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.2"}`),
"@novox/mesh-sdk.0.1": []byte(`{"v":1,"name":"@novox/mesh-sdk","package":"mesh-sdk/ts","series":"0.1"}`),
"twice.0.1": []byte(`{"v":1,"name":"twice","package":"a/x","series":"0.1"}`),
"twice-b.0.1": []byte(`{"v":1,"name":"twice","package":"b/y","series":"0.1"}`),
pkg := func(ref, name string) meshcatalog.Artifact {
return meshcatalog.Artifact{Ref: ref, Kind: KindPackage, Package: &meshcatalog.ArtifactPackage{Name: name}}
}
entries := func() []meshcatalog.CatalogEntry {
return []meshcatalog.CatalogEntry{
{Module: "mesh-sdk", Artifacts: []meshcatalog.Artifact{pkg("mesh-sdk:go", "git.novox.be/novox/mesh-sdk/go"), pkg("mesh-sdk:ts", "@novox/mesh-sdk")}},
{Module: "a", Artifacts: []meshcatalog.Artifact{pkg("a:x", "twice")}},
{Module: "b", Artifacts: []meshcatalog.Artifact{pkg("b:y", "twice")}},
}
}
store := &reserveMem{mem: newMem()}
r := &Reserver{Store: store, ReleasedOf: func(context.Context, string) ([]string, error) { return []string{"0.1.3"}, nil }}
@@ -40,7 +43,7 @@ func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
asked = append(asked, module)
return []meshcatalog.VersionEntry{{Module: module, Version: "0.1.2", Artifacts: []meshcatalog.VersionArtifact{{Artifact: "mesh-sdk:go", Digest: "sha256:dd"}}}}, nil
}
carriers := Carriers(view)
carriers := CarriersFrom(entries)
ask := func(name, version string) meshbuilds.ReservedAnswer {
t.Helper()
got, err := AnswerReservedByName(ctx, rd, carriers, released, name, version)
@@ -81,7 +84,8 @@ func TestReservedByNameAnswersFromTheViewAndTheCatalog(t *testing.T) {
if got := ask("@novox/mesh-sdk", "9.9.9"); !strings.Contains(got.Error, "reserved or released") {
t.Errorf("a version never reserved = %+v, want refused as neither reserved nor released", got)
}
if _, err := AnswerReservedByName(ctx, rd, Carriers(packagesMem(nil)), released, "x", ""); err == nil {
unreadable := func(context.Context, string) ([]Built, error) { return nil, errors.New("down") }
if _, err := AnswerReservedByName(ctx, rd, unreadable, released, "x", ""); err == nil {
t.Error("an unreadable view was answered as if no entry carried the name")
}
if _, err := AnswerReservedByName(ctx, rd, carriers, func(context.Context, string) ([]meshcatalog.VersionEntry, error) { return nil, errors.New("down") }, "git.novox.be/novox/mesh-sdk/go", "0.1.2"); err == nil {
@@ -3,9 +3,7 @@ package versions
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
// AllFilter is the key filter of every version of every name: two tokens.
@@ -37,191 +35,3 @@ type Store interface {
// KeysOf are the keys under a filter (NameFilter, or AllFilter for every key).
KeysOf(ctx context.Context, filter string) ([]string, error)
}
// Versions is the builder's state.
type Versions struct {
Store Store
Now func() time.Time
}
// Of is every entry of name.
func (v Versions) Of(ctx context.Context, name string) ([]Entry, error) {
keys, err := v.Store.KeysOf(ctx, NameFilter(name))
if err != nil {
return nil, fmt.Errorf("the versions of %s cannot be listed: %w", name, err)
}
var out []Entry
for _, k := range keys {
raw, _, found, err := v.Store.Get(ctx, k)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
if !found {
continue
}
e, err := Decode(raw)
if err != nil {
return nil, fmt.Errorf("%s holds what is not a version: %w", k, err)
}
out = append(out, e)
}
return InOrder(out), nil
}
// Claim is one numbering asked of the builder.
type Claim struct {
Name, Kind, Series, Module, Fingerprint, Commit, Revision, Digest, Seat string
Merge uint64
Floor Floor
// Fresh numbers anew a fingerprint or revision already numbered: builder_publish_again after a published (design 51
// *Tools of the builder*).
Fresh bool
}
// Number numbers a claim under compare-and-set: two claims of one name never get one number, the second reading the
// first's key and taking the next (ADR 0606 §2). It answers the decision and, when it numbered or kept a version, its
// entry. Attempts are bounded by the claims the name can meet at once; a store that keeps conflicting is an error.
func (v Versions) Number(ctx context.Context, c Claim) (Decision, Entry, error) {
if c.Series == "" {
c.Series = DefaultSeries
}
for attempt := 0; attempt < 16; attempt++ {
entries, err := v.Of(ctx, c.Name)
if err != nil {
return Decision{}, Entry{}, err
}
d := Decide(fresh(entries, c), c.Kind, c.Series, c.Fingerprint, c.Revision, c.Floor)
if d.Version == "" {
return d, Entry{}, nil
}
if d.Keep {
for _, e := range entries {
if e.Version == d.Version {
return d, e, nil
}
}
}
e := Entry{Name: c.Name, Kind: c.Kind, Series: c.Series, Version: d.Version, Module: c.Module,
Fingerprint: c.Fingerprint, Commit: c.Commit, Revision: c.Revision, Digest: c.Digest, Seat: c.Seat,
State: Numbered, At: v.now(), Merge: c.Merge}
raw, err := Encode(e)
if err != nil {
return Decision{}, Entry{}, err
}
_, err = v.Store.Create(ctx, Key(c.Name, d.Version), raw)
if errors.Is(err, ErrConflict) {
continue // another claim took this number: read again and take the next
}
if err != nil {
return Decision{}, Entry{}, fmt.Errorf("%s@%s: %w", c.Name, d.Version, err)
}
return d, e, nil
}
return Decision{}, Entry{}, fmt.Errorf("%s: the versions kept changing under 16 claims", c.Name)
}
// ErrNotNumbered is a version the state versions does not hold (design 51's numbering by name): a version the reservation
// numbered (§369) is never held there.
var ErrNotNumbered = errors.New("not numbered by the builder")
// Mark moves one version to a new state by compare-and-set, as the holders' events say (published, refused, removed):
// change edits the entry read; a version the state does not hold is an error naming it.
func (v Versions) Mark(ctx context.Context, name, version string, change func(*Entry)) (Entry, error) {
key := Key(name, version)
for attempt := 0; attempt < 16; attempt++ {
raw, rev, found, err := v.Store.Get(ctx, key)
if err != nil {
return Entry{}, fmt.Errorf("%s: %w", key, err)
}
if !found {
return Entry{}, fmt.Errorf("%s@%s is %w", name, version, ErrNotNumbered)
}
e, err := Decode(raw)
if err != nil {
return Entry{}, fmt.Errorf("%s holds what is not a version: %w", key, err)
}
change(&e)
e.At = v.now()
out, err := Encode(e)
if err != nil {
return Entry{}, err
}
if _, err := v.Store.Update(ctx, key, out, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return Entry{}, fmt.Errorf("%s: %w", key, err)
}
return e, nil
}
return Entry{}, fmt.Errorf("%s@%s kept changing under 16 marks", name, version)
}
// Recorded is the holder's question through builder_versions (ADR 0605 §4): whether name, version and digest are a
// version the builder numbered. It answers the entry when they are, and why not otherwise.
func (v Versions) Recorded(ctx context.Context, name, version, digest string) (Entry, bool, string, error) {
raw, _, found, err := v.Store.Get(ctx, Key(name, version))
if err != nil {
return Entry{}, false, "", err
}
if !found {
return Entry{}, false, fmt.Sprintf("%s@%s is not a version the builder numbered", name, version), nil
}
e, err := Decode(raw)
if err != nil {
return Entry{}, false, "", err
}
switch {
case e.State == Removed:
return e, false, fmt.Sprintf("%s@%s was removed (%s)", name, version, e.Reason), nil
case e.Digest != "" && digest != "" && e.Digest != digest:
return e, false, fmt.Sprintf("%s@%s is recorded with digest %s, not %s", name, version, e.Digest, digest), nil
}
return e, true, "", nil
}
func (v Versions) now() time.Time {
if v.Now != nil {
return v.Now().UTC()
}
return time.Now().UTC()
}
// fresh is entries as Decide reads them for c: with Fresh, the entries of c's fingerprint and revision still count for the
// next number but keep none.
func fresh(entries []Entry, c Claim) []Entry {
if !c.Fresh {
return entries
}
out := make([]Entry, len(entries))
for i, e := range entries {
if e.Tag == "" && (e.Fingerprint == c.Fingerprint || (c.Revision != "" && e.Revision == c.Revision)) {
e.Fingerprint, e.Revision = "", ""
}
out[i] = e
}
return out
}
// All is every entry of every name, by name in order: what the versions' readers read.
func (v Versions) All(ctx context.Context) ([]Entry, error) {
keys, err := v.Store.KeysOf(ctx, AllFilter)
if err != nil {
return nil, fmt.Errorf("the versions cannot be listed: %w", err)
}
var out []Entry
for _, k := range keys {
raw, _, found, err := v.Store.Get(ctx, k)
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
if !found {
continue
}
e, err := Decode(raw)
if err != nil {
return nil, fmt.Errorf("%s holds what is not a version: %w", k, err)
}
out = append(out, e)
}
return out, nil
}
@@ -14,7 +14,6 @@ import (
const (
VersionsTool = "builder_versions"
PublishAgainTool = "builder_publish_again"
FloorAgainTool = "builder_floor_again"
OldFormTool = "builder_old_form"
// OldFormClosedEvent is the builder's own family `version`, kept seven days,
// apart from its builds' ends, so a waiter on a build's end does not wake on them.
@@ -76,10 +75,77 @@ func (r Reader) values(state string) (map[string]json.RawMessage, *StateCapped,
return out, nil, nil
}
// readStore is a Store over a Reader that refuses every write: the tools bundle only reads versions.
// VersionsAnswer is what builder_versions answers, from the reservations alone (design 47 H §756, G §372, §381): what the
// seat mesh-builds' verb reserved answers for the name, and, asked for a version and a digest, whether the reservation holds
// that version with that digest.
type VersionsAnswer struct {
Name string `json:"name"`
// Asked, Recorded and Why answer a holder's question for one version and digest (ADR 0605 §4).
Asked string `json:"asked,omitempty"`
Recorded *bool `json:"recorded,omitempty"`
Why string `json:"why,omitempty"`
// Reserved is what the seat mesh-builds' verb reserved answers for the name (and version): the reserved or released version
// with each artifact's digest, or its error (design 47 G §572, §582).
Reserved *meshbuilds.ReservedAnswer `json:"reserved,omitempty"`
}
// AnswerVersions is builder_versions: what the reservation answers for a name, read through reserve (the seat mesh-builds'
// verb reserved); with a version and a digest, recorded says whether that version is the one reserved or released and an
// artifact of it has that digest or none recorded yet, the question a registry seat's holder asks before it stores
// (ADR 0605 §4, design 47 G §381, A-490j).
func AnswerVersions(name, version, digest string, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) (VersionsAnswer, error) {
name, version, digest = strings.TrimSpace(name), strings.TrimSpace(version), strings.TrimSpace(digest)
if name == "" {
return VersionsAnswer{}, errors.New("name is required: the package, image, bundle or archive name")
}
if reserve == nil {
return VersionsAnswer{}, errors.New("the seat mesh-builds' reserved cannot be asked")
}
ra, err := reserve(name, version)
if err != nil {
return VersionsAnswer{}, fmt.Errorf("the seat mesh-builds' reserved did not answer for %s: %w", name, err)
}
out := VersionsAnswer{Name: name, Reserved: &ra}
if version == "" {
return out, nil
}
ok, why := recordedIn(ra, name, version, digest)
out.Asked, out.Recorded, out.Why = version, &ok, why
return out, nil
}
// recordedIn is whether the reservation answer ra holds name@version with digest, and why not.
func recordedIn(ra meshbuilds.ReservedAnswer, name, version, digest string) (bool, string) {
switch {
case ra.Error != "":
return false, ra.Error
case ra.Version != version:
return false, fmt.Sprintf("%s has no reservation of version %s of %s (it holds %s)", ra.Module, version, name, ra.Version)
}
var held []string
for _, a := range ra.Artifacts {
if a.Digest == digest || a.Digest == "" {
return true, ""
}
held = append(held, a.Digest)
}
if len(held) == 0 {
return false, fmt.Sprintf("%s holds %s@%s with no artifact, so no digest takes %s", ra.Module, name, version, digest)
}
return false, fmt.Sprintf("%s holds %s@%s for digest %s, not %s", ra.Module, name, version, strings.Join(held, ", "), digest)
}
// VersionsDescription is builder_versions' description.
const VersionsDescription = "A name's reservation, from the reservations alone (the numbering from before G is gone, design 47 H §756): " +
"what the seat mesh-builds' verb reserved answers for the package, image, bundle or archive name, the reserved or released version " +
"with each artifact's digest. With version, and digest, it also answers recorded: whether that version is the one reserved or " +
"released and an artifact of it has that digest (or none recorded yet), and why not: the question a registry seat's holder asks " +
"before it stores a publish (ADR 0605 §4). Read-only."
// readStore is a Store over a Reader that refuses every write: the tools bundle only reads the builder's states.
type readStore struct{ r Reader }
var errReadOnly = errors.New("the versions are written by the builder alone")
var errReadOnly = errors.New("the builder's states are written by the builder alone")
func (s readStore) Get(_ context.Context, key string) ([]byte, uint64, bool, error) {
v, ok, err := s.r.Get(key)
@@ -102,49 +168,3 @@ func (s readStore) KeysOf(_ context.Context, filter string) ([]string, error) {
}
return out, nil
}
// VersionsAnswer is what builder_versions answers.
type VersionsAnswer struct {
Name string `json:"name"`
Versions []Entry `json:"versions"`
// Asked, Recorded and Why answer a holder's question for one version and digest (ADR 0605 §4).
Asked string `json:"asked,omitempty"`
Recorded *bool `json:"recorded,omitempty"`
Why string `json:"why,omitempty"`
// Reserved is what the seat mesh-builds' verb reserved answers for the name (and version): the reserved or released version
// with each artifact's digest, or its error (design 47 G §572, §582).
Reserved *meshbuilds.ReservedAnswer `json:"reserved,omitempty"`
}
// AnswerVersions is builder_versions: a name's versions in order, in one call; with a version (and a digest), whether
// the builder numbered it with that digest, which the holder asks before it stores (ADR 0605 §4).
func AnswerVersions(ctx context.Context, r Reader, name, version, digest string) (VersionsAnswer, error) {
name = strings.TrimSpace(name)
if name == "" {
return VersionsAnswer{}, errors.New("name is required: the package, image, bundle or archive name")
}
v := Versions{Store: readStore{r}}
all, err := v.Of(ctx, name)
if err != nil {
return VersionsAnswer{}, err
}
out := VersionsAnswer{Name: name, Versions: all}
if out.Versions == nil {
out.Versions = []Entry{}
}
if version = strings.TrimSpace(version); version != "" {
_, ok, why, err := v.Recorded(ctx, name, version, strings.TrimSpace(digest))
if err != nil {
return VersionsAnswer{}, fmt.Errorf("%s@%s: %w", name, version, err)
}
out.Asked, out.Recorded, out.Why = version, &ok, why
}
return out, nil
}
// VersionsDescription is builder_versions' description.
const VersionsDescription = "A name's versions as the builder numbered them (its state versions, design 51): every trunk and tagged " +
"version of a package, image, bundle or archive in order, each with its kind, series, fingerprint, commit, source revision, digest, " +
"seat, state (numbered, published, refused with its reason, removed with its time, reason and the event that removed it, or kept: its seat kept it whole on remove, its digest shared, with the reason and the other tags naming it, kept_with) and when. " +
"With version, and digest, it also answers recorded: whether the builder numbered that version with that digest, and why not: the " +
"question a registry seat's holder asks before it stores a publish (ADR 0605 §4). Read-only."
@@ -1,46 +1,19 @@
// Package versions is the builder's state `versions` (novox/hq design 51 *The versions*, ADR 0606): one key per name,
// tag and version, written only by the builder under compare-and-set, read by others only through the builder's tool
// builder_versions or its events (ADR 0596 §2). It holds what each version is (its fingerprint, commit, source revision
// and digest) and where it stands: numbered, published, refused with its reason, or removed with its time, reason and the
// event that removed it.
//
// The state is declared in the builder's old `state` section (ADR 0619: the builder is one of the foundation's nine
// parts), history one; its cap is 64 MiB, the most the template state allows (ADR 0595 §3), and past 80 % of it the
// builder writes a finding, cleared below it (Fill).
// Package versions holds the builder's versions as the reservation numbers them (novox/hq design 47 G §369): the state
// reserved, its index and releases, the publish queue, the old form's window and the builder's bounds. The state versions
// numbered before G goes with its numbering (design 47 H §756); builder_versions answers from the reservations alone.
package versions
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
)
// State is the builder state's name; its bucket is `<module>_versions` of the credential's module.
const (
State = "versions"
// Cap is the bucket's cap in bytes (64 MiB); FullPercent the share of it past which the builder writes its finding.
Cap = 64 << 20
FullPercent = 80
// DefaultSeries is the series of a name whose manifest declares none (design 32).
DefaultSeries = "0.1"
)
// The states a version is in.
const (
Numbered = "numbered"
Published = "published"
Refused = "refused"
Removed = "removed"
// Kept is a tagged version its seat kept whole on remove: another tag names its digest, so the store cannot remove the
// tag alone (review round 2; the registry seats' `kept`). Its Reason is the seat's (shared-digest), KeptWith the
// other tags; it is asked no more.
Kept = "kept"
)
// The kinds the builder numbers: a package per source revision, the rest per fingerprint (design 51).
const (
KindPackage = "package"
@@ -49,82 +22,8 @@ const (
KindArchive = "archive"
)
// Entry is one key of the state: a version of a name, tagged or not.
type Entry struct {
Name string `json:"name"`
Kind string `json:"kind"`
Series string `json:"series"`
Version string `json:"version"`
// Tag is the cleaned tag of a tagged version (`feat-x`); empty for a trunk version.
Tag string `json:"tag,omitempty"`
Module string `json:"module"`
Fingerprint string `json:"fingerprint"`
Commit string `json:"commit,omitempty"`
// Revision is the source revision a package's version is numbered for (one version per revision, design 51).
Revision string `json:"revision,omitempty"`
// Digest is the digest the build recorded (an image's manifest, a blob's, Go's h1: hash).
Digest string `json:"digest,omitempty"`
// Seat is the registry seat it is published to.
Seat string `json:"seat,omitempty"`
State string `json:"state"`
At time.Time `json:"at"`
// Reason is why it was refused or removed: the holder's reason, a branch's end, retention, the sweep.
Reason string `json:"reason,omitempty"`
// Repository is a tagged version's repository: its branch's end removes it (Untagged).
Repository string `json:"repository,omitempty"`
// KeptWith are the other tags naming its digest, when its seat kept it (Kept).
KeptWith []string `json:"kept_with,omitempty"`
// RemovedBy is the id of the event that removed it.
RemovedBy string `json:"removed_by,omitempty"`
// RefusedDigest is the digest the holder refused: one other than Digest means the seat was offered other bytes under
// this number, which builder_publish_again refuses to publish again (design 51 *Tools of the builder*).
RefusedDigest string `json:"refused_digest,omitempty"`
// Merge is the forge bridge's sequence of the merge that numbered it, for merge order.
Merge uint64 `json:"merge,omitempty"`
}
// Valid says what is wrong with an entry, or nil.
func (e Entry) Valid() error {
switch {
case strings.TrimSpace(e.Name) == "":
return errors.New("a version names no name")
case e.Version == "":
return fmt.Errorf("%s: a version with no version", e.Name)
}
switch e.State {
case Numbered, Published, Refused, Removed, Kept:
default:
return fmt.Errorf("%s@%s: unknown state %q", e.Name, e.Version, e.State)
}
switch e.Kind {
case KindPackage, KindImage, KindBundle, KindArchive:
default:
return fmt.Errorf("%s@%s: unknown kind %q", e.Name, e.Version, e.Kind)
}
if _, _, err := SplitSeries(e.Series); err != nil {
return fmt.Errorf("%s@%s: %w", e.Name, e.Version, err)
}
return nil
}
// Encode and Decode are the value's bytes.
func Encode(e Entry) ([]byte, error) {
if err := e.Valid(); err != nil {
return nil, err
}
return json.Marshal(e)
}
func Decode(raw []byte) (Entry, error) {
var e Entry
if err := json.Unmarshal(raw, &e); err != nil {
return Entry{}, err
}
return e, e.Valid()
}
// Key is the state's key of a name's version: two tokens, the name and the version each escaped (EscapeToken), so a
// name's versions are the keys under NameFilter and no name's keys fall under another's.
// Key is a key of two tokens, a name and a version (or series) each escaped (EscapeToken), so a name's keys are the keys
// under NameFilter and no name's keys fall under another's.
func Key(name, version string) string { return EscapeToken(name) + "." + EscapeToken(version) }
// NameFilter is the key filter of every version of name.
@@ -181,174 +80,3 @@ func Patch(series, version string) (int, bool) {
}
return n, true
}
// Floor is what the three sources answered for a name (design 51 *The floor*, ADR 0606 §3): the seat's versions, the
// package's git tags (the seat git's tags) and the pseudo-versions consumers require (the catalog half's
// indexer_requirements). A source not answered is listed in Silent.
type Floor struct {
Seat []string `json:"seat,omitempty"`
Tags []string `json:"tags,omitempty"`
Requirements []string `json:"requirements,omitempty"`
// Silent names the sources that did not answer: "seat", "git.tags", "catalog.requirements".
Silent []string `json:"silent,omitempty"`
}
// The floor's sources, as Floor.Silent names them.
const (
SourceSeat = "seat"
SourceTags = "git.tags"
SourceRequirements = "catalog.requirements"
)
// Known is whether every source answered.
func (f Floor) Known() bool { return len(f.Silent) == 0 }
// Highest is the highest count of series the floor's three sources name, -1 when none names one. A pseudo-version
// (`v0.1.14-0.2026…-abc`) counts as the version below it was cut from, so its base (`0.1.13`) counts: Go orders it
// before `0.1.14`.
func (f Floor) Highest(series string) int {
high := -1
for _, list := range [][]string{f.Seat, f.Tags, f.Requirements} {
for _, v := range list {
n, ok := Patch(series, v)
if !ok {
n, ok = pseudoBase(series, v)
}
if ok && n > high {
high = n
}
}
}
return high
}
// pseudoBase is the count a Go pseudo-version stands on: `v0.1.14-0.<time>-<hash>` is cut after `v0.1.13`.
func pseudoBase(series, version string) (int, bool) {
version = strings.TrimPrefix(version, "v")
base, rest, ok := strings.Cut(version, "-")
if !ok || !strings.HasPrefix(rest, "0.") || strings.Count(rest, "-") != 1 {
return 0, false
}
n, ok := Patch(series, base)
if !ok || n == 0 {
return 0, false
}
return n - 1, true
}
// Next is the next trunk version of name in series: one above the highest of the trunk versions entries hold and the
// floor (design 51: a name with none starts at `<series>.0`).
func Next(entries []Entry, series string, floor Floor) string {
high := floor.Highest(series)
for _, e := range entries {
if e.Tag != "" || e.Series != series {
continue
}
if n, ok := Patch(series, e.Version); ok && n > high {
high = n
}
}
return fmt.Sprintf("%s.%d", series, high+1)
}
// Decision is what the builder does with a trunk build at its claim.
type Decision struct {
// Version is the version the build is published under; empty when it is built unnumbered (Unnumbered) or waits (Wait).
Version string
// Keep is true when the version is one entries already hold for this fingerprint or source revision.
Keep bool
// Publish is false only for a package's revision held published: it publishes nothing (design 51).
Publish bool
// Unnumbered: an image, bundle or archive whose floor is not known is built and published by its digest, numbered
// once the floor answers (ADR 0617 §1).
Unnumbered bool
// Wait: a package whose floor is not known waits for it (a package is published only under its version).
Wait bool
// Why is said in the build log.
Why string
}
// Decide numbers a trunk build of kind for name in series at fingerprint and source revision, from what entries hold of
// the name and what the floor answered (design 51 *The versions*, ADR 0606, ADR 0617 §1):
// - a package is numbered per source revision: a revision held published keeps its version and publishes nothing; a
// revision numbered or refused but never stored is published again under the same version;
// - an image, bundle or archive is numbered per fingerprint: a fingerprint already numbered keeps its number;
// - otherwise the next version, when the floor is known; else an image, bundle or archive is built unnumbered and a
// package waits.
func Decide(entries []Entry, kind, series, fingerprint, revision string, floor Floor) Decision {
for _, e := range latestFirst(entries) {
if e.Tag != "" || e.State == Removed {
continue
}
switch {
case kind == KindPackage && revision != "" && e.Revision == revision:
if e.State == Published {
return Decision{Version: e.Version, Keep: true, Why: fmt.Sprintf("version %s kept: source revision %s is published under it, and a package's content is its source", e.Version, revision)}
}
return Decision{Version: e.Version, Keep: true, Publish: true, Why: fmt.Sprintf("version %s kept: source revision %s was numbered %s but never stored, so it is published under it", e.Version, revision, e.State)}
case kind != KindPackage && e.Fingerprint == fingerprint:
return Decision{Version: e.Version, Keep: true, Publish: e.State != Published, Why: fmt.Sprintf("version %s kept: fingerprint %s is numbered under it", e.Version, fingerprint)}
}
}
if !floor.Known() {
silent := strings.Join(floor.Silent, ", ")
if kind == KindPackage {
return Decision{Wait: true, Why: "the package waits for its floor: " + silent + " did not answer"}
}
return Decision{Unnumbered: true, Publish: true, Why: "built unnumbered and published by its digest: the floor is not known (" + silent + " did not answer); numbered once it answers"}
}
v := Next(entries, series, floor)
return Decision{Version: v, Publish: true, Why: "numbered " + v}
}
// Fill is whether a bucket holding bytes of cap is past its finding's mark.
func Fill(bytes, capacity uint64) (share float64, full bool) {
if capacity == 0 {
return 0, false
}
share = float64(bytes) / float64(capacity)
return share, bytes*100 >= capacity*FullPercent
}
// InOrder sorts a name's entries by version, trunk versions by count and tagged ones after the trunk version they stand
// below: the order builder_versions answers.
func InOrder(entries []Entry) []Entry {
out := append([]Entry(nil), entries...)
sort.SliceStable(out, func(i, j int) bool {
ki, kj := orderKey(out[i]), orderKey(out[j])
if ki.n != kj.n {
return ki.n < kj.n
}
if ki.tagged != kj.tagged {
return ki.tagged // a tagged version stands below the trunk version of its count
}
return out[i].Version < out[j].Version
})
return out
}
type order struct {
n int
tagged bool
}
func orderKey(e Entry) order {
v := e.Version
tagged := false
if i := strings.IndexByte(v, '-'); i >= 0 {
v, tagged = v[:i], true
}
n, ok := Patch(e.Series, v)
if !ok {
n = -1
}
return order{n: n, tagged: tagged}
}
func latestFirst(entries []Entry) []Entry {
out := InOrder(entries)
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return out
}
@@ -3,16 +3,14 @@ package versions
import (
"context"
"encoding/json"
"errors"
"maps"
"reflect"
"slices"
"strings"
"sync"
"testing"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds/forms"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
)
// mem is a Store in memory; before runs once before the next Create, to stage a race.
@@ -75,39 +73,6 @@ func (m *mem) KeysOf(_ context.Context, filter string) ([]string, error) {
return out, nil
}
// keeperMem is the state floor-waits in memory.
type keeperMem map[string][]byte
func (k keeperMem) Put(key string, v []byte) error { k[key] = v; return nil }
func (k keeperMem) Delete(key string) error { delete(k, key); return nil }
func (k keeperMem) keys() ([]string, error) {
var out []string
for key := range k {
out = append(out, key)
}
return out, nil
}
func (k keeperMem) get(key string) (json.RawMessage, bool, error) { v, ok := k[key]; return v, ok, nil }
// packagesMem is the indexer's packages state as the builder reads it, in memory.
type packagesMem map[string][]byte
func (p packagesMem) Keys(context.Context) ([]string, error) {
if p == nil {
return nil, errors.New("not readable")
}
return slices.Collect(maps.Keys(p)), nil
}
func (p packagesMem) Get(_ context.Context, key string) ([]byte, bool, error) {
v, ok := p[key]
return v, ok, nil
}
func (p packagesMem) failing() packagesMem { return nil }
func known(seat, tags, reqs []string) Floor { return Floor{Seat: seat, Tags: tags, Requirements: reqs} }
// TestTheBuildersVersions holds design 51 *The versions*, *The floor* and *Tagged versions* (DLV-B1, DLV-B2, DLV-B3):
// one table per rule, the unit cases of the builder's numbering.
func TestTheBuildersVersions(t *testing.T) {
@@ -128,184 +93,42 @@ func TestTheBuildersVersions(t *testing.T) {
}
}
})
t.Run("floor", func(t *testing.T) {
for _, c := range []struct {
name string
floor Floor
want string
}{
{"none starts at 0", known(nil, nil, nil), "0.1.0"},
{"the Go tag of today gives v0.1.14", known(nil, []string{"go/v0.1.13"}, []string{"v0.1.14-0.20261103221822-85ba0a9a70d8"}), "0.1.14"},
{"npm's 0.1.17 on the seat gives 0.1.18", known([]string{"0.1.17", "0.1.3"}, nil, nil), "0.1.18"},
{"another series and a tagged version count nothing", known([]string{"0.2.40", "0.1.9-feat-x.1"}, nil, nil), "0.1.0"},
{"the highest of the three", known([]string{"0.1.4"}, []string{"v0.1.9"}, []string{"v0.1.7"}), "0.1.10"},
} {
if got := Next(nil, "0.1", c.floor); got != c.want {
t.Errorf("%s: Next = %s, want %s", c.name, got, c.want)
}
}
if got := Next([]Entry{{Version: "0.1.20", Series: "0.1"}, {Version: "0.1.21-x.1", Series: "0.1", Tag: "x"}}, "0.1", known([]string{"0.1.3"}, nil, nil)); got != "0.1.21" {
t.Errorf("Next above the state's own = %s, want 0.1.21", got)
}
})
t.Run("decide", func(t *testing.T) {
pub := Entry{Name: "n", Kind: KindPackage, Series: "0.1", Version: "0.1.5", Revision: "r1", Fingerprint: "fA", State: Published}
ref := pub
ref.State, ref.Version, ref.Revision = Refused, "0.1.6", "r2"
img := Entry{Name: "i", Kind: KindBundle, Series: "0.1", Version: "0.1.2", Fingerprint: "fB", State: Published}
silent := Floor{Silent: []string{SourceSeat}}
for _, c := range []struct {
name string
entries []Entry
kind, fp, rev string
floor Floor
version string
keep, publish, unnum bool
wait bool
}{
{"a package's revision held published keeps its version and publishes nothing", []Entry{pub}, KindPackage, "fX", "r1", silent, "0.1.5", true, false, false, false},
{"a revision numbered but refused is published by its second build under the same version", []Entry{pub, ref}, KindPackage, "fY", "r2", known(nil, nil, nil), "0.1.6", true, true, false, false},
{"a new revision takes the next", []Entry{pub, ref}, KindPackage, "fZ", "r3", known(nil, nil, nil), "0.1.7", false, true, false, false},
{"a bundle's fingerprint keeps its number", []Entry{img}, KindBundle, "fB", "", silent, "0.1.2", true, false, false, false},
{"an unknown floor builds a bundle unnumbered", nil, KindBundle, "fC", "", silent, "", false, true, true, false},
{"an unknown floor builds an image unnumbered", nil, KindImage, "fC", "", silent, "", false, true, true, false},
{"an unknown floor makes a package wait", nil, KindPackage, "fC", "r9", silent, "", false, false, false, true},
} {
d := Decide(c.entries, c.kind, "0.1", c.fp, c.rev, c.floor)
if d.Version != c.version || d.Keep != c.keep || d.Publish != c.publish || d.Unnumbered != c.unnum || d.Wait != c.wait || d.Why == "" {
t.Errorf("%s: Decide = %+v", c.name, d)
}
}
})
t.Run("two claims never one number", func(t *testing.T) {
st := newMem()
v := Versions{Store: st, Now: func() time.Time { return time.Unix(0, 0) }}
ctx := context.Background()
st.before = func() { // a second claim takes 0.1.0 between the first's read and its create
if _, _, err := (Versions{Store: st}).Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f2"}); err != nil {
t.Error(err)
}
}
d, e, err := v.Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f1"})
if err != nil || d.Version != "0.1.1" || e.State != Numbered || e.Series != DefaultSeries {
t.Fatalf("Number = %+v, %+v, %v, want 0.1.1 after the other claim's 0.1.0", d, e, err)
}
if d, _, _ := v.Number(ctx, Claim{Name: "n", Kind: KindBundle, Fingerprint: "f1"}); !d.Keep || d.Version != "0.1.1" {
t.Errorf("a numbered fingerprint claimed again = %+v, want it kept", d)
}
got, err := v.Mark(ctx, "n", "0.1.1", func(e *Entry) { e.State = Published })
if err != nil || got.State != Published {
t.Errorf("Mark = %+v, %v", got, err)
}
if _, err := v.Mark(ctx, "n", "0.9.9", func(*Entry) {}); err == nil {
t.Error("marking a version never numbered is no error")
}
})
t.Run("recorded", func(t *testing.T) {
st := newMem()
v := Versions{Store: st}
ctx := context.Background()
if _, _, err := v.Number(ctx, Claim{Name: "n", Kind: KindImage, Fingerprint: "f", Digest: "sha256:aa", Floor: known(nil, nil, nil)}); err != nil {
t.Fatal(err)
t.Run("builder_versions answers from the reservations alone", func(t *testing.T) { // B1/AC2 (DMC-5: design 47 H §756, G §372)
asked := ""
reserve := func(name, version string) (meshbuilds.ReservedAnswer, error) {
asked = name + "@" + version
return meshbuilds.ReservedAnswer{Module: "m", Version: "0.1.4", Artifacts: []meshbuilds.ReservedAnswerArtifactsItem{
{Artifact: "m:program", Digest: "sha256:aa"}}}, nil
}
for _, c := range []struct {
version, digest string
ok bool
}{{"0.1.0", "sha256:aa", true}, {"0.1.0", "sha256:bb", false}, {"0.1.7", "sha256:aa", false}} {
if _, ok, why, err := v.Recorded(ctx, "n", c.version, c.digest); err != nil || ok != c.ok || (!ok && why == "") {
t.Errorf("Recorded(%s, %s) = %v, %q, %v; want %v", c.version, c.digest, ok, why, err, c.ok)
}{{"0.1.4", "sha256:aa", true}, {"0.1.4", "sha256:bb", false}, {"0.1.7", "sha256:aa", false}} {
a, err := AnswerVersions("m/program", c.version, c.digest, reserve)
if err != nil || a.Recorded == nil || *a.Recorded != c.ok || (!c.ok && a.Why == "") || a.Reserved == nil || asked != "m/program@"+c.version {
t.Errorf("builder_versions(%s, %s) = %+v, %v, asked %s; want recorded %v from the reservation", c.version, c.digest, a, err, asked, c.ok)
}
}
// builder_versions answers the same through the tools bundle's read-only view.
r := Reader{Keys: func() ([]string, error) {
var all []string
for k := range st.vals {
all = append(all, k)
}
return all, nil
}, Get: func(k string) (json.RawMessage, bool, error) {
v, _, ok, err := st.Get(ctx, k)
return v, ok, err
}}
a, err := AnswerVersions(ctx, r, "n", "0.1.0", "sha256:bb")
if err != nil || len(a.Versions) != 1 || a.Recorded == nil || *a.Recorded || a.Why == "" {
t.Errorf("builder_versions = %+v, %v; want one version and not recorded for another digest", a, err)
// A digest not recorded yet takes the publish (A-490j); a name the reservation does not know is a no naming it.
unbuilt := func(string, string) (meshbuilds.ReservedAnswer, error) {
return meshbuilds.ReservedAnswer{Module: "m", Version: "0.1.5", Artifacts: []meshbuilds.ReservedAnswerArtifactsItem{{Artifact: "m:program"}}}, nil
}
if _, err := AnswerVersions(ctx, r, " ", "", ""); err == nil {
if a, _ := AnswerVersions("m/program", "0.1.5", "sha256:cc", unbuilt); a.Recorded == nil || !*a.Recorded {
t.Errorf("an artifact with no digest recorded yet = %+v, want recorded", a)
}
unknown := func(string, string) (meshbuilds.ReservedAnswer, error) {
return meshbuilds.ReservedAnswer{Error: "no entry carries the name x"}, nil
}
if a, _ := AnswerVersions("x", "0.1.0", "sha256:aa", unknown); a.Recorded == nil || *a.Recorded || !strings.Contains(a.Why, "no entry carries") {
t.Errorf("a name no entry carries = %+v, want not recorded naming it", a)
}
if a, err := AnswerVersions("m/program", "", "", reserve); err != nil || a.Recorded != nil || a.Reserved == nil {
t.Errorf("builder_versions with no version = %+v, %v; want the reservation alone", a, err)
}
if _, err := AnswerVersions(" ", "", "", reserve); err == nil {
t.Error("builder_versions with no name answered")
}
})
t.Run("the floor wakes on its silent source, never a timer", func(t *testing.T) {
ctx := context.Background()
src := FloorSources{
Seat: func(context.Context, string, string) ([]string, error) { return []string{"0.1.3"}, nil },
Tags: func(context.Context, string, string) ([]string, error) { return nil, errors.New("no answer") },
Requirements: func(context.Context, string) ([]string, error) { return nil, nil },
}
f, why := src.Ask(ctx, FloorOf{Seat: "oci-artifact-registry", Name: "m/program"})
if f.Known() || !reflect.DeepEqual(f.Silent, []string{SourceTags}) || why[SourceTags] != "no answer" {
t.Fatalf("Ask = %+v, %v; want git.tags silent", f, why)
}
holders := map[string]string{SourceSeats[SourceTags]: "mesh-delivery-forge-bridge", SourceSeats[SourceRequirements]: "mesh-delivery-indexer"}
fw := FloorWaits{Holder: func(seat string) (string, bool) { h, ok := holders[seat]; return h, ok }}
w := fw.Wait("m/program", "oci-artifact-registry", "distribution", f, why, time.Unix(0, 0))
if !strings.Contains(w.Finding(), "git.tags (no answer)") {
t.Errorf("finding = %q", w.Finding())
}
for _, c := range []struct {
kind, seat, module, name string
want []string
}{
{WakePublished, "oci-artifact-registry", "", "", nil}, // the seat answered already: a publish wakes nothing
{WakeTakenIn, "", "", "", nil},
{WakeRevision, "", "", "", []string{"m/program"}},
{WakeCleared, "", "mesh-delivery-forge-bridge", "", []string{"m/program"}}, // recovered with nothing to say
{WakeCleared, "", "mesh-delivery-indexer", "", nil},
{WakeByHand, "", "", "m/program", []string{"m/program"}},
{WakeByHand, "", "", "other", nil},
} {
if got := fw.Wake(c.kind, c.seat, c.module, c.name); !reflect.DeepEqual(got, c.want) {
t.Errorf("Wake(%s %s %s %s) = %v, want %v", c.kind, c.seat, c.module, c.name, got, c.want)
}
}
seatDown := Floor{Silent: []string{SourceSeat}}
fw.Wait("distribution/program", "container-image-registry", "distribution", seatDown, nil, time.Unix(0, 0))
if got := fw.Wake(WakePublished, "container-image-registry", "", ""); !reflect.DeepEqual(got, []string{"distribution/program"}) {
t.Errorf("the holder's published woke %v, want its own image's name", got)
}
if got := fw.Wake(WakeCleared, "", "distribution", ""); !reflect.DeepEqual(got, []string{"distribution/program"}) {
t.Errorf("the holder's clear woke %v", got)
}
if !fw.Answered("m/program") || fw.Answered("m/program") || len(fw.Waiting()) != 1 {
t.Error("Answered drops the wait once")
}
// DLV-B4: the waits are kept in floor-waits; a restarted builder takes them in, and its sources' events still wake them.
kept := keeperMem{}
restarted := &FloorWaits{}
restarted.Keep(kept, []FloorWait{{Name: "m/held", Seat: SeatImages, Silent: []string{SourceTags}, Since: time.Unix(5, 0)}})
if got := restarted.Wake(WakeRevision, "", "", ""); !reflect.DeepEqual(got, []string{"m/held"}) {
t.Errorf("a wait held in floor-waits woke %v after a restart, want m/held", got)
}
restarted.Wait("m/new", SeatNPM, "", Floor{Silent: []string{SourceSeat}}, nil, time.Unix(9, 0))
ans, err := AnswerFloorWaits(Reader{Keys: kept.keys, Get: kept.get})
if err != nil || len(ans.Waits) != 2 || ans.Waits[0].Name != "m/held" || ans.Waits[1].Name != "m/new" || !strings.Contains(ans.Waits[1].Finding, "seat did not answer") {
t.Fatalf("builder_floor_waits = %+v, %v", ans, err)
}
restarted.Answered("m/held")
if _, ok := kept[FloorWaitKey("m/held")]; ok {
t.Error("an answered floor stays in floor-waits")
}
// The lead's ruling (review round 1): builder_bounds lists each key of the state bounds with what it bounds and
// when it ends.
at := time.Date(2026, 11, 4, 17, 0, 0, 0, time.UTC)
bounds := keeperMem{PublishBoundKey("m/program", "0.1.4"): EncodeBound("the publish of m/program@0.1.4 to oci-artifact-registry", at.Add(PublishBound)),
OldFormBoundKey("g14"): EncodeBound("the seven days g14 holds the old form's window", at.Add(FindingAfter))}
rows, err := AnswerBounds(Reader{Keys: bounds.keys, Get: bounds.get}, at)
if err != nil || len(rows) != 2 || rows[0].Key != OldFormBoundKey("g14") || rows[1].Left != "10m0s" ||
!strings.Contains(rows[1].Bounds, "m/program@0.1.4") || !rows[0].Ends.Equal(at.Add(FindingAfter)) {
t.Fatalf("builder_bounds = %+v, %v", rows, err)
}
})
t.Run("old form", func(t *testing.T) {
// One kind, a first form and a newer one.
fs := forms.ArtifactForms{{Name: "registry", First: true, Kinds: []string{"image"}}, {Name: "oci", Kinds: []string{"image"}}}
@@ -368,221 +191,4 @@ func TestTheBuildersVersions(t *testing.T) {
t.Error("a closed window closes again: old-form-closed would be said twice")
}
})
t.Run("at the claim", func(t *testing.T) {
ctx := context.Background()
tagsUp := false
var asked []string
src := FloorSources{
Seat: func(context.Context, string, string) ([]string, error) { return []string{"0.1.3"}, nil },
Tags: func(_ context.Context, repo, prefix string) ([]string, error) {
asked = append(asked, repo+" "+prefix)
if !tagsUp {
return nil, errors.New("no answer")
}
return []string{"go/v0.1.13"}, nil
},
Requirements: func(context.Context, string) ([]string, error) { return nil, nil },
}
fw := &FloorWaits{}
n := &Numberer{Versions: Versions{Store: newMem()}, Floor: src, Waits: fw}
c := BuildClaim{Module: "m", Path: "go", Repository: "novox/m", Fingerprint: "fp1", Commit: "c1", Revision: "7", Merge: 7,
Artifacts: []ClaimArtifact{{Artifact: "program", Kind: KindBundle, Language: "go"}, {Artifact: "base", Kind: "upstream"}}}
got, err := n.Number(ctx, c)
if err != nil || len(got.Versions) != 0 || !reflect.DeepEqual(got.Unnumbered, []string{"program"}) || got.Wait != "" {
t.Fatalf("silent floor: %+v, %v; want program unnumbered, the upstream copy left out", got, err)
}
if !reflect.DeepEqual(asked, []string{"novox/m go/v"}) || len(fw.Waiting()) != 1 {
t.Fatalf("asked %v, waits %+v", asked, fw.Waiting())
}
pkg := c
pkg.Artifacts = []ClaimArtifact{{Artifact: "lib", Kind: KindPackage, Language: "go"}}
if got, _ := n.Number(ctx, pkg); got.Wait == "" || len(got.Versions) != 0 {
t.Fatalf("a package with no floor = %+v; want it to wait", got)
}
tagsUp = true
got, err = n.Number(ctx, c)
if err != nil || got.Versions["program"] != "0.1.14" || len(fw.Waiting()) != 1 {
t.Fatalf("floor answered: %+v, %v, waits %+v; want 0.1.14, lib still waiting", got, err, fw.Waiting())
}
got, _ = n.Number(ctx, c)
var publishing []string // review round 1: a version built and still numbered arms its publish bound
n.Publishing = func(_ context.Context, e Entry) { publishing = append(publishing, e.Name+"@"+e.Version) }
if err := n.Built(ctx, c, got, map[string]string{"program": "sha256:aa"}); err != nil {
t.Fatal(err)
}
if n.Publishing = nil; !reflect.DeepEqual(publishing, []string{"m/program@0.1.14"}) {
t.Fatalf("the publish bounds armed: %v, want m/program@0.1.14", publishing)
}
again, _ := n.Number(ctx, c)
if again.Versions["program"] != "0.1.14" || len(asked) != 3 {
t.Fatalf("again: %+v, asked %v; want the number kept, the floor not asked", again, asked)
}
if _, ok, why, _ := n.Versions.Recorded(ctx, "m/program", "0.1.14", "sha256:bb"); ok {
t.Fatalf("another digest recorded: %s", why)
}
// DLV-B4: the seat's events move the entry; a published wakes the names waiting on that seat.
if wake, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e1", Outcome{Name: "m/other", Digest: "sha256:cc"}); err != nil || len(wake) != 0 {
t.Fatalf("a by-digest publish of another seat's wait: %v, %v", wake, err)
}
n.Waits.Wait("m/lib", SeatGoPackages, "", Floor{Silent: []string{SourceSeat}}, nil, time.Unix(0, 0))
if wake, _ := n.Heard(ctx, SeatGoPackages, HeardPublished, "e2", Outcome{Name: "m/x", Digest: "sha256:dd"}); !reflect.DeepEqual(wake, []string{"m/lib"}) {
t.Fatalf("a published on the Go seat woke %v, want m/lib, whose seat was silent", wake)
}
// Design 47 G §369, A-415; ADR 0605 §4: a published of other bytes under the number is the reservation's, never this entry's.
if _, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e5", Outcome{Name: "m/program", Version: "0.1.14", Digest: "sha256:new"}); !errors.Is(err, ErrNotNumbered) {
t.Fatalf("a published of other bytes under 0.1.14: %v, want ErrNotNumbered", err)
}
if all, _ := n.Versions.Of(ctx, "m/program"); all[0].State != Numbered || all[0].Digest != "sha256:aa" {
t.Fatalf("after a published of other bytes: %+v, want it numbered with sha256:aa", all[0])
}
for _, h := range []struct{ event, state, reason string }{{HeardRefused, Refused, "bytes differ"}, {HeardPublished, Published, ""}, {HeardRefused, Published, ""}, {HeardRemoved, Removed, "retention"}} {
if _, err := n.Heard(ctx, SeatArtifacts, h.event, "e3", Outcome{Name: "m/program", Version: "0.1.14", Digest: "sha256:aa", Reason: h.reason}); err != nil {
t.Fatal(err)
}
all, _ := n.Versions.Of(ctx, "m/program")
if all[0].State != h.state {
t.Fatalf("after %s: %+v, want %s", h.event, all[0], h.state)
}
}
if _, err := n.Heard(ctx, SeatArtifacts, HeardPublished, "e4", Outcome{Name: "m/none", Version: "0.1.0"}); err == nil {
t.Fatal("a published of a version the builder never numbered is not said")
}
// D-B5 (ADR 0666 §15, design 51 *The versions* line 287): a package's build whose published versions cannot be read
// is refused, naming the state; a bundle's is built as before (ADR 0617 §1), the error said.
st := n.Versions.Store.(*mem)
st.down = errors.New("nats: no responders available for request")
if got, err := n.Number(ctx, pkg); err != nil || !strings.Contains(got.Refused, "state versions cannot be read") || len(got.Versions) != 0 {
t.Errorf("a package with its versions unread = %+v, %v; want refused naming the state", got, err)
}
if got, err := n.Number(ctx, c); err == nil || got.Refused != "" {
t.Errorf("a bundle with its versions unread = %+v, %v; want the error, no refusal", got, err)
}
st.down = nil
})
t.Run("a package is numbered under its name in its ecosystem", func(t *testing.T) {
// design 32: the indexer's packages state names, in each series key, the package's name and the <module>/<artifact>
// it is built from; the builder numbers, asks the floor of and records the package under that name.
ctx := context.Background()
state := packagesMem{
"git=2enovox=2ebe/novox/mesh-sdk/go.0.1": []byte(`{"v":1,"name":"git.novox.be/novox/mesh-sdk/go","package":"mesh-sdk/go","series":"0.1"}`),
"@novox/mesh-sdk.0.1": []byte(`{"v":1,"name":"@novox/mesh-sdk","package":"mesh-sdk/ts","series":"0.1"}`),
"git=2enovox=2ebe/novox/mesh-sdk/go": []byte(`{"v":1,"module":"git.novox.be/novox/mesh-sdk/go"}`),
"broken.0.1": []byte(`not json`),
}
var floorOf []string
src := FloorSources{
Seat: func(_ context.Context, _, name string) ([]string, error) {
floorOf = append(floorOf, name)
return []string{"0.1.3"}, nil
},
Tags: func(context.Context, string, string) ([]string, error) { return nil, nil },
Requirements: func(_ context.Context, name string) ([]string, error) {
floorOf = append(floorOf, name)
return nil, nil
},
}
n := &Numberer{Versions: Versions{Store: newMem()}, Floor: src, Names: NamesIn(state)}
c := BuildClaim{Module: "mesh-sdk", Path: "go", Repository: "novox/mesh-sdk", Fingerprint: "fp1", Commit: "c1", Revision: "3", Merge: 3,
Artifacts: []ClaimArtifact{{Artifact: "go", Kind: KindPackage, Language: "go"}, {Artifact: "ts", Kind: KindPackage, Language: "typescript"},
{Artifact: "new", Kind: KindPackage, Language: "go"}, {Artifact: "program", Kind: KindBundle, Language: "go"}}}
got, err := n.Number(ctx, c)
if err != nil || got.Versions["go"] != "0.1.4" || got.Versions["ts"] != "0.1.4" || !reflect.DeepEqual(got.Unnumbered, []string{"new"}) {
t.Fatalf("Number = %+v, %v; want go and ts numbered, new unnumbered (no name yet)", got, err)
}
if got.Names["go"] != "git.novox.be/novox/mesh-sdk/go" || got.Names["ts"] != "@novox/mesh-sdk" || got.Names["program"] != "mesh-sdk/program" {
t.Errorf("names = %v", got.Names)
}
if !slices.Contains(floorOf, "git.novox.be/novox/mesh-sdk/go") || slices.Contains(floorOf, "mesh-sdk/go") {
t.Errorf("the floor was asked of %v, want the Go module path", floorOf)
}
if es, _ := n.Versions.Of(ctx, "git.novox.be/novox/mesh-sdk/go"); len(es) != 1 || es[0].Version != "0.1.4" {
t.Errorf("versions of the Go module path = %+v", es)
}
if es, _ := n.Versions.Of(ctx, "mesh-sdk/go"); len(es) != 0 {
t.Errorf("numbered under the builder's name too: %+v", es)
}
if err := n.Built(ctx, c, got, map[string]string{"go": "sha256:aa"}); err != nil {
t.Fatal(err)
}
if es, _ := n.Versions.Of(ctx, "git.novox.be/novox/mesh-sdk/go"); len(es) != 1 || es[0].Digest != "sha256:aa" {
t.Errorf("the built digest is not recorded under the name: %+v", es)
}
// The indexer writes the name of `new` later: its series key names the module, and the look at the done build
// numbers it with the done key's digest; the rest are kept.
state["new.0.1"] = []byte(`{"v":1,"name":"new","package":"mesh-sdk/new","series":"0.1"}`)
for key, want := range map[string]string{"new.0.1": "mesh-sdk", "git=2enovox=2ebe/novox/mesh-sdk/go": "", "broken.0.1": ""} {
if module, name, ok := NamedModule(key, state[key]); module != want || ok != (want != "") || (ok && name != "new") {
t.Errorf("NamedModule(%s) = %q, %q, %v, want %q", key, module, name, ok, want)
}
}
done := c
done.Done = map[string]string{"go": "sha256:aa", "new": "sha256:bb"}
late, err := n.Number(ctx, done)
if err != nil || late.Versions["new"] != "0.1.4" || late.Versions["go"] != "0.1.4" || len(late.Unnumbered) != 0 {
t.Fatalf("a look at the done build = %+v, %v; want new numbered and go kept", late, err)
}
if es, _ := n.Versions.Of(ctx, "new"); len(es) != 1 || es[0].Digest != "sha256:bb" {
t.Errorf("versions of new = %+v, want its done digest recorded", es)
}
if _, _, err := NamesIn(packagesMem(nil).failing())(ctx, "m", "a"); err == nil {
t.Error("a packages state that cannot be read is no error")
}
// A packages state not on the bus yet leaves the package unnumbered, said, and numbers the rest of the claim.
n.Names = NamesIn(packagesMem(nil).failing())
bare, err := n.Number(ctx, c)
if err != nil || !reflect.DeepEqual(bare.Unnumbered, []string{"go", "new", "ts"}) || bare.Versions["program"] == "" ||
!strings.Contains(bare.Said[0].Line, "cannot be read") {
t.Errorf("an unreadable packages state: %+v, %v", bare, err)
}
})
t.Run("fill", func(t *testing.T) {
if _, full := Fill(Cap*79/100, Cap); full {
t.Error("79 % is full")
}
if _, full := Fill((Cap*80+99)/100, Cap); !full {
t.Error("80 % is not full")
}
})
t.Run("fresh claims and the floor", func(t *testing.T) {
ctx := context.Background()
// A fresh claim of a published fingerprint takes the next number; the old one stays.
st := newMem()
v := Versions{Store: st}
raw, _ := Encode(Entry{Name: "m/p", Kind: KindBundle, Series: "0.1", Version: "0.1.3", Fingerprint: "f1", State: Published, At: time.Unix(1, 0)})
_, _ = st.Create(ctx, Key("m/p", "0.1.3"), raw)
if d, _, err := v.Number(ctx, Claim{Name: "m/p", Kind: KindBundle, Fingerprint: "f1"}); err != nil || d.Version != "0.1.3" || !d.Keep {
t.Fatalf("a published fingerprint keeps its number: %+v %v", d, err)
}
if d, e, err := v.Number(ctx, Claim{Name: "m/p", Kind: KindBundle, Fingerprint: "f1", Fresh: true}); err != nil || d.Version != "0.1.4" || d.Keep || e.Fingerprint != "f1" {
t.Fatalf("a fresh claim takes the next number: %+v %+v %v", d, e, err)
}
// A refusal records the digest refused; Built replaces a digest no published was said for, never a published one.
n := &Numberer{Versions: v}
_, _ = n.Heard(ctx, SeatArtifacts, HeardRefused, "r1", Outcome{Name: "m/p", Version: "0.1.4", Digest: "sha256:old", Reason: "x"})
if es, _ := v.Of(ctx, "m/p"); es[1].RefusedDigest != "sha256:old" {
t.Errorf("refused records no digest: %+v", es[1])
}
_, _ = v.Mark(ctx, "m/p", "0.1.4", func(e *Entry) { e.Digest = "sha256:old" })
bc := BuildClaim{Module: "m"}
_ = n.Built(ctx, bc, Numbering{Versions: map[string]string{"p": "0.1.4"}}, map[string]string{"p": "sha256:new"})
_, _ = v.Mark(ctx, "m/p", "0.1.3", func(e *Entry) { e.Digest = "sha256:held" })
_ = n.Built(ctx, bc, Numbering{Versions: map[string]string{"p": "0.1.3"}}, map[string]string{"p": "sha256:other"})
es, _ := v.Of(ctx, "m/p")
if es[0].Digest != "sha256:held" || es[1].Digest != "sha256:new" {
t.Errorf("Built: published %s (want sha256:held), refused %s (want sha256:new)", es[0].Digest, es[1].Digest)
}
if all, err := v.All(ctx); err != nil || len(all) != 2 {
t.Errorf("All = %d entries, %v", len(all), err)
}
_, _ = v.Mark(ctx, "m/p", "0.1.4", func(e *Entry) { e.State = Published })
acts := Acts{Numberer: &Numberer{Versions: v, Waits: &FloorWaits{}}, Reconsider: func(context.Context) {}}
reconsidered := false
acts.Reconsider = func(context.Context) { reconsidered = true }
// H-A-159: the builder numbers nothing of its own, so no claim asks a floor: the tool refuses, saying so, and does nothing.
for _, name := range []string{"m/p", "m/new"} {
if ans, err := acts.FloorAgain(ctx, name); err == nil || !strings.Contains(err.Error(), "numbers nothing of its own") || reconsidered {
t.Errorf("floor again of %s: %q %v, looked again %v; want refused naming H-A-159, nothing looked at", name, ans, err, reconsidered)
}
}
})
}
@@ -122,7 +122,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
if m.Module != "mesh-delivery-builder" {
t.Errorf("module = %q", m.Module)
}
if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "floor-waits", History: 1, MaxMiB: 8}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, MaxMiB: 1}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "versions", History: 1, MaxMiB: 32}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814)
if want := []state{{Name: "builds", History: 5, MaxMiB: 128}, {Name: "engine-reads", History: 1, MaxMiB: 8}, {Name: "findings", History: 5, MaxMiB: 32}, {Name: "hearing", History: 1, MaxMiB: 8}, {Name: "instances", History: 1, MaxMiB: 8}, {Name: "old-form", History: 1, MaxMiB: 8}, {Name: "bounds", History: 1, KeyTTL: true, MaxMiB: 16}, {Name: "taken", History: 1, KeyTTL: true, MaxMiB: 8}, {Name: "queues", History: 1, MaxMiB: 8}, {Name: "toolchains-heard", History: 1, MaxMiB: 8}, {Name: "waits", History: 1, MaxMiB: 4}, {Name: "reserved", History: 1, MaxMiB: 8}, {Name: "acted", History: 1, MaxMiB: 1}, {Name: "asked", History: 1, MaxMiB: 8}, {Name: "reasks", History: 1, MaxMiB: 8}, {Name: "first-views", History: 1, MaxMiB: 8}, {Name: "unbuildable", History: 1, MaxMiB: 8}, {Name: "consumers", History: 1, MaxMiB: 8}}; !reflect.DeepEqual(m.State, want) { // builds.BuilderBuildsHistory // caps per H-A-437 over the fills read on novox 2026-11-22 (design 47 H2 §812, §814)
t.Errorf("state = %+v, want %+v", m.State, want)
}
// 1887/A4c: the builder chooses no node, so it reads neither presence nor have, invokes no build module's tool and
@@ -149,10 +149,10 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
t.Errorf("reads %s: the indexer's and the assigner's state is read by their tools and views families alone", r)
}
}
// Design 51 *The floor*: the floor's three sources, the registry seats' versions, git.tags and indexer_requirements.
// Design 47 H §756: the floor goes, and with it its source git.tags; the registry seats' versions are asked of a number a
// registry holds (H-A-275) and of a package's published versions (H-A-194).
// The watchdogs seat's presence says a node's machine is heard (issue 1966, ADR 0596 §2, ADR 0668 §3).
if want := []string{"seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.seat-definitions", "seat:mesh-catalog.revision", "seat:mesh-delivery.source", "seat:container-image-registry.publish", "seat:container-image-registry.remove", "seat:container-image-registry.versions",
"seat:git.tags", // the floor's source alone: no tag is written at a release (design 47 H2 H-A-494)
"seat:go-package-registry.publish", "seat:go-package-registry.remove", "seat:go-package-registry.versions", "seat:mesh-artifact-sweep.held", "seat:mesh-builds.reserved", "seat:mesh-builds.drop", "seat:mesh-builds.publish-queue", "seat:mesh-catalog.versions", "seat:mesh-hand-acts.hand-act", "seat:mesh-module-assigner.assignments", "seat:mesh-watchdogs.presence", "seat:node-build-go.drop", "seat:node-build-image.drop", "seat:node-build-node.drop", "seat:node-build-go.answer", "seat:node-build-image.answer", "seat:node-build-node.answer", "seat:node-engine.manifest-reads", "seat:npm-package-registry.publish", "seat:npm-package-registry.remove",
"seat:npm-package-registry.versions", "seat:oci-artifact-registry.publish", "seat:oci-artifact-registry.remove", "seat:oci-artifact-registry.versions",
// A-231: the build asks on each build seat's queue delivery (accept.delivery.<asker>).
@@ -162,14 +162,13 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
// The builder hears the build seats' toolchain-reported and the node-engine seat's running (design 47 G §492, §546) and reads no
// build module's toolchains; and by the seat mesh-artifact-sweep's artifacts-gone, a blob the sweep found gone (1937/AC4, 1955/L7), the
// controller's no longer (1126/B9, ADR 0590).
// Design 51 *The floor*: the indexer's take-in.taken (design 47 H H-A-116) and the condition keeper's condition-cleared wake
// a silent floor.
// Design 47 H §756: the floor and its wait go, so neither the indexer's take-in.taken (H-A-116) nor condition-cleared is heard.
// DLV-B4: the four registry seats' outcomes, each a seat event `<seat>.<event>` on the shared events stream.
// DLV-M1: the indexer's and the assigner's views families of the states it follows.
if want := []string{"container-image-registry.kept", "container-image-registry.published", "container-image-registry.refused", "container-image-registry.removed",
"go-package-registry.kept", "go-package-registry.published", "go-package-registry.refused", "go-package-registry.removed",
"mesh-artifact-sweep.artifacts-gone", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-catalog.version-released", "mesh-catalog.versions-filled",
"mesh-conditions.condition-cleared", "mesh-conditions.findings-asked", "mesh-delivery-indexer.take-in.taken", "seat:mesh-module-assigner.views.assignments",
"mesh-artifact-sweep.artifacts-gone", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", "mesh-catalog.version-released",
"mesh-conditions.findings-asked", "seat:mesh-module-assigner.views.assignments",
"seat:mesh-module-assigner.views.seat-holders", // A-298: the claimant's seat-holders view resolves the callers' seat entries
"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "node-build-go.toolchain-reported", "node-build-node.toolchain-reported", "node-engine.manifest-reads-changed", "node-engine.running",
"npm-package-registry.kept", "npm-package-registry.published", "npm-package-registry.refused", "npm-package-registry.removed",
@@ -185,7 +184,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
}
// 1945: the builder's tools (builder_seat_queue: note 62), served by its tools bundle, and the event it says when it asks an ask again.
if want := []string{"build_current", "builder_announce_again", "builder_ask_again", "builder_ask_drop", "builder_asks", "builder_bounds", "builder_build", "builder_build_again", "builder_builds_since", "builder_engine_reads", "builder_first_view_again", "builder_first_views",
"builder_floor_again", "builder_floor_waits", "builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserve_done", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) {
"builder_health", "builder_old_form", "builder_publish_again", "builder_publish_queue", "builder_release", "builder_reserve_done", "builder_reserved", "builder_reserved_drop", "builder_seat_list", "builder_seat_list_again", "builder_seat_queue", "builder_stuck", "builder_toolchains", "builder_toolchains_drop", "builder_unbuildable", "builder_versions", "builder_waits"}; !reflect.DeepEqual(sorted(m.Tools), want) {
t.Errorf("tools = %v, want %v", m.Tools, want)
}
// Design 47 G §672: the toolchain waits' stream, kept 7 days within 16 MiB, and the bound's setting, 60 minutes.
@@ -25,8 +25,6 @@
"builder_build_again",
"builder_builds_since",
"builder_engine_reads",
"builder_floor_again",
"builder_floor_waits",
"builder_old_form",
"builder_publish_again",
"builder_publish_queue",
@@ -66,9 +64,6 @@
"mesh-catalog.seat-definition-changed",
"mesh-catalog.seat-definition-removed",
"mesh-catalog.version-released",
"mesh-catalog.versions-filled",
"mesh-conditions.condition-cleared",
"mesh-delivery-indexer.take-in.taken",
"node-build-go.toolchain-reported",
"node-build-node.toolchain-reported",
"node-engine.manifest-reads-changed",
@@ -91,7 +86,6 @@
"invokes": [
"seat:container-image-registry.remove",
"seat:container-image-registry.versions",
"seat:git.tags",
"seat:go-package-registry.remove",
"seat:go-package-registry.versions",
"seat:mesh-artifact-sweep.held",
@@ -133,7 +127,6 @@
{ "name": "builds", "history": 5, "max-mib": 128 },
{ "name": "engine-reads", "history": 1, "max-mib": 8 },
{ "name": "findings", "history": 5, "max-mib": 32 },
{ "name": "floor-waits", "history": 1, "max-mib": 8 },
{ "name": "hearing", "history": 1, "max-mib": 8 },
{ "name": "instances", "history": 1, "max-mib": 8 },
{ "name": "old-form", "history": 1, "max-mib": 8 },
@@ -146,7 +139,6 @@
{ "name": "acted", "history": 1, "max-mib": 1 },
{ "name": "asked", "history": 1, "max-mib": 8 },
{ "name": "reasks", "history": 1, "max-mib": 8 },
{ "name": "versions", "history": 1, "max-mib": 32 },
{ "name": "first-views", "history": 1, "max-mib": 8 },
{ "name": "unbuildable", "history": 1, "max-mib": 8 },
{ "name": "consumers", "history": 1, "max-mib": 8 }
@@ -69,6 +69,12 @@ func TestManifestAndModuleValuesKeepTheirRules(t *testing.T) {
if m, err := DecodeModule(raw); err != nil || m.Fp2 != good.Fp2 || m.Path != RootPath {
t.Errorf("DecodeModule = %+v, %v", m, err)
}
// Design 47 H2 H-A-536, H-A-538: an import form with no imports is a reported empty import set.
empty := good
empty.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", ImportForm: SourcePrefix2 + hex64("a")}
if _, err := EncodeModule(empty); err != nil {
t.Errorf("a reported empty import set: %v", err)
}
refused := good
refused.Verdict, refused.Problems = VerdictRefused, []string{"p"}
if _, err := EncodeModule(refused); err != nil {
@@ -90,8 +96,8 @@ func TestManifestAndModuleValuesKeepTheirRules(t *testing.T) {
"a toolchain with no recipe": func(m *seat.ModulesByModuleValue) {
m.Toolchains = map[string]seat.ToolchainUsed{"go": {Language: "go", Version: "1.26"}}
},
"an import form with no imports": func(m *seat.ModulesByModuleValue) {
m.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", ImportForm: SourcePrefix2 + hex64("a")}
"an import form of another form": func(m *seat.ModulesByModuleValue) {
m.Inputs2 = &seat.ModulesByModuleValueInputs2{Tree: "t", Imports: []string{"p"}, ImportForm: "src1:" + hex64("a")}
},
} {
m := good
@@ -68,8 +68,9 @@ func CheckModule(m seat.ModulesByModuleValue) error {
}
}
if in := m.Inputs2; in != nil {
if f := in.ImportForm; f != "" && (len(in.Imports) == 0 || !strings.HasPrefix(f, SourcePrefix2) || !keys.IsHex64(f[len(SourcePrefix2):])) {
return fmt.Errorf("meshcatalogclient: the kept import form %q is set only with imports, and is %s and 64 hex digits", f, SourcePrefix2)
// An import form with no imports says a reported empty import set (design 47 H2 H-A-536, H-A-538).
if f := in.ImportForm; f != "" && (!strings.HasPrefix(f, SourcePrefix2) || !keys.IsHex64(f[len(SourcePrefix2):])) {
return fmt.Errorf("meshcatalogclient: the kept import form %q is not %s and 64 hex digits", f, SourcePrefix2)
}
for p, object := range in.Paths {
if !cleanInside(p) {
@@ -14,13 +14,13 @@ const Seat = "mesh-catalog"
// Form is the form of the seat's values, events and answers this contract was generated at (design 47 H2 §780):
// a reader of a value of another form says "form N, this reader knows M".
const Form = 5
const Form = 6
// The forms and the digest of the fields this contract was generated from: the generator's compare fails a definition
// whose fields changed while its forms did not (design 47 H2 §780).
const (
generatedForms = "5"
generatedFieldsDigest = "ActingRule=8a83ce7e0457 Artifact=78b05c1a9ec3 ArtifactPackage=2a3a660a934d ArtifactRef=a2f06147f4b6 BuildEdge=76f0684e254a BuildEdges=d2b95000259e BuildEdgesByModuleBranchValue=4fdf7cc1e723 CandidatesByGroupValue=9ea8c6c580d2 CandidatesByGroupValuePullsItem=90fb03643258 CandidatesByGroupValuePullsItemFpsValue=4c6783201aa3 CatalogEntry=c0a4ea25d523 CatalogRevision=d1ecaaa484af CatalogRevisionDefinitionsItem=77fcff620d48 CatalogRevisionEvent=710cbc5bfff1 CatalogRevisionsByBranchRevisionValue=17e54f635d35 CatalogRevisionsByCandidateGroupHeadsValue=17e54f635d35 CatalogRevisionsByEntryDigestValue=8755036a3051 DependentsAnswer=7538f2f5e68e Edge=7242732afaef EntryAnswer=805c2ff28e1c EntryInputs=76a7f8690dd2 EntryRef=ff109e5089e1 Fill=80f442916429 FillingEvent=5bd4df78ed84 FingerprintInputs=99a6df7f991f FullEvent=5bd4df78ed84 Head=774b4bf88ba4 InputAnswer=cd41ee65565d InputsByTimeDigestValue=a2f06147f4b6 ManifestsByDigestValue=51b3822b29c6 ModuleAnswer=499a03ce9b27 ModuleAnswerModule=c0f679e09f08 ModulesAnswer=6d119571c69e ModulesAnswerModulesItem=a70f39c60b67 ModulesByModuleValue=fc7530ba893a ModulesByModuleValueInputs2=99a6df7f991f Outdated=e820214f66bc OutdatedAnswer=275fb25266b9 OutdatedDependency=dc35dca1b683 PackagesByModuleValue=2b62574b709f PackagesByModuleValuePackagesItem=a7d30558470d PackagesByPackageSeriesValue=07421d8d3411 PackagesByPackageSeriesValueNewest=aba144994370 PackagesByPackageSeriesValueNewestContents=eca2ccf56913 PackagesByPackageSeriesValueNewestContentsPackagesItem=a7d30558470d PackagesByPackageSeriesValueNumbered=c8ffc628599c PackagesByPackageSeriesValueNumberedContents=0def6c0794ee PackagesByPackageSeriesValueNumberedContentsPackagesItem=a7d30558470d Policy=719e2f460c6f PolicyAnswer=46cdf8430557 PredefinedByListValue=ec8e3febe8ac ProvidesAnswer=7538f2f5e68e RegisterAnswer=46cdf8430557 Registration=ef03d1b2e73f RegistrationAsked=b529a0e1c5ca RegistrationChangedEvent=99a3268edf41 RegistrationHistoryByModuleVersionValue=0999b5bb7dc7 RegistrationHistoryBySourceOwnerNameVersionValue=0999b5bb7dc7 RegistrationsAnswer=8849ef618cf3 RegistrationsByModuleValue=0999b5bb7dc7 RegistrationsBySourceOwnerNameValue=0999b5bb7dc7 RevisionAnswer=258ea5124931 RoomEvent=5bd4df78ed84 SeatDefinitionChangedEvent=e271d24d58f7 SeatDefinitionRemovedEvent=f7d6171111e6 SeatDefinitionsAnswer=0fd6a59fec59 SeatDefinitionsAnswerEntry=d006f68d2be5 SeatDefinitionsAnswerSeatsItem=e271d24d58f7 SeatListAnswer=04477a8044b1 SourceCheck=d1ed7cbbd579 StepStatuses=4f50aa633e61 TakeInEntry=545ec1528499 ToolchainUsed=43b6d42376fb UnwatchAnswer=46cdf8430557 VersionArtifact=438c49a392b0 VersionEdge=b0f80e83f4dc VersionEntry=33f5b00dbda9 VersionReleasedEvent=4ccf1ea90e7f VersionsAnswer=b59e6e057e7b VersionsByModuleVersionValue=e546dfadb913 VersionsFilledEvent=4cc437912dc3 WatchAnswer=46cdf8430557"
generatedForms = "6"
generatedFieldsDigest = "ActingRule=8a83ce7e0457 Artifact=78b05c1a9ec3 ArtifactPackage=2a3a660a934d ArtifactRef=a2f06147f4b6 BuildEdge=76f0684e254a CandidatesByGroupValue=9ea8c6c580d2 CandidatesByGroupValuePullsItem=90fb03643258 CandidatesByGroupValuePullsItemFpsValue=4c6783201aa3 CatalogEntry=c0a4ea25d523 CatalogRevision=d1ecaaa484af CatalogRevisionDefinitionsItem=77fcff620d48 CatalogRevisionEvent=710cbc5bfff1 CatalogRevisionsByBranchRevisionValue=17e54f635d35 CatalogRevisionsByCandidateGroupHeadsValue=17e54f635d35 CatalogRevisionsByEntryDigestValue=8755036a3051 DependentsAnswer=7538f2f5e68e Edge=7242732afaef EntryAnswer=805c2ff28e1c EntryInputs=76a7f8690dd2 EntryRef=ff109e5089e1 Fill=80f442916429 FillingEvent=5bd4df78ed84 FingerprintInputs=99a6df7f991f FullEvent=5bd4df78ed84 Head=774b4bf88ba4 InputAnswer=cd41ee65565d InputsByTimeDigestValue=a2f06147f4b6 ManifestsByDigestValue=51b3822b29c6 ModuleAnswer=499a03ce9b27 ModuleAnswerModule=c0f679e09f08 ModulesAnswer=6d119571c69e ModulesAnswerModulesItem=a70f39c60b67 ModulesByModuleValue=fc7530ba893a ModulesByModuleValueInputs2=99a6df7f991f PackagesByModuleValue=2b62574b709f PackagesByModuleValuePackagesItem=a7d30558470d PackagesByPackageSeriesValue=07421d8d3411 PackagesByPackageSeriesValueNewest=aba144994370 PackagesByPackageSeriesValueNewestContents=eca2ccf56913 PackagesByPackageSeriesValueNewestContentsPackagesItem=a7d30558470d PackagesByPackageSeriesValueNumbered=c8ffc628599c PackagesByPackageSeriesValueNumberedContents=0def6c0794ee PackagesByPackageSeriesValueNumberedContentsPackagesItem=a7d30558470d Policy=719e2f460c6f PolicyAnswer=46cdf8430557 PredefinedByListValue=ec8e3febe8ac ProvidesAnswer=7538f2f5e68e RegisterAnswer=46cdf8430557 Registration=ef03d1b2e73f RegistrationAsked=b529a0e1c5ca RegistrationChangedEvent=99a3268edf41 RegistrationHistoryByModuleVersionValue=0999b5bb7dc7 RegistrationHistoryBySourceOwnerNameVersionValue=0999b5bb7dc7 RegistrationsAnswer=8849ef618cf3 RegistrationsByModuleValue=0999b5bb7dc7 RegistrationsBySourceOwnerNameValue=0999b5bb7dc7 RevisionAnswer=258ea5124931 RoomEvent=5bd4df78ed84 SeatDefinitionChangedEvent=e271d24d58f7 SeatDefinitionRemovedEvent=f7d6171111e6 SeatDefinitionsAnswer=0fd6a59fec59 SeatDefinitionsAnswerEntry=d006f68d2be5 SeatDefinitionsAnswerSeatsItem=e271d24d58f7 SeatListAnswer=04477a8044b1 SourceCheck=d1ed7cbbd579 StepStatuses=4f50aa633e61 TakeInEntry=545ec1528499 ToolchainUsed=43b6d42376fb UnwatchAnswer=46cdf8430557 VersionArtifact=438c49a392b0 VersionEdge=b0f80e83f4dc VersionEntry=33f5b00dbda9 VersionReleasedEvent=4ccf1ea90e7f VersionsAnswer=b59e6e057e7b VersionsByModuleVersionValue=e546dfadb913 WatchAnswer=46cdf8430557"
)
const (
@@ -37,7 +37,6 @@ const (
VerbWatch = "watch"
VerbUnwatch = "unwatch"
VerbVersions = "versions"
VerbOutdated = "outdated"
VerbInput = "input"
VerbEntry = "entry"
)
@@ -51,12 +50,11 @@ const (
EventRoom = "room"
EventRegistrationChanged = "registration-changed"
EventVersionReleased = "version-released"
EventVersionsFilled = "versions-filled"
)
// Verbs is every verb the seat serves, in its definition's order: a new copy each call.
func Verbs() []string {
return []string{VerbModules, VerbModule, VerbProvides, VerbDependents, VerbSeatDefinitions, VerbSeatList, VerbRevision, VerbRegistrations, VerbRegister, VerbPolicy, VerbWatch, VerbUnwatch, VerbVersions, VerbOutdated, VerbInput, VerbEntry}
return []string{VerbModules, VerbModule, VerbProvides, VerbDependents, VerbSeatDefinitions, VerbSeatList, VerbRevision, VerbRegistrations, VerbRegister, VerbPolicy, VerbWatch, VerbUnwatch, VerbVersions, VerbInput, VerbEntry}
}
// VerbDescription is a verb's description as the seat's definition says it, "" for a verb the seat does not serve or
@@ -89,8 +87,6 @@ func VerbDescription(verb string) string {
return "Remove a watched branch from a module's registration, as an authorising ask (ADR 0666 section 2)."
case VerbVersions:
return "A module's released versions, each artifact's digest, the source revision built and its edge entries; a reserved version is not in it (design 47 G section 349)."
case VerbOutdated:
return "Every entry behind, by the part's digest: its module and version or build, the kind, the dependency with its watched branch and source revision, what was recorded and what is newest, and the act; may be asked for one dependency (design 47 G section 375)."
case VerbInput:
return "A step's input by its digest, as the indexer keeps it for a validation step it asked a build seat to run (design 47 G section 354): its fields, then the bytes in chunks of at most 512 KiB on the chunk subject of the call, each acknowledged by the caller on the ack subject within 30 seconds; the input is of any size."
case VerbEntry:
@@ -101,7 +97,7 @@ func VerbDescription(verb string) string {
// Events is every event published on the seat's subject: a new copy each call.
func Events() []string {
return []string{EventSeatDefinitionChanged, EventSeatDefinitionRemoved, EventCatalogRevision, EventFilling, EventFull, EventRoom, EventRegistrationChanged, EventVersionReleased, EventVersionsFilled}
return []string{EventSeatDefinitionChanged, EventSeatDefinitionRemoved, EventCatalogRevision, EventFilling, EventFull, EventRoom, EventRegistrationChanged, EventVersionReleased}
}
// Family is where the seat's events are kept: the shared events stream, filtered to the seat's subjects.
@@ -145,12 +141,6 @@ const StreamVersionReleased = "SEAT_mesh-catalog_version-released"
// SubjectVersionReleased is where version-released is published.
const SubjectVersionReleased = "mesh.seat.mesh-catalog.event.version-released"
// StreamVersionsFilled is the stream versions-filled is kept in.
const StreamVersionsFilled = "SEAT_mesh-catalog_versions-filled"
// SubjectVersionsFilled is where versions-filled is published.
const SubjectVersionsFilled = "mesh.seat.mesh-catalog.event.versions-filled"
const (
StateManifests = "manifests"
StateModules = "modules"
@@ -161,7 +151,6 @@ const (
StateRegistrations = "registrations"
StateRegistrationHistory = "registration-history"
StateVersions = "versions"
StateBuildEdges = "build-edges"
StateInputs = "inputs"
)
@@ -594,37 +583,6 @@ func DecodeVersionsByModuleVersionValue(raw []byte) (VersionsByModuleVersionValu
return v, formRead(raw), nil
}
// BuildEdgesByModuleBranchKey is the key of one value of the state build-edges under the form "<module>.<branch>".
func BuildEdgesByModuleBranchKey(module, branch string) string { return module + "." + branch }
// ParseBuildEdgesByModuleBranchKey reads the parts of a key of the form "<module>.<branch>", in the order of the form; the last result is false for a key of another form.
func ParseBuildEdgesByModuleBranchKey(key string) (string, string, bool) {
rest := key
v0, after0, found0 := strings.Cut(rest, ".")
if !found0 || v0 == "" {
return "", "", false
}
rest = after0
if rest == "" {
return "", "", false
}
v2 := rest
rest = ""
if rest != "" {
return "", "", false
}
return v0, v2, true
}
// DecodeBuildEdgesByModuleBranchValue reads one value of the state build-edges under the form "<module>.<branch>" as another part wrote it: a field BuildEdgesByModuleBranchValue does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeBuildEdgesByModuleBranchValue(raw []byte) (BuildEdgesByModuleBranchValue, int, error) {
var v BuildEdgesByModuleBranchValue
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// InputsByTimeDigestKey is the key of one value of the state inputs under the form "<time>.<digest>".
func InputsByTimeDigestKey(time, digest string) string { return time + "." + digest }
@@ -698,17 +656,6 @@ type BuildEdge struct {
Version string `json:"version"`
}
// BuildEdges is the newest build's edge entries of a module on a watched branch other than the first, keyed by its fingerprint, which releases no version (design 47 G section 374).
type BuildEdges struct {
Edges []VersionEdge `json:"edges"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// the build's fingerprint
Fp string `json:"fp"`
Source int64 `json:"source,omitempty"`
V int64 `json:"v"`
}
// CatalogEntry is one module of a catalog graph revision as its manifest declares it, stored once by its digest (ADR 0656, design 47 Two graphs).
type CatalogEntry struct {
// the acting rules of the seats it claims
@@ -895,33 +842,6 @@ type Head struct {
Repository string `json:"repository"`
}
// OutdatedDependency is a type of the contract.
type OutdatedDependency struct {
Artifact ArtifactRef `json:"artifact"`
// the dependency's watched branch
Branch string `json:"branch"`
// the dependency's source revision
Source int64 `json:"source"`
}
// Outdated is one entry behind, by the part's digest (design 47 G section 375).
type Outdated struct {
// the act: a rebuild for a stale edge (kinds 1, 3), none for an ordering edge, which is shown only
Act string `json:"act,omitempty"`
// its build's fingerprint, for a build of another branch
Build string `json:"build,omitempty"`
Dependency OutdatedDependency `json:"dependency"`
Kind int64 `json:"kind"`
// the dependent module
Module string `json:"module"`
// what is newest: version and digest, or the fact
Newest string `json:"newest"`
// what the dependent recorded: version and digest, or the fact
Recorded string `json:"recorded"`
// its version, or empty for a build of another branch
Version string `json:"version,omitempty"`
}
// Policy is a module's policy: its steps' statuses, and per artifact what differs (ADR 0666 section 7).
type Policy struct {
// by artifact name, the statuses that differ from the module's
@@ -1402,21 +1322,6 @@ type VersionsAnswer struct {
Versions []VersionEntry `json:"versions"`
}
// OutdatedInput is what outdated takes.
type OutdatedInput struct {
// a watched branch, to answer for it alone
Branch string `json:"branch,omitempty"`
// one dependency, to answer for it alone
Dependency ArtifactRef `json:"dependency,omitempty"`
}
// OutdatedAnswer is what outdated answers.
type OutdatedAnswer struct {
Behind []Outdated `json:"behind"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
}
// InputInput is what input takes.
type InputInput struct {
// 128 random bits the caller chooses: the subject token of this send's chunks and acknowledgements
@@ -1542,16 +1447,6 @@ type VersionReleasedEvent struct {
Version string `json:"version"`
}
// VersionsFilledEvent is the body of the event versions-filled.
type VersionsFilledEvent struct {
At time.Time `json:"at"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// how many modules were filled
Modules int64 `json:"modules,omitempty"`
V int64 `json:"v"`
}
// ManifestsByDigestValue is one value of the state manifests under the key <digest>.
type ManifestsByDigestValue struct {
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
@@ -1778,9 +1673,6 @@ type RegistrationHistoryBySourceOwnerNameVersionValue = Registration
// VersionsByModuleVersionValue is one value of the state versions under the key <module>.<version>.
type VersionsByModuleVersionValue = VersionEntry
// BuildEdgesByModuleBranchValue is one value of the state build-edges under the key <module>.<branch>.
type BuildEdgesByModuleBranchValue = BuildEdges
// InputsByTimeDigestValue is one value of the state inputs under the key <time>.<digest>.
type InputsByTimeDigestValue = string
@@ -1901,15 +1793,6 @@ func DecodeVersionsAnswer(raw []byte) (VersionsAnswer, int, error) {
return v, formRead(raw), nil
}
// DecodeOutdatedAnswer reads a OutdatedAnswer as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeOutdatedAnswer(raw []byte) (OutdatedAnswer, int, error) {
var v OutdatedAnswer
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// DecodeInputAnswer reads a InputAnswer as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeInputAnswer(raw []byte) (InputAnswer, int, error) {
var v InputAnswer
@@ -2000,15 +1883,6 @@ func DecodeVersionReleasedEvent(raw []byte) (VersionReleasedEvent, int, error) {
return v, formRead(raw), nil
}
// DecodeVersionsFilledEvent reads a VersionsFilledEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeVersionsFilledEvent(raw []byte) (VersionsFilledEvent, int, error) {
var v VersionsFilledEvent
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// formRead is the form a value says on the wire: 1 when it says none, or is no object.
func formRead(raw []byte) int {
var f struct {
@@ -35,8 +35,6 @@ func TestFixtures(t *testing.T) {
}, subjectIs: regexp.MustCompile("^mesh\\.seat\\.mesh-catalog\\.event\\.registration-changed$")},
{name: "a version released", subject: "mesh.seat.mesh-catalog.event.version-released", given: "{\"artifacts\":[{\"artifact\":\"mesh-sdk:go\",\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}],\"module\":\"mesh-sdk\",\"source\":3589,\"v\":1,\"version\":\"0.1.15\"}", wire: "{\"artifacts\":[{\"artifact\":\"mesh-sdk:go\",\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}],\"module\":\"mesh-sdk\",\"source\":3589,\"v\":1,\"version\":\"0.1.15\"}",
decode: func(b []byte) (any, error) { var v VersionReleasedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.mesh-catalog\\.event\\.version-released$")},
{name: "the versions filled", subject: "mesh.seat.mesh-catalog.event.versions-filled", given: "{\"at\":\"2026-11-11T10:00:00Z\",\"modules\":120,\"v\":1}", wire: "{\"at\":\"2026-11-11T10:00:00Z\",\"modules\":120,\"v\":1}",
decode: func(b []byte) (any, error) { var v VersionsFilledEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.mesh-catalog\\.event\\.versions-filled$")},
{name: "a manifest (xclip, read through mesh-catalog.module)", subject: "", given: "{\"manifest\":\"{\\\"build\\\":{\\\"artifacts\\\":[{\\\"binary\\\":\\\"xclip-tools\\\",\\\"from\\\":\\\"cmd/xclip-tools\\\",\\\"kind\\\":\\\"bundle\\\",\\\"language\\\":\\\"go\\\",\\\"loads\\\":[\\\"xclip-tools\\\"],\\\"name\\\":\\\"tools\\\",\\\"system\\\":\\\"arch\\\"}]},\\\"capabilities\\\":[\\\"package-manager\\\"],\\\"module\\\":\\\"xclip\\\",\\\"resources\\\":[{\\\"id\\\":\\\"package\\\",\\\"package\\\":\\\"xclip\\\",\\\"type\\\":\\\"package\\\"}],\\\"tools\\\":[\\\"xclip_copy\\\",\\\"xclip_paste\\\",\\\"xclip_targets\\\",\\\"xclip_session\\\"],\\\"version\\\":\\\"1\\\"}\",\"module\":\"xclip\",\"v\":1}", wire: "{\"manifest\":\"{\\\"build\\\":{\\\"artifacts\\\":[{\\\"binary\\\":\\\"xclip-tools\\\",\\\"from\\\":\\\"cmd/xclip-tools\\\",\\\"kind\\\":\\\"bundle\\\",\\\"language\\\":\\\"go\\\",\\\"loads\\\":[\\\"xclip-tools\\\"],\\\"name\\\":\\\"tools\\\",\\\"system\\\":\\\"arch\\\"}]},\\\"capabilities\\\":[\\\"package-manager\\\"],\\\"module\\\":\\\"xclip\\\",\\\"resources\\\":[{\\\"id\\\":\\\"package\\\",\\\"package\\\":\\\"xclip\\\",\\\"type\\\":\\\"package\\\"}],\\\"tools\\\":[\\\"xclip_copy\\\",\\\"xclip_paste\\\",\\\"xclip_targets\\\",\\\"xclip_session\\\"],\\\"version\\\":\\\"1\\\"}\",\"module\":\"xclip\",\"v\":1}",
decode: func(b []byte) (any, error) { var v ManifestsByDigestValue; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "a module (xclip, read through mesh-catalog.modules; the inputs and toolchains no tool reads are not here)", subject: "", given: "{\"commit\":\"f469eb387a3015569d9b16c66ed418e9dd098f64\",\"fp2\":\"src2:b427bdde1f100e2f52490cfa9df0c5112dd3700226b4892349f0c14a15a4af56\",\"path\":\"modules/xclip\",\"repository\":\"novox/mesh-catalog\",\"v\":1}", wire: "{\"commit\":\"f469eb387a3015569d9b16c66ed418e9dd098f64\",\"fp2\":\"src2:b427bdde1f100e2f52490cfa9df0c5112dd3700226b4892349f0c14a15a4af56\",\"path\":\"modules/xclip\",\"repository\":\"novox/mesh-catalog\",\"v\":1}",
@@ -113,12 +111,6 @@ func TestFixtures(t *testing.T) {
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "a build of another branch", subject: "", given: "{\"edges\":[{\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"kind\":1,\"part\":\"mesh-contracts:go-nodeengine\",\"stale\":true,\"version\":\"0.1.4\",\"word\":\"imports\"}],\"fp\":\"src2:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"source\":3589,\"v\":1}", wire: "{\"edges\":[{\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"kind\":1,\"part\":\"mesh-contracts:go-nodeengine\",\"stale\":true,\"version\":\"0.1.4\",\"word\":\"imports\"}],\"fp\":\"src2:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"source\":3589,\"v\":1}",
decode: func(b []byte) (any, error) {
var v BuildEdgesByModuleBranchValue
err := json.Unmarshal(b, &v)
return v, err
}, subjectIs: nil},
{name: "an input", subject: "", given: "\"eyJ2IjoxfQ==\"", wire: "\"eyJ2IjoxfQ==\"",
decode: func(b []byte) (any, error) {
var v InputsByTimeDigestValue
@@ -171,10 +163,6 @@ func TestFixtures(t *testing.T) {
decode: func(b []byte) (any, error) { var v VersionsInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "versions answers the released versions with their edges", subject: "", given: "{\"module\":\"mesh-sdk\",\"versions\":[{\"artifacts\":[{\"artifact\":\"mesh-sdk:go\",\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}],\"edges\":[{\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"kind\":1,\"part\":\"mesh-contracts:go-nodeengine\",\"stale\":true,\"version\":\"0.1.4\",\"word\":\"imports\"}],\"module\":\"mesh-sdk\",\"source\":3589,\"v\":1,\"version\":\"0.1.15\"}]}", wire: "{\"module\":\"mesh-sdk\",\"versions\":[{\"artifacts\":[{\"artifact\":\"mesh-sdk:go\",\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}],\"edges\":[{\"digest\":\"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"kind\":1,\"part\":\"mesh-contracts:go-nodeengine\",\"stale\":true,\"version\":\"0.1.4\",\"word\":\"imports\"}],\"module\":\"mesh-sdk\",\"source\":3589,\"v\":1,\"version\":\"0.1.15\"}]}",
decode: func(b []byte) (any, error) { var v VersionsAnswer; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "outdated asks for one dependency", subject: "", given: "{\"branch\":\"main\",\"dependency\":\"mesh-sdk:go\"}", wire: "{\"branch\":\"main\",\"dependency\":\"mesh-sdk:go\"}",
decode: func(b []byte) (any, error) { var v OutdatedInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "outdated answers an entry behind", subject: "", given: "{\"behind\":[{\"act\":\"rebuild\",\"dependency\":{\"artifact\":\"mesh-sdk:go\",\"branch\":\"main\",\"source\":3589},\"kind\":1,\"module\":\"nats\",\"newest\":\"0.1.15 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"recorded\":\"0.1.14 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"version\":\"1.2.3\"}]}", wire: "{\"behind\":[{\"act\":\"rebuild\",\"dependency\":{\"artifact\":\"mesh-sdk:go\",\"branch\":\"main\",\"source\":3589},\"kind\":1,\"module\":\"nats\",\"newest\":\"0.1.15 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"recorded\":\"0.1.14 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"version\":\"1.2.3\"}]}",
decode: func(b []byte) (any, error) { var v OutdatedAnswer; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "input asks a step's input by digest", subject: "", given: "{\"call\":\"0123456789abcdef0123456789abcdef\",\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}", wire: "{\"call\":\"0123456789abcdef0123456789abcdef\",\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}",
decode: func(b []byte) (any, error) { var v InputInput; err := json.Unmarshal(b, &v); return v, err }, subjectIs: nil},
{name: "input answers how many chunks carry the exact bytes", subject: "", given: "{\"chunks\":3,\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}", wire: "{\"chunks\":3,\"digest\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}",
@@ -17,13 +17,13 @@ const Seat = "node-build-go"
const Form = 1
// FormBuildStep is the form of what the part build-step adds.
const FormBuildStep = 3
const FormBuildStep = 4
// The forms and the digest of the fields this contract was generated from: the generator's compare fails a definition
// whose fields changed while its forms did not (design 47 H2 §780).
const (
generatedForms = "1 build-step:3"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckRunAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
generatedForms = "1 build-step:4"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckRunAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c ImportsReported=c5960405236e ImportsReportedEvent=1615a3e4797e InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
)
const (
@@ -49,6 +49,7 @@ const (
const (
EventStepEnded = "step-ended"
EventToolchainReported = "toolchain-reported"
EventImportsReported = "imports-reported"
EventStepProgress = "step-progress"
EventAskTaken = "ask-taken"
)
@@ -84,7 +85,7 @@ func VerbDescription(verb string) string {
// Events is every event published on the seat's subject: a new copy each call.
func Events() []string {
return []string{EventStepEnded, EventToolchainReported, EventStepProgress, EventAskTaken}
return []string{EventStepEnded, EventToolchainReported, EventImportsReported, EventStepProgress, EventAskTaken}
}
// Family is where the seat's events are kept: the shared events stream, filtered to the seat's subjects.
@@ -113,6 +114,17 @@ func SubjectToolchainReported(node string) string {
// SubjectToolchainReportedAll hears every toolchain-reported.
const SubjectToolchainReportedAll = "mesh.seat.node-build-go.event.toolchain-reported.*"
// StreamImportsReported is the stream imports-reported is kept in.
const StreamImportsReported = "SEAT_node-build-go_imports-reported"
// SubjectImportsReported is where imports-reported is published, on mesh.seat.node-build-go.event.imports-reported.<node>.
func SubjectImportsReported(node string) string {
return "mesh.seat.node-build-go.event.imports-reported." + node
}
// SubjectImportsReportedAll hears every imports-reported.
const SubjectImportsReportedAll = "mesh.seat.node-build-go.event.imports-reported.*"
// SubjectStepProgress is where step-progress is published, on mesh.seat.node-build-go.event.step-progress.<node>.
func SubjectStepProgress(node string) string {
return "mesh.seat.node-build-go.event.step-progress." + node
@@ -586,6 +598,22 @@ type FetchRefusal struct {
Reason string `json:"reason"`
}
// ImportsReported is the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2).
type ImportsReported struct {
// the commit the build was made from
Commit string `json:"commit"`
// the fingerprint the build was asked for
Fingerprint string `json:"fingerprint"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// each mesh package the module's programs import, by its import path; empty when they import none
Imports []string `json:"imports"`
// the module built
Module string `json:"module"`
// the node the build ran on
Node string `json:"node"`
}
// InstallAsk is the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers.
type InstallAsk struct {
// who asked it
@@ -1246,6 +1274,9 @@ type StepEndedEvent = StepEnded
// ToolchainReportedEvent is the body of the event toolchain-reported.
type ToolchainReportedEvent = ToolchainReported
// ImportsReportedEvent is the body of the event imports-reported.
type ImportsReportedEvent = ImportsReported
// StepProgressEvent is the body of the event step-progress.
type StepProgressEvent = StepProgress
@@ -1363,6 +1394,15 @@ func DecodeToolchainReportedEvent(raw []byte) (ToolchainReportedEvent, int, erro
return v, formRead(raw), nil
}
// DecodeImportsReportedEvent reads a ImportsReportedEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeImportsReportedEvent(raw []byte) (ImportsReportedEvent, int, error) {
var v ImportsReportedEvent
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// DecodeStepProgressEvent reads a StepProgressEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeStepProgressEvent(raw []byte) (StepProgressEvent, int, error) {
var v StepProgressEvent
@@ -23,6 +23,10 @@ func TestFixtures(t *testing.T) {
decode: func(b []byte) (any, error) { var v StepEndedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-go\\.event\\.step-ended\\.[^.*> ]+$")},
{name: "a node's toolchain reported", subject: "mesh.seat.node-build-go.event.toolchain-reported.anchor", given: "{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"language\":\"go\",\"node\":\"anchor\",\"recipe\":\"1\",\"version\":\"1.26.0\"}", wire: "{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"language\":\"go\",\"node\":\"anchor\",\"recipe\":\"1\",\"version\":\"1.26.0\"}",
decode: func(b []byte) (any, error) { var v ToolchainReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-go\\.event\\.toolchain-reported\\.[^.*> ]+$")},
{name: "a module's import set said at its build's end (design 47 H2 H-A-517)", subject: "mesh.seat.node-build-go.event.imports-reported.anchor", given: "{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"fingerprint\":\"fp-0123\",\"imports\":[\"git.novox.be/novox/mesh-sdk/go/bus\",\"git.novox.be/novox/mesh-sdk/go/catalogue\"],\"module\":\"nats\",\"node\":\"anchor\"}", wire: "{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"fingerprint\":\"fp-0123\",\"imports\":[\"git.novox.be/novox/mesh-sdk/go/bus\",\"git.novox.be/novox/mesh-sdk/go/catalogue\"],\"module\":\"nats\",\"node\":\"anchor\"}",
decode: func(b []byte) (any, error) { var v ImportsReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-go\\.event\\.imports-reported\\.[^.*> ]+$")},
{name: "a module whose programs import no mesh package says an empty set (H-A-532 DQ-2)", subject: "mesh.seat.node-build-go.event.imports-reported.anchor", given: "{\"commit\":\"89abcdef0123456789abcdef0123456789abcdef\",\"fingerprint\":\"fp-4567\",\"imports\":[],\"module\":\"feh\",\"node\":\"anchor\"}", wire: "{\"commit\":\"89abcdef0123456789abcdef0123456789abcdef\",\"fingerprint\":\"fp-4567\",\"imports\":[],\"module\":\"feh\",\"node\":\"anchor\"}",
decode: func(b []byte) (any, error) { var v ImportsReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-go\\.event\\.imports-reported\\.[^.*> ]+$")},
{name: "a running ask says its progress", subject: "mesh.seat.node-build-go.event.step-progress.anchor", given: "{\"ask\":\"a1b2\",\"asker\":\"runner\",\"at\":\"2026-11-11T10:01:00Z\",\"phase\":\"fetch\"}", wire: "{\"ask\":\"a1b2\",\"asker\":\"runner\",\"at\":\"2026-11-11T10:01:00Z\",\"phase\":\"fetch\"}",
decode: func(b []byte) (any, error) { var v StepProgressEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-go\\.event\\.step-progress\\.[^.*> ]+$")},
{name: "a builder's build ended, naming its asker and no commit or fingerprint (G 548)", subject: "mesh.seat.node-build-go.event.step-ended.anchor", given: "{\"ask\":\"m2kx9a1b3c4d6a\",\"asker\":\"mesh-delivery-builder\",\"at\":\"2026-11-11T10:03:00Z\",\"id\":\"m2kx9a1b3c4d6a\",\"node\":\"anchor\",\"outcome\":\"failed\",\"said\":\"the build failed\",\"v\":1}", wire: "{\"ask\":\"m2kx9a1b3c4d6a\",\"asker\":\"mesh-delivery-builder\",\"at\":\"2026-11-11T10:03:00Z\",\"id\":\"m2kx9a1b3c4d6a\",\"node\":\"anchor\",\"outcome\":\"failed\",\"said\":\"the build failed\",\"v\":1}",
@@ -17,13 +17,13 @@ const Seat = "node-build-image"
const Form = 1
// FormBuildStep is the form of what the part build-step adds.
const FormBuildStep = 3
const FormBuildStep = 4
// The forms and the digest of the fields this contract was generated from: the generator's compare fails a definition
// whose fields changed while its forms did not (design 47 H2 §780).
const (
generatedForms = "1 build-step:3"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
generatedForms = "1 build-step:4"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c ImportsReported=c5960405236e ImportsReportedEvent=1615a3e4797e InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
)
const (
@@ -48,6 +48,7 @@ const (
const (
EventStepEnded = "step-ended"
EventToolchainReported = "toolchain-reported"
EventImportsReported = "imports-reported"
EventStepProgress = "step-progress"
EventAskTaken = "ask-taken"
)
@@ -83,7 +84,7 @@ func VerbDescription(verb string) string {
// Events is every event published on the seat's subject: a new copy each call.
func Events() []string {
return []string{EventStepEnded, EventToolchainReported, EventStepProgress, EventAskTaken}
return []string{EventStepEnded, EventToolchainReported, EventImportsReported, EventStepProgress, EventAskTaken}
}
// Family is where the seat's events are kept: the shared events stream, filtered to the seat's subjects.
@@ -114,6 +115,17 @@ func SubjectToolchainReported(node string) string {
// SubjectToolchainReportedAll hears every toolchain-reported.
const SubjectToolchainReportedAll = "mesh.seat.node-build-image.event.toolchain-reported.*"
// StreamImportsReported is the stream imports-reported is kept in.
const StreamImportsReported = "SEAT_node-build-image_imports-reported"
// SubjectImportsReported is where imports-reported is published, on mesh.seat.node-build-image.event.imports-reported.<node>.
func SubjectImportsReported(node string) string {
return "mesh.seat.node-build-image.event.imports-reported." + node
}
// SubjectImportsReportedAll hears every imports-reported.
const SubjectImportsReportedAll = "mesh.seat.node-build-image.event.imports-reported.*"
// SubjectStepProgress is where step-progress is published, on mesh.seat.node-build-image.event.step-progress.<node>.
func SubjectStepProgress(node string) string {
return "mesh.seat.node-build-image.event.step-progress." + node
@@ -584,6 +596,22 @@ type FetchRefusal struct {
Reason string `json:"reason"`
}
// ImportsReported is the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2).
type ImportsReported struct {
// the commit the build was made from
Commit string `json:"commit"`
// the fingerprint the build was asked for
Fingerprint string `json:"fingerprint"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// each mesh package the module's programs import, by its import path; empty when they import none
Imports []string `json:"imports"`
// the module built
Module string `json:"module"`
// the node the build ran on
Node string `json:"node"`
}
// InstallAsk is the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers.
type InstallAsk struct {
// who asked it
@@ -1241,6 +1269,9 @@ type StepEndedEvent = StepEnded
// ToolchainReportedEvent is the body of the event toolchain-reported.
type ToolchainReportedEvent = ToolchainReported
// ImportsReportedEvent is the body of the event imports-reported.
type ImportsReportedEvent = ImportsReported
// StepProgressEvent is the body of the event step-progress.
type StepProgressEvent = StepProgress
@@ -1358,6 +1389,15 @@ func DecodeToolchainReportedEvent(raw []byte) (ToolchainReportedEvent, int, erro
return v, formRead(raw), nil
}
// DecodeImportsReportedEvent reads a ImportsReportedEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeImportsReportedEvent(raw []byte) (ImportsReportedEvent, int, error) {
var v ImportsReportedEvent
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// DecodeStepProgressEvent reads a StepProgressEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeStepProgressEvent(raw []byte) (StepProgressEvent, int, error) {
var v StepProgressEvent
@@ -17,13 +17,13 @@ const Seat = "node-build-node"
const Form = 1
// FormBuildStep is the form of what the part build-step adds.
const FormBuildStep = 3
const FormBuildStep = 4
// The forms and the digest of the fields this contract was generated from: the generator's compare fails a definition
// whose fields changed while its forms did not (design 47 H2 §780).
const (
generatedForms = "1 build-step:3"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c InstallAccept=ef89c6962ae4 InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
generatedForms = "1 build-step:4"
generatedFieldsDigest = "AnswerAnswer=a3b42bd5e791 AskArtifact=35eb85c27e97 AskTaken=8c917075eed4 AskTakenEvent=e4fc9b81e066 BuiltArtifact=b5fcef7a8b58 BuiltArtifactResolvedItem=3bcbbcfd1a1f Capacity=b40cca7ccdfa CheckAccept=ef89c6962ae4 CheckStepAccept=ef89c6962ae4 CurrentAnswer=e39824e012cb CurrentAsk=ac167e5ee11f DeliveryAccept=ef89c6962ae4 DeliveryStepAccept=ef89c6962ae4 DetectedStep=a6fcd7d0eca4 DetectedSteps=05198185c776 DetectedStepsByModuleArtifactValue=cb35b5775cc6 Drop=fb4637978e86 DropAnswer=7538f2f5e68e FailingTest=f3fb3f1a3ca8 Fetch=6e12677bbc2c FetchAnswer=46fc3d5bd7ee FetchBesideItem=774b4bf88ba4 FetchBuildsItem=aee5adc97246 FetchPackage=20d1668a0eee FetchRefusal=de1518848b4c ImportsReported=c5960405236e ImportsReportedEvent=1615a3e4797e InstallAccept=ef89c6962ae4 InstallAsk=9f965aa5b30b KeptArtifactAnswer=706729f8ccb9 KeptResult=8657683cdcd7 LevelAnswer=143c69c28a6a LevelAnswerDigest=d54b7fd7b1da LevelAnswerDigestNeedsItem=946b37d1d4a1 LevelAnswerDigestPackagesItem=a7d30558470d LevelAnswerKeptItem=85d3c2f78632 LevelAnswerUnmetItem=946b37d1d4a1 ModuleTree=00bb59e9f262 NotRun=d322fb1eb153 OutputAnswer=97ba4bd92bf9 Pause=d6521e0cdd1e PauseAnswer=7538f2f5e68e PausesByCapacityNodeValue=5392cf505c80 PausesByDroppedIDValue=0e15ac9cacbd PausesByPausedNodeValue=d111aad0f0cf PlacedBeside=53479337ff18 Program=b48ae74f34e0 RecheckAccept=ef89c6962ae4 ResumeAnswer=7538f2f5e68e RunHead=774b4bf88ba4 RunInput=3dc41505a4b7 RunJob=88af2a7f432b RunProgram=6fd636999d54 Step=75190430d510 StepAsk=f0d09ea1670e StepAskBuild=de784b6c05da StepAskCheck=b77941df6dea StepAskCompose=4c6a08e10231 StepEnded=9bc24593a47d StepEndedEvent=207787118dac StepProgress=d25781cc895a StepProgressEvent=179344ce0ca2 StepResult=67f88be36d0e StepRun=a7a81f25515f StepsAnswer=2c02cac2df23 StepsByAskerNodeIDValue=50ccfd4cebd8 StepsByNodeIDValue=50ccfd4cebd8 TakenVersion=1b8d0547f61e TestCounts=9c1332427159 Toolchain=8ecb7debf9ad ToolchainReported=d26392767c50 ToolchainReportedEvent=fa0a431c9c7b ToolchainUsed=6cc7ccabc9f8 ToolchainsByNodeLanguageValue=f97d1dd27613"
)
const (
@@ -49,6 +49,7 @@ const (
const (
EventStepEnded = "step-ended"
EventToolchainReported = "toolchain-reported"
EventImportsReported = "imports-reported"
EventStepProgress = "step-progress"
EventAskTaken = "ask-taken"
)
@@ -84,7 +85,7 @@ func VerbDescription(verb string) string {
// Events is every event published on the seat's subject: a new copy each call.
func Events() []string {
return []string{EventStepEnded, EventToolchainReported, EventStepProgress, EventAskTaken}
return []string{EventStepEnded, EventToolchainReported, EventImportsReported, EventStepProgress, EventAskTaken}
}
// Family is where the seat's events are kept: the shared events stream, filtered to the seat's subjects.
@@ -115,6 +116,17 @@ func SubjectToolchainReported(node string) string {
// SubjectToolchainReportedAll hears every toolchain-reported.
const SubjectToolchainReportedAll = "mesh.seat.node-build-node.event.toolchain-reported.*"
// StreamImportsReported is the stream imports-reported is kept in.
const StreamImportsReported = "SEAT_node-build-node_imports-reported"
// SubjectImportsReported is where imports-reported is published, on mesh.seat.node-build-node.event.imports-reported.<node>.
func SubjectImportsReported(node string) string {
return "mesh.seat.node-build-node.event.imports-reported." + node
}
// SubjectImportsReportedAll hears every imports-reported.
const SubjectImportsReportedAll = "mesh.seat.node-build-node.event.imports-reported.*"
// SubjectStepProgress is where step-progress is published, on mesh.seat.node-build-node.event.step-progress.<node>.
func SubjectStepProgress(node string) string {
return "mesh.seat.node-build-node.event.step-progress." + node
@@ -588,6 +600,22 @@ type FetchRefusal struct {
Reason string `json:"reason"`
}
// ImportsReported is the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2).
type ImportsReported struct {
// the commit the build was made from
Commit string `json:"commit"`
// the fingerprint the build was asked for
Fingerprint string `json:"fingerprint"`
// is the form of what this value carries, left out while it is 1 (design 47 H2 §780).
Form int64 `json:"form,omitempty"`
// each mesh package the module's programs import, by its import path; empty when they import none
Imports []string `json:"imports"`
// the module built
Module string `json:"module"`
// the node the build ran on
Node string `json:"node"`
}
// InstallAsk is the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers.
type InstallAsk struct {
// who asked it
@@ -1248,6 +1276,9 @@ type StepEndedEvent = StepEnded
// ToolchainReportedEvent is the body of the event toolchain-reported.
type ToolchainReportedEvent = ToolchainReported
// ImportsReportedEvent is the body of the event imports-reported.
type ImportsReportedEvent = ImportsReported
// StepProgressEvent is the body of the event step-progress.
type StepProgressEvent = StepProgress
@@ -1365,6 +1396,15 @@ func DecodeToolchainReportedEvent(raw []byte) (ToolchainReportedEvent, int, erro
return v, formRead(raw), nil
}
// DecodeImportsReportedEvent reads a ImportsReportedEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeImportsReportedEvent(raw []byte) (ImportsReportedEvent, int, error) {
var v ImportsReportedEvent
if err := json.Unmarshal(raw, &v); err != nil {
return v, 0, err
}
return v, formRead(raw), nil
}
// DecodeStepProgressEvent reads a StepProgressEvent as another part wrote it: a field this reader does not know is left unread, never refused; the form read is answered, 1 when absent (design 47 H2 §780).
func DecodeStepProgressEvent(raw []byte) (StepProgressEvent, int, error) {
var v StepProgressEvent
@@ -23,6 +23,10 @@ func TestFixtures(t *testing.T) {
decode: func(b []byte) (any, error) { var v StepEndedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-node\\.event\\.step-ended\\.[^.*> ]+$")},
{name: "a node's toolchain reported", subject: "mesh.seat.node-build-node.event.toolchain-reported.anchor", given: "{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"language\":\"go\",\"node\":\"anchor\",\"recipe\":\"1\",\"version\":\"1.26.0\"}", wire: "{\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"language\":\"go\",\"node\":\"anchor\",\"recipe\":\"1\",\"version\":\"1.26.0\"}",
decode: func(b []byte) (any, error) { var v ToolchainReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-node\\.event\\.toolchain-reported\\.[^.*> ]+$")},
{name: "a module's import set said at its build's end (design 47 H2 H-A-517)", subject: "mesh.seat.node-build-node.event.imports-reported.anchor", given: "{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"fingerprint\":\"fp-0123\",\"imports\":[\"@novox/mesh-sdk\"],\"module\":\"nats\",\"node\":\"anchor\"}", wire: "{\"commit\":\"0123456789abcdef0123456789abcdef01234567\",\"fingerprint\":\"fp-0123\",\"imports\":[\"@novox/mesh-sdk\"],\"module\":\"nats\",\"node\":\"anchor\"}",
decode: func(b []byte) (any, error) { var v ImportsReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-node\\.event\\.imports-reported\\.[^.*> ]+$")},
{name: "a module whose programs import no mesh package says an empty set (H-A-532 DQ-2)", subject: "mesh.seat.node-build-node.event.imports-reported.anchor", given: "{\"commit\":\"89abcdef0123456789abcdef0123456789abcdef\",\"fingerprint\":\"fp-4567\",\"imports\":[],\"module\":\"feh\",\"node\":\"anchor\"}", wire: "{\"commit\":\"89abcdef0123456789abcdef0123456789abcdef\",\"fingerprint\":\"fp-4567\",\"imports\":[],\"module\":\"feh\",\"node\":\"anchor\"}",
decode: func(b []byte) (any, error) { var v ImportsReportedEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-node\\.event\\.imports-reported\\.[^.*> ]+$")},
{name: "a running ask says its progress", subject: "mesh.seat.node-build-node.event.step-progress.anchor", given: "{\"ask\":\"a1b2\",\"asker\":\"runner\",\"at\":\"2026-11-11T10:01:00Z\",\"phase\":\"fetch\"}", wire: "{\"ask\":\"a1b2\",\"asker\":\"runner\",\"at\":\"2026-11-11T10:01:00Z\",\"phase\":\"fetch\"}",
decode: func(b []byte) (any, error) { var v StepProgressEvent; err := json.Unmarshal(b, &v); return v, err }, subjectIs: regexp.MustCompile("^mesh\\.seat\\.node-build-node\\.event\\.step-progress\\.[^.*> ]+$")},
{name: "a builder's build ended, naming its asker and no commit or fingerprint (G 548)", subject: "mesh.seat.node-build-node.event.step-ended.anchor", given: "{\"ask\":\"m2kx9a1b3c4d6a\",\"asker\":\"mesh-delivery-builder\",\"at\":\"2026-11-11T10:03:00Z\",\"id\":\"m2kx9a1b3c4d6a\",\"node\":\"anchor\",\"outcome\":\"failed\",\"said\":\"the build failed\",\"v\":1}", wire: "{\"ask\":\"m2kx9a1b3c4d6a\",\"asker\":\"mesh-delivery-builder\",\"at\":\"2026-11-11T10:03:00Z\",\"id\":\"m2kx9a1b3c4d6a\",\"node\":\"anchor\",\"outcome\":\"failed\",\"said\":\"the build failed\",\"v\":1}",
@@ -2059,6 +2059,42 @@
"fingerprint",
"lock"
]
},
"ImportsReported": {
"type": "object",
"description": "the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2)",
"properties": {
"node": {
"type": "string",
"description": "the node the build ran on"
},
"module": {
"type": "string",
"description": "the module built"
},
"fingerprint": {
"type": "string",
"description": "the fingerprint the build was asked for"
},
"commit": {
"type": "string",
"description": "the commit the build was made from"
},
"imports": {
"type": "array",
"items": {
"type": "string"
},
"description": "each mesh package the module's programs import, by its import path; empty when they import none"
}
},
"required": [
"node",
"module",
"fingerprint",
"commit",
"imports"
]
}
},
"events": [
@@ -2084,6 +2120,17 @@
"max-mib": 16
}
},
{
"name": "imports-reported",
"subject": "imports-reported.<node>",
"body": {
"$ref": "#/defs/ImportsReported"
},
"keep": {
"max-age-days": 90,
"max-mib": 16
}
},
{
"name": "step-progress",
"subject": "step-progress.<node>",
@@ -2099,5 +2146,5 @@
}
}
],
"form": 3
"form": 4
}
@@ -101,15 +101,5 @@
],
"source": 3589
}
},
{
"name": "the versions filled",
"of": "event:versions-filled",
"subject": "mesh.seat.mesh-catalog.event.versions-filled",
"given": {
"v": 1,
"at": "2026-11-11T10:00:00Z",
"modules": 120
}
}
]
@@ -566,25 +566,6 @@
]
}
},
{
"name": "a build of another branch",
"of": "state:build-edges/<module>.<branch>",
"given": {
"v": 1,
"fp": "src2:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"source": 3589,
"edges": [
{
"kind": 1,
"stale": true,
"word": "imports",
"part": "mesh-contracts:go-nodeengine",
"version": "0.1.4",
"digest": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
}
]
}
},
{
"name": "an input",
"of": "state:inputs/<time>.<digest>",
@@ -391,35 +391,6 @@
]
}
},
{
"name": "outdated asks for one dependency",
"of": "verb:outdated.input",
"given": {
"dependency": "mesh-sdk:go",
"branch": "main"
}
},
{
"name": "outdated answers an entry behind",
"of": "verb:outdated.answer",
"given": {
"behind": [
{
"module": "nats",
"version": "1.2.3",
"kind": 1,
"dependency": {
"artifact": "mesh-sdk:go",
"branch": "main",
"source": 3589
},
"recorded": "0.1.14 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"newest": "0.1.15 sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"act": "rebuild"
}
]
}
},
{
"name": "input asks a step's input by digest",
"of": "verb:input.input",
@@ -555,38 +555,6 @@
]
}
},
{
"name": "outdated",
"class": "read",
"description": "Every entry behind, by the part's digest: its module and version or build, the kind, the dependency with its watched branch and source revision, what was recorded and what is newest, and the act; may be asked for one dependency (design 47 G section 375).",
"input": {
"type": "object",
"properties": {
"dependency": {
"$ref": "#/defs/ArtifactRef",
"description": "one dependency, to answer for it alone"
},
"branch": {
"type": "string",
"description": "a watched branch, to answer for it alone"
}
}
},
"answer": {
"type": "object",
"properties": {
"behind": {
"type": "array",
"items": {
"$ref": "#/defs/Outdated"
}
}
},
"required": [
"behind"
]
}
},
{
"name": "input",
"class": "read",
@@ -889,34 +857,6 @@
],
"description": "a version released: every artifact of the module is published at it (design 47 G section 349)"
}
},
{
"name": "versions-filled",
"keep": {
"max-age-days": 0,
"max-mib": 1
},
"body": {
"type": "object",
"properties": {
"v": {
"type": "integer"
},
"at": {
"type": "string",
"format": "date-time"
},
"modules": {
"type": "integer",
"description": "how many modules were filled"
}
},
"required": [
"v",
"at"
],
"description": "the catalog's versions were filled once from what is published (design 47 G section 372)"
}
}
],
"states": [
@@ -1583,21 +1523,6 @@
}
]
},
{
"name": "build-edges",
"template": "state",
"history": 1,
"description": "the newest build's edges of a module on a watched branch other than the first (design 47 G section 374)",
"key-forms": [
{
"key": "<module>.<branch>",
"value": {
"$ref": "#/defs/BuildEdges"
},
"description": "a build's edges"
}
]
},
{
"name": "inputs",
"template": "state",
@@ -2477,102 +2402,6 @@
"artifacts"
]
},
"BuildEdges": {
"type": "object",
"description": "the newest build's edge entries of a module on a watched branch other than the first, keyed by its fingerprint, which releases no version (design 47 G section 374)",
"properties": {
"v": {
"type": "integer"
},
"fp": {
"type": "string",
"description": "the build's fingerprint"
},
"source": {
"type": "integer"
},
"edges": {
"type": "array",
"items": {
"$ref": "#/defs/VersionEdge"
}
}
},
"required": [
"v",
"fp",
"edges"
]
},
"Outdated": {
"type": "object",
"description": "one entry behind, by the part's digest (design 47 G section 375)",
"properties": {
"module": {
"type": "string",
"description": "the dependent module"
},
"version": {
"type": "string",
"description": "its version, or empty for a build of another branch"
},
"build": {
"type": "string",
"description": "its build's fingerprint, for a build of another branch"
},
"kind": {
"type": "integer",
"enum": [
1,
2,
3,
4,
5,
6
]
},
"dependency": {
"type": "object",
"properties": {
"artifact": {
"$ref": "#/defs/ArtifactRef"
},
"branch": {
"type": "string",
"description": "the dependency's watched branch"
},
"source": {
"type": "integer",
"description": "the dependency's source revision"
}
},
"required": [
"artifact",
"branch",
"source"
]
},
"recorded": {
"type": "string",
"description": "what the dependent recorded: version and digest, or the fact"
},
"newest": {
"type": "string",
"description": "what is newest: version and digest, or the fact"
},
"act": {
"type": "string",
"description": "the act: a rebuild for a stale edge (kinds 1, 3), none for an ordering edge, which is shown only"
}
},
"required": [
"module",
"kind",
"dependency",
"recorded",
"newest"
]
},
"Artifact": {
"type": "object",
"description": "one artifact of a module in the catalog graph entry",
@@ -2737,5 +2566,5 @@
]
}
},
"form": 5
"form": 6
}
@@ -72,6 +72,33 @@
"digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
},
{
"name": "a module's import set said at its build's end (design 47 H2 H-A-517)",
"of": "event:imports-reported",
"subject": "mesh.seat.node-build-go.event.imports-reported.anchor",
"given": {
"node": "anchor",
"module": "nats",
"fingerprint": "fp-0123",
"commit": "0123456789abcdef0123456789abcdef01234567",
"imports": [
"git.novox.be/novox/mesh-sdk/go/bus",
"git.novox.be/novox/mesh-sdk/go/catalogue"
]
}
},
{
"name": "a module whose programs import no mesh package says an empty set (H-A-532 DQ-2)",
"of": "event:imports-reported",
"subject": "mesh.seat.node-build-go.event.imports-reported.anchor",
"given": {
"node": "anchor",
"module": "feh",
"fingerprint": "fp-4567",
"commit": "89abcdef0123456789abcdef0123456789abcdef",
"imports": []
}
},
{
"name": "a running ask says its progress",
"of": "event:step-progress",
@@ -72,6 +72,32 @@
"digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
},
{
"name": "a module's import set said at its build's end (design 47 H2 H-A-517)",
"of": "event:imports-reported",
"subject": "mesh.seat.node-build-node.event.imports-reported.anchor",
"given": {
"node": "anchor",
"module": "nats",
"fingerprint": "fp-0123",
"commit": "0123456789abcdef0123456789abcdef01234567",
"imports": [
"@novox/mesh-sdk"
]
}
},
{
"name": "a module whose programs import no mesh package says an empty set (H-A-532 DQ-2)",
"of": "event:imports-reported",
"subject": "mesh.seat.node-build-node.event.imports-reported.anchor",
"given": {
"node": "anchor",
"module": "feh",
"fingerprint": "fp-4567",
"commit": "89abcdef0123456789abcdef0123456789abcdef",
"imports": []
}
},
{
"name": "a running ask says its progress",
"of": "event:step-progress",
@@ -18,7 +18,6 @@ export declare const verbs: {
readonly watch: "watch";
readonly unwatch: "unwatch";
readonly versions: "versions";
readonly outdated: "outdated";
readonly input: "input";
readonly entry: "entry";
};
@@ -32,7 +31,6 @@ export declare const events: {
readonly room: "room";
readonly registrationChanged: "registration-changed";
readonly versionReleased: "version-released";
readonly versionsFilled: "versions-filled";
};
export declare const family: { readonly name: "mesh-catalog.events"; readonly maxAgeDays: 7 };
@@ -59,10 +57,6 @@ export declare const versionReleasedStream: "SEAT_mesh-catalog_version-released"
export declare const versionReleasedSubject: "mesh.seat.mesh-catalog.event.version-released";
export declare const versionsFilledStream: "SEAT_mesh-catalog_versions-filled";
export declare const versionsFilledSubject: "mesh.seat.mesh-catalog.event.versions-filled";
export declare const states: {
readonly manifests: "manifests";
readonly modules: "modules";
@@ -73,7 +67,6 @@ export declare const states: {
readonly registrations: "registrations";
readonly registrationHistory: "registration-history";
readonly versions: "versions";
readonly buildEdges: "build-edges";
readonly inputs: "inputs";
};
@@ -161,12 +154,6 @@ export declare function versionsByModuleVersionKey(module: string, version: stri
/** The parts of a key of the form "<module>.<version>", or undefined for a key of another form. */
export declare function parseVersionsByModuleVersionKey(_key: string): { module: string; version: string } | undefined;
/** The key of one value of the state build-edges under the form "<module>.<branch>". */
export declare function buildEdgesByModuleBranchKey(module: string, branch: string): string;
/** The parts of a key of the form "<module>.<branch>", or undefined for a key of another form. */
export declare function parseBuildEdgesByModuleBranchKey(_key: string): { module: string; branch: string } | undefined;
/** The key of one value of the state inputs under the form "<time>.<digest>". */
export declare function inputsByTimeDigestKey(time: string, digest: string): string;
@@ -215,17 +202,6 @@ export interface BuildEdge {
"version": string;
}
/** the newest build's edge entries of a module on a watched branch other than the first, keyed by its fingerprint, which releases no version (design 47 G section 374) */
export interface BuildEdges {
"edges": VersionEdge[];
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** the build's fingerprint */
"fp": string;
"source"?: number;
"v": number;
}
/** one module of a catalog graph revision as its manifest declares it, stored once by its digest (ADR 0656, design 47 Two graphs) */
export interface CatalogEntry {
/** the acting rules of the seats it claims */
@@ -401,32 +377,6 @@ export interface Head {
"repository": string;
}
export interface OutdatedDependency {
"artifact": ArtifactRef;
/** the dependency's watched branch */
"branch": string;
/** the dependency's source revision */
"source": number;
}
/** one entry behind, by the part's digest (design 47 G section 375) */
export interface Outdated {
/** the act: a rebuild for a stale edge (kinds 1, 3), none for an ordering edge, which is shown only */
"act"?: string;
/** its build's fingerprint, for a build of another branch */
"build"?: string;
"dependency": OutdatedDependency;
"kind": number;
/** the dependent module */
"module": string;
/** what is newest: version and digest, or the fact */
"newest": string;
/** what the dependent recorded: version and digest, or the fact */
"recorded": string;
/** its version, or empty for a build of another branch */
"version"?: string;
}
/** a module's policy: its steps' statuses, and per artifact what differs (ADR 0666 section 7) */
export interface Policy {
/** by artifact name, the statuses that differ from the module's */
@@ -828,21 +778,6 @@ export interface VersionsAnswer {
"versions": VersionEntry[];
}
/** is what outdated takes. */
export interface OutdatedInput {
/** a watched branch, to answer for it alone */
"branch"?: string;
/** one dependency, to answer for it alone */
"dependency"?: ArtifactRef;
}
/** is what outdated answers. */
export interface OutdatedAnswer {
"behind": Outdated[];
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
}
/** is what input takes. */
export interface InputInput {
/** 128 random bits the caller chooses: the subject token of this send's chunks and acknowledgements */
@@ -960,16 +895,6 @@ export interface VersionReleasedEvent {
"version": string;
}
/** is the body of the event versions-filled. */
export interface VersionsFilledEvent {
"at": string;
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** how many modules were filled */
"modules"?: number;
"v": number;
}
/** is one value of the state manifests under the key <digest>. */
export interface ManifestsByDigestValue {
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
@@ -1186,9 +1111,6 @@ export type RegistrationHistoryBySourceOwnerNameVersionValue = Registration;
/** is one value of the state versions under the key <module>.<version>. */
export type VersionsByModuleVersionValue = VersionEntry;
/** is one value of the state build-edges under the key <module>.<branch>. */
export type BuildEdgesByModuleBranchValue = BuildEdges;
/** is one value of the state inputs under the key <time>.<digest>. */
export type InputsByTimeDigestValue = string;
@@ -18,7 +18,6 @@ export const verbs = {
watch: "watch",
unwatch: "unwatch",
versions: "versions",
outdated: "outdated",
input: "input",
entry: "entry",
};
@@ -32,7 +31,6 @@ export const events = {
room: "room",
registrationChanged: "registration-changed",
versionReleased: "version-released",
versionsFilled: "versions-filled",
};
export const family = { name: "mesh-catalog.events", maxAgeDays: 7 };
@@ -61,10 +59,6 @@ export const versionReleasedStream = "SEAT_mesh-catalog_version-released";
export const versionReleasedSubject = "mesh.seat.mesh-catalog.event.version-released";
export const versionsFilledStream = "SEAT_mesh-catalog_versions-filled";
export const versionsFilledSubject = "mesh.seat.mesh-catalog.event.versions-filled";
export const states = {
manifests: "manifests",
modules: "modules",
@@ -75,7 +69,6 @@ export const states = {
registrations: "registrations",
registrationHistory: "registration-history",
versions: "versions",
buildEdges: "build-edges",
inputs: "inputs",
};
@@ -328,25 +321,6 @@ export function parseVersionsByModuleVersionKey(_key) {
return { module, version };
}
/** The key of one value of the state build-edges under the form "<module>.<branch>". */
export function buildEdgesByModuleBranchKey(module, branch) {
return module + "." + branch;
}
/** The parts of a key of the form "<module>.<branch>", or undefined for a key of another form. */
export function parseBuildEdgesByModuleBranchKey(_key) {
let _rest = _key;
const _at0 = _rest.indexOf(".");
if (_at0 <= 0) return undefined;
const module = _rest.slice(0, _at0);
_rest = _rest.slice(_at0 + 1);
if (_rest === "") return undefined;
const branch = _rest;
_rest = "";
if (_rest !== "") return undefined;
return { module, branch };
}
/** The key of one value of the state inputs under the form "<time>.<digest>". */
export function inputsByTimeDigestKey(time, digest) {
return time + "." + digest;
@@ -29,6 +29,7 @@ export declare const accepts: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -47,6 +48,12 @@ export declare function toolchainReportedSubject(node: string): string;
export declare const toolchainReportedSubjectAll: "mesh.seat.node-build-go.event.toolchain-reported.*";
export declare const importsReportedStream: "SEAT_node-build-go_imports-reported";
export declare function importsReportedSubject(node: string): string;
export declare const importsReportedSubjectAll: "mesh.seat.node-build-go.event.imports-reported.*";
export declare function stepProgressSubject(node: string): string;
export declare const stepProgressSubjectAll: "mesh.seat.node-build-go.event.step-progress.*";
@@ -142,6 +149,8 @@ export type FetchBesideItem = buildStep.FetchBesideItem;
export type FetchBuildsItem = buildStep.FetchBuildsItem;
export type FetchPackage = buildStep.FetchPackage;
export type FetchRefusal = buildStep.FetchRefusal;
export type ImportsReported = buildStep.ImportsReported;
export type ImportsReportedEvent = buildStep.ImportsReportedEvent;
export type InstallAsk = buildStep.InstallAsk;
export type KeptArtifactAnswer = buildStep.KeptArtifactAnswer;
export type KeptArtifactInput = buildStep.KeptArtifactInput;
@@ -27,6 +27,7 @@ export const accepts = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -49,6 +50,14 @@ export function toolchainReportedSubject(node) {
export const toolchainReportedSubjectAll = "mesh.seat.node-build-go.event.toolchain-reported.*";
export const importsReportedStream = "SEAT_node-build-go_imports-reported";
export function importsReportedSubject(node) {
return "mesh.seat.node-build-go.event.imports-reported." + node;
}
export const importsReportedSubjectAll = "mesh.seat.node-build-go.event.imports-reported.*";
export function stepProgressSubject(node) {
return "mesh.seat.node-build-go.event.step-progress." + node;
}
@@ -16,6 +16,7 @@ export declare const verbs: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -215,6 +216,22 @@ export interface FetchRefusal {
"reason": string;
}
/** the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2) */
export interface ImportsReported {
/** the commit the build was made from */
"commit": string;
/** the fingerprint the build was asked for */
"fingerprint": string;
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** each mesh package the module's programs import, by its import path; empty when they import none */
"imports": string[];
/** the module built */
"module": string;
/** the node the build ran on */
"node": string;
}
/** the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers */
export interface InstallAsk {
/** who asked it */
@@ -797,6 +814,9 @@ export type StepEndedEvent = StepEnded;
/** is the body of the event toolchain-reported. */
export type ToolchainReportedEvent = ToolchainReported;
/** is the body of the event imports-reported. */
export type ImportsReportedEvent = ImportsReported;
/** is the body of the event step-progress. */
export type StepProgressEvent = StepProgress;
@@ -16,6 +16,7 @@ export const verbs = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -28,6 +28,7 @@ export declare const accepts: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -46,6 +47,12 @@ export declare function toolchainReportedSubject(node: string): string;
export declare const toolchainReportedSubjectAll: "mesh.seat.node-build-image.event.toolchain-reported.*";
export declare const importsReportedStream: "SEAT_node-build-image_imports-reported";
export declare function importsReportedSubject(node: string): string;
export declare const importsReportedSubjectAll: "mesh.seat.node-build-image.event.imports-reported.*";
export declare function stepProgressSubject(node: string): string;
export declare const stepProgressSubjectAll: "mesh.seat.node-build-image.event.step-progress.*";
@@ -139,6 +146,8 @@ export type FetchBesideItem = buildStep.FetchBesideItem;
export type FetchBuildsItem = buildStep.FetchBuildsItem;
export type FetchPackage = buildStep.FetchPackage;
export type FetchRefusal = buildStep.FetchRefusal;
export type ImportsReported = buildStep.ImportsReported;
export type ImportsReportedEvent = buildStep.ImportsReportedEvent;
export type InstallAsk = buildStep.InstallAsk;
export type KeptArtifactAnswer = buildStep.KeptArtifactAnswer;
export type KeptArtifactInput = buildStep.KeptArtifactInput;
@@ -26,6 +26,7 @@ export const accepts = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -48,6 +49,14 @@ export function toolchainReportedSubject(node) {
export const toolchainReportedSubjectAll = "mesh.seat.node-build-image.event.toolchain-reported.*";
export const importsReportedStream = "SEAT_node-build-image_imports-reported";
export function importsReportedSubject(node) {
return "mesh.seat.node-build-image.event.imports-reported." + node;
}
export const importsReportedSubjectAll = "mesh.seat.node-build-image.event.imports-reported.*";
export function stepProgressSubject(node) {
return "mesh.seat.node-build-image.event.step-progress." + node;
}
@@ -16,6 +16,7 @@ export declare const verbs: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -215,6 +216,22 @@ export interface FetchRefusal {
"reason": string;
}
/** the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2) */
export interface ImportsReported {
/** the commit the build was made from */
"commit": string;
/** the fingerprint the build was asked for */
"fingerprint": string;
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** each mesh package the module's programs import, by its import path; empty when they import none */
"imports": string[];
/** the module built */
"module": string;
/** the node the build ran on */
"node": string;
}
/** the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers */
export interface InstallAsk {
/** who asked it */
@@ -797,6 +814,9 @@ export type StepEndedEvent = StepEnded;
/** is the body of the event toolchain-reported. */
export type ToolchainReportedEvent = ToolchainReported;
/** is the body of the event imports-reported. */
export type ImportsReportedEvent = ImportsReported;
/** is the body of the event step-progress. */
export type StepProgressEvent = StepProgress;
@@ -16,6 +16,7 @@ export const verbs = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -29,6 +29,7 @@ export declare const accepts: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -47,6 +48,12 @@ export declare function toolchainReportedSubject(node: string): string;
export declare const toolchainReportedSubjectAll: "mesh.seat.node-build-node.event.toolchain-reported.*";
export declare const importsReportedStream: "SEAT_node-build-node_imports-reported";
export declare function importsReportedSubject(node: string): string;
export declare const importsReportedSubjectAll: "mesh.seat.node-build-node.event.imports-reported.*";
export declare function stepProgressSubject(node: string): string;
export declare const stepProgressSubjectAll: "mesh.seat.node-build-node.event.step-progress.*";
@@ -142,6 +149,8 @@ export type FetchBesideItem = buildStep.FetchBesideItem;
export type FetchBuildsItem = buildStep.FetchBuildsItem;
export type FetchPackage = buildStep.FetchPackage;
export type FetchRefusal = buildStep.FetchRefusal;
export type ImportsReported = buildStep.ImportsReported;
export type ImportsReportedEvent = buildStep.ImportsReportedEvent;
export type InstallAsk = buildStep.InstallAsk;
export type KeptArtifactAnswer = buildStep.KeptArtifactAnswer;
export type KeptArtifactInput = buildStep.KeptArtifactInput;
@@ -27,6 +27,7 @@ export const accepts = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -49,6 +50,14 @@ export function toolchainReportedSubject(node) {
export const toolchainReportedSubjectAll = "mesh.seat.node-build-node.event.toolchain-reported.*";
export const importsReportedStream = "SEAT_node-build-node_imports-reported";
export function importsReportedSubject(node) {
return "mesh.seat.node-build-node.event.imports-reported." + node;
}
export const importsReportedSubjectAll = "mesh.seat.node-build-node.event.imports-reported.*";
export function stepProgressSubject(node) {
return "mesh.seat.node-build-node.event.step-progress." + node;
}
@@ -16,6 +16,7 @@ export declare const verbs: {
export declare const events: {
readonly stepEnded: "step-ended";
readonly toolchainReported: "toolchain-reported";
readonly importsReported: "imports-reported";
readonly stepProgress: "step-progress";
readonly askTaken: "ask-taken";
};
@@ -215,6 +216,22 @@ export interface FetchRefusal {
"reason": string;
}
/** the mesh packages a module's programs import, said by the build module at a build's end (design 47 H2 H-A-517, H-A-532 DQ-2): the import closure without tests, each package by its import path, the union over the module's programs (H-A-518); the indexer keeps it only for the fingerprint main's modules state holds (H-A-532 DMC-2) */
export interface ImportsReported {
/** the commit the build was made from */
"commit": string;
/** the fingerprint the build was asked for */
"fingerprint": string;
/** is the form of what this value carries, left out while it is 1 (design 47 H2 §780). */
"form"?: number;
/** each mesh package the module's programs import, by its import path; empty when they import none */
"imports": string[];
/** the module built */
"module": string;
/** the node the build ran on */
"node": string;
}
/** the job of an ask of the kind install (design 47 H2 §800, H-A-367 (4), H-A-403): the npm tree a module's package lock names, installed with an integrity-checked install and no install scripts, and published to the artifact store (the seat oci-artifact-registry) as the module's archive <module>:node-modules under the ask's version, which the builder's reservation covers */
export interface InstallAsk {
/** who asked it */
@@ -797,6 +814,9 @@ export type StepEndedEvent = StepEnded;
/** is the body of the event toolchain-reported. */
export type ToolchainReportedEvent = ToolchainReported;
/** is the body of the event imports-reported. */
export type ImportsReportedEvent = ImportsReported;
/** is the body of the event step-progress. */
export type StepProgressEvent = StepProgress;
@@ -16,6 +16,7 @@ export const verbs = {
export const events = {
stepEnded: "step-ended",
toolchainReported: "toolchain-reported",
importsReported: "imports-reported",
stepProgress: "step-progress",
askTaken: "ask-taken",
};
@@ -199,7 +199,6 @@ func main() {
// The seat mesh-catalog's verb revision, a first view of the catalog half answered in this runtime of its own to exactly
// the parts whose entry declares it (novox/hq ADR 0663).
tools = append(tools, index.RevisionTool(revisions, kept), index.EntryTool(revisions, keptRead{stdio.State(index.EntryIndexState)}), index.EntriesTool(revisions, keptRead{stdio.State(index.EntryIndexState)}, keptRead{stdio.State(index.NamedState)}), entryReadTool(revisions), index.VersionsTool(keptRead{stdio.State(index.VersionsState)}),
index.OutdatedTool(&index.Indexer{Versions: keptRead{stdio.State(index.VersionsState)}, Heard: keptRead{stdio.State(index.HeardState)}, Revisions: revisions}),
index.InputsReadTool(keptRead{stdio.State(index.InputsState)}, stateobjects.ForState(index.InputsState).Objects))
tools = append(tools, index.CatalogRevisionTools(revisions, asks, time.Now, func(what, why string) error {
_, err := acts.Record(meshhandactsclient.Request{What: what, Why: why, Cause: index.DropCandidateGraphTool, Verb: "drop-candidate-graph"})
@@ -231,8 +230,9 @@ func main() {
_, err := acts.Record(meshhandactsclient.Request{What: what, Why: why, Cause: index.FingerprintsAgainTool, Verb: "fingerprints-again"})
return err
}, 10*time.Second)...)
tools = append(tools, configReadersTool(watched, trunk.State("modules")), busStateTool(trunk.State), requirementsTool(keptSource),
packageUsersTool(trunk.State), seatDefinitionTool(keptSource), outOfStepTool(os.Getenv(stdio.ServedAs), keptSource))
tools = append(tools, configReadersTool(watched, trunk.State("modules")), busStateTool(trunk.State),
packageUsersTool(trunk.State), seatDefinitionTool(keptSource), outOfStepTool(os.Getenv(stdio.ServedAs), keptSource),
index.ImportsReadTool(keptRead{stdio.State(index.ImportsState)}))
if err := stdio.Serve("", tools); err != nil {
fmt.Fprintf(os.Stderr, "[mesh-delivery-indexer-tools] %v\n", err)
os.Exit(1)
@@ -88,37 +88,6 @@ func busStateTool(state func(string) views.Source) stdio.Tool {
}}
}
// requirementsTool is indexer_requirements (REG S15; DLV-I7): the versions of one mesh Go module its consumers' go.sum
// files require, from the indexer's requirements state, kept at each merge. The builder's floor numbers no version below
// the highest.
func requirementsTool(state func(string) views.Source) stdio.Tool {
return stdio.Tool{Name: index.RequirementsTool,
Description: "The versions of one mesh Go module (its module path, as go.sum names it) that the trunk's consumers require: " +
"the highest each consumer's go.sum names, distinct, highest last, kept by the indexer at each merge. The builder " +
"numbers no version of the package below the highest.",
Input: map[string]any{"type": "object", "required": []string{"package"}, "properties": map[string]any{
"package": map[string]any{"type": "string", "description": "the mesh Go module's path, such as git.novox.be/novox/mesh-sdk/go"}}},
Run: func(args map[string]any) (any, error) {
pkg, _ := args["package"].(string)
if pkg == "" {
return nil, fmt.Errorf("%s names the package", index.RequirementsTool)
}
e, found, err := state(index.RequirementsState).Get(pkg)
if err != nil {
return nil, fmt.Errorf("the requirements state cannot be read: %w", err)
}
var value []byte
if found {
value = e.Value
}
versions, err := index.RequirementsOf(value, found)
if err != nil {
return nil, err
}
return map[string]any{"package": pkg, "requirements": versions}, nil
}}
}
// packageUsersTool is indexer_package_users (design 32 *A package, its series, and the series its users accept*; DLV-I8):
// per package, its users and the series each accepts, read from the indexer's own states.
func packageUsersTool(state func(string) views.Source) stdio.Tool {
@@ -1,120 +0,0 @@
//go:build integration
package main
import (
"context"
"encoding/json"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/busretry"
"mesh-delivery-indexer/internal/index"
)
// TestIndexerFillsTheFloorOfAModuleWithTags (design 47 G §412 as A-490c to A-490h amend it): the whole indexer on a real bus, the
// seat git and the package holders stood in. A module of the trunk with a Go package and no version in `versions` stays unfilled
// while the forge does not answer, and is filled from the highest of its tags and the holder's versions once the forge answers,
// with no restart and no catalog revision: the kept call gives up after its bound (one second here, so that it is spent before the
// forge answers) and the fill asks it again at once (A-490i, ADR 0668 §3). The finding after five minutes is in the unit tests (the
// five minutes are not waited for here).
func TestIndexerFillsTheFloorOfAModuleWithTags(t *testing.T) {
t.Cleanup(busretry.Waits(time.Second, 50*time.Millisecond, 200*time.Millisecond)) // the form gives up after one second
const pkg = "git.novox.be/novox/mesh-delivery/modules/" + testIndexer
var serveTags func()
var prefix atomic.Value
js, ctx, _, _ := startIndexer(t, func(context.Context, buildLog) {}, func(ctx context.Context, js jetstream.JetStream) {
for _, bucket := range []string{index.Bucket(testIndexer, index.VersionsState), index.Bucket(testIndexer, index.HeardState)} {
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: bucket, History: 1}); err != nil {
t.Fatal(err)
}
}
// the module's artifacts are Go packages here, so that the indexer's own entries carry their names (read from go.mod, §676)
e := trunkIndexerEntryOf(t, ctx, js, func(raw []byte) []byte {
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
m["build"] = map[string]any{"artifacts": []any{map[string]any{"name": "go", "kind": "package", "language": "go"}}}
out, _ := json.Marshal(m)
return out
})
for i := range e.Artifacts {
e.Artifacts[i].Package = &meshcatalog.ArtifactPackage{Ecosystem: index.EcosystemGo, Name: pkg}
}
seedBuildModules(t, ctx, js, map[string]meshcatalog.CatalogEntry{testIndexer: e})
reply := func(m *nats.Msg, body map[string]any) {
body["node"] = "n0"
raw, _ := json.Marshal(body)
_ = m.Respond(raw)
}
serve := func(subject string, h func(m *nats.Msg)) {
if _, err := js.Conn().Subscribe(subject, h); err != nil {
t.Fatal(err)
}
}
// the forge answers no one until the test lets it (nobody serves the verb: a transport fault, which the kept call asks again)
serveTags = func() {
serve("mesh.seat.git.tool.tags", func(m *nats.Msg) {
var in git.TagsInput
_ = json.Unmarshal(m.Data, &in)
prefix.Store(in.Prefix)
reply(m, map[string]any{"result": git.TagsAnswer{Repository: in.Repository, Tags: []git.Tag{{Tag: in.Prefix + "0.4.2", Commit: strings.Repeat("a", 40)}, {Tag: in.Prefix + "0.4.10", Commit: strings.Repeat("b", 40)}, {Tag: "unrelated", Commit: strings.Repeat("c", 40)}}}})
})
}
// the package's name is read from the revision's own files (§676): its go.mod
serve("mesh.seat.git.tool.file", func(m *nats.Msg) {
var in git.FileInput
_ = json.Unmarshal(m.Data, &in)
if strings.HasSuffix(in.Path, "go.mod") {
reply(m, map[string]any{"result": git.FileAnswer{Path: in.Path, Ref: in.Ref, Content: "module " + pkg + "\n\ngo 1.26\n"}})
return
}
reply(m, map[string]any{"result": git.FileAnswer{Path: in.Path, Ref: in.Ref, Absent: true}})
})
serve("mesh.seat.go-package-registry.tool.versions", func(m *nats.Msg) {
reply(m, map[string]any{"result": map[string]any{"name": pkg, "versions": []any{}}})
})
})
versions, err := js.KeyValue(ctx, index.Bucket(testIndexer, index.VersionsState))
if err != nil {
t.Fatal(err)
}
// the forge is asked at the start and does not answer: the form gives up and the module's clock is kept in the state heard
heard, err := js.KeyValue(ctx, index.Bucket(testIndexer, index.HeardState))
if err != nil {
t.Fatal(err)
}
for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
if _, err := heard.Get(ctx, index.FloorSinceKey(testIndexer)); err == nil {
break
}
}
if _, err := heard.Get(ctx, index.FloorSinceKey(testIndexer)); err != nil {
t.Fatalf("the unanswered floor read of the module is not kept within 30 s: %v", err)
}
if keys, _ := versions.Keys(ctx); len(keys) != 0 {
t.Fatalf("versions holds %v while the forge does not answer, want nothing", keys)
}
serveTags()
var got []string
for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
if got, _ = versions.Keys(ctx); len(got) > 0 {
break
}
}
if len(got) != 1 || !strings.Contains(got[0], "0.4.10") {
t.Fatalf("versions holds %v within 30 s of the forge answering, want the floor 0.4.10 of its tags", got)
}
if p, _ := prefix.Load().(string); p != "modules/"+testIndexer+"/v" {
t.Errorf("the tags were read with the prefix %q, want the package's directory and /v", p)
}
}
@@ -395,7 +395,6 @@ func startIndexerRun(t *testing.T, put func(context.Context, buildLog), before .
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS", Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.mesh-catalog.event.catalog-revision.*", "mesh.seat.mesh-catalog.event.filling",
"mesh.seat.mesh-catalog.event.full", "mesh.seat.mesh-catalog.event.room", "mesh.seat.mesh-catalog.event.seat-definition-changed",
"mesh.seat.mesh-catalog.event.seat-definition-removed", "mesh.seat.mesh-catalog.event.manifest-accepted", "mesh.seat.mesh-catalog.event.version-released",
"mesh.seat.mesh-catalog.event.versions-filled",
"mesh.seat.mesh-conditions.event.>", "mesh.seat.operator-channel.event.>", "mesh.seat.go-package-registry.event.>", "mesh.seat.npm-package-registry.event.>",
"mesh.seat.mesh-module-assigner.event.>", "mesh.seat.node-build-go.event.>", meshbuilds.SubjectVersionReserved}}); err != nil { // not the seats kept in streams of their own (wanted and running, above)
t.Fatal(err)
@@ -802,9 +801,9 @@ func serveAssignerAssignments(t *testing.T, ctx context.Context, js jetstream.Je
if _, err := js.CreateOrUpdateConsumer(ctx, "EVENTS", jetstream.ConsumerConfig{Durable: "n1_mesh-delivery-indexer", AckPolicy: jetstream.AckExplicitPolicy,
// and the build seat's step-ended the manifest's consumes names (design 47 G §713: the end of a validation ask), and the
// builder's version-reserved, which no stream of its own keeps (design 47 H2 §805), and the Go package registry seat's
// published, a series' newest a pin names (H-A-495 addendum).
// published, a series' newest a pin names (H-A-495 addendum), and the Go build seat's imports-reported (design 47 H2 H-A-517).
FilterSubjects: []string{"mesh.mod." + assignerHolderModule + ".event.views.>", meshcatalog.SubjectRoom, nodebuildgo.SubjectStepEndedAll, meshbuilds.SubjectVersionReserved,
gopackageregistry.SubjectPublished}}); err != nil {
gopackageregistry.SubjectPublished, nodebuildgo.SubjectImportsReportedAll}}); err != nil {
t.Fatal(err)
}
em := views.Emitter{Owner: assignerHolderModule, Subject: process.Account{Node: "n1", Module: assignerHolderModule}.EventSubject,
@@ -24,8 +24,8 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
@@ -287,12 +287,9 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// How many modules use each old section (issue 1966 D4): a state this delivery brings, bound when it appears; until then
// the judge refuses no use of an old section.
oldSections := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.OldSectionsState), "the count of the old sections is not kept, so the judge refuses no use of one", logger.Printf)
// What each consumer's go.sum requires of each mesh Go module (DLV-I7): a state this delivery brings, bound when it
// appears; until then indexer_requirements answers none, and the builder's floor waits on its answer.
requirements := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.RequirementsState), "what consumers require is not kept", logger.Printf)
// The module graph (ADR 0603 §2) is held in memory, read with the view: each revision's entries carry its nodes.
// The state heard (A-80): the forge messages handled (key forge) and what the indexer heard and compares later (the time a call is
// unanswered since, the newest toolchain-agreed, the artifacts published so far of a version).
// unanswered since, the artifacts published so far of a version).
heardStore := awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.HeardState), "what the indexer heard is not kept", logger.Printf)}
// The runs on request the indexer holds a candidate for (A-174): a state this delivery brings, bound when it appears.
runs := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.RunsState), "no run on request's candidate is written or dropped", logger.Printf)
@@ -330,7 +327,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}, seatLists)
readWhenBound(seatReader, seatDefs, marks)
keepSeatListAtStart(ctx, seatDefs, seatBus.defs, seatLists, logger.Printf)
var fillFollow atomic.Pointer[versionsFill]
// Kept while named (design 47 G §675): the want and the running build that name a fingerprint, heard below.
named := index.NewNamed(awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.NamedState), "no entry is kept for a want or a running build that names it", logger.Printf)}, logger.Printf)
pinsBucket := process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.PinsState), "no record's pin on a catalog graph revision is kept, so no revision is removed", logger.Printf)
@@ -356,10 +352,10 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
logger.Printf("the state %s is not cleared at this start: %v", index.DryRunsState, err)
}
})
ix := &index.Indexer{Module: cred.Module, TakeIns: awaitedStore{b: takeIns}, DryRuns: awaitedStore{b: dryRuns}, NamedSets: named, Findings: writer, OldSections: awaitedStore{b: oldSections}, Requirements: awaitedStore{b: requirements}, Store: kvStore{candidates}, Modules: modules, Manifests: kvStore{manifests}, Taken: awaitedStore{b: taken}, Builds: known,
ix := &index.Indexer{Module: cred.Module, TakeIns: awaitedStore{b: takeIns}, DryRuns: awaitedStore{b: dryRuns}, NamedSets: named, Findings: writer, OldSections: awaitedStore{b: oldSections}, Store: kvStore{candidates}, Modules: modules, Manifests: kvStore{manifests}, Taken: awaitedStore{b: taken}, Builds: known,
Predefined: awaitedStore{b: predefined}, Logf: logger.Printf,
Named: namedVia(calls.Call), Trunk: trunkVia(calls.Call), BranchHead: branchHeadVia(calls.Call), Contains: containsVia(calls.Call), Read: readVia(calls.Call),
Packages: awaitedStore{b: packages, js: js, name: index.Bucket(cred.Module, index.PackagesState)}, Files: filesVia(calls.Call), GoSum: goSumVia(calls.Call), GoMod: goModVia(calls.Call),
Packages: awaitedStore{b: packages, js: js, name: index.Bucket(cred.Module, index.PackagesState)}, Files: filesVia(calls.Call), GoMod: goModVia(calls.Call),
Heard: heardStore, Runs: awaitedStore{b: runs}, Graph: graph,
// How long a reservation is kept and how long its gathering waits at most (design 47 H2 §805, H-A-424).
ReservedKeep: durationSetting("reserved-keep", index.DefaultReservedKeep, logger.Printf),
@@ -371,33 +367,28 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
Revisions: revisions, EntryIndex: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.EntryIndexState), "no entry is found by its fingerprint", logger.Printf)}, // Message a kept call: a read, called again through a transport fault (ADR 0668 §1)
// Each catalog revision may bring another holder of a build seat: the build modules are found again (buildmodules.go).
// A new trunk revision that changes the modules is said on the views family of modules too (design 47 G A-360).
SayCatalogRevision: afterRevision(refreshingBuildModules(sayingModulesView(sayCatalogRevision(cred, views.JetStreamPublish(js)), cred, views.JetStreamPublish(js)), &buildFollow), &fillFollow),
SayCatalogRevision: refreshingBuildModules(sayingModulesView(sayCatalogRevision(cred, views.JetStreamPublish(js)), cred, views.JetStreamPublish(js)), &buildFollow),
SayFill: sayFill(conn, cred),
// The catalog's released versions (design 47 G §349): the state versions, bound when it appears, and the event version-released.
Versions: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.VersionsState), "no released version is kept, so no package-published makes a version", logger.Printf)},
BuildEdges: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.BuildEdgesState), "no build of another watched branch keeps its edges", logger.Printf)},
Pins: pinsStore, PinsPending: pendingOf(js, cred),
Versions: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.VersionsState), "no released version is kept, so no package-published makes a version", logger.Printf)},
Pins: pinsStore, PinsPending: pendingOf(js, cred),
Held: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.HeldState), "no held take-in is kept, so indexer_pending reads none", logger.Printf)},
Imports: awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.ImportsState), "no import set is kept, so every module keeps the version line", logger.Printf)},
Inputs: inputsStore,
InputObjects: inObjects,
SayVersionReleased: sayVersionReleased(conn, cred), SayVersionsFilled: sayVersionsFilled(conn, cred),
SayTakeIn: sayTakeIn(js, cred)}
SayVersionReleased: sayVersionReleased(conn, cred),
SayTakeIn: sayTakeIn(js, cred)}
// The registrations and the changes that wait for their warrant (design 47 G §2, §667): their states are bound when they
// appear; a warrant is heard on the router's decided event for this module, below.
registry := newRegistry(js, conn, cred, calls.Call,
awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.RegistrationsState), "no registration is kept or written", logger.Printf)},
awaitedStore{b: process.AwaitBucket(ctx, js, conn, index.Bucket(cred.Module, index.ProposalsState), "no change of a registration waits for its warrant", logger.Printf)},
routerRecordOf(cred.Module, calls.Call, calls.Ask), ix, logger.Printf)
registry.Pruned = ix.PruneBranchBuilds
ix.Registry = registry
// The gate's source revisions, on one durable per watched branch (design 47 H §743, H-A-90), bound below.
sources := &sourceMoved{ctx: ctx, ix: ix, branches: watchedBranches(registry), bind: bindBranch(js, cred, logger.Printf), source: sourceVia(calls.Call), logf: logger.Printf}
defer sources.stop()
named.Changed = ix.RemoveUnlisted
// The first fill of the versions (design 47 G §372): at the start, and again at each catalog revision kept until it is made.
fill := &versionsFill{ix: ix, ctx: ctx, ask: versionsVia(calls.CallKeptWhileOpen, ix.ModuleInNewestView, logger.Printf), floor: index.FloorSources{Tags: tagsVia(calls.CallKept), Holder: holderVia(calls.CallKept)}, logf: logger.Printf}
fillFollow.Store(fill)
fill.kick()
ix.SeedModules = func(ctx context.Context) ([]index.SeedModule, error) {
r := seatReader.Reader()
if r == nil {
@@ -424,19 +415,16 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
done = step("reading the build log")
// The log's entries at the start are read before any fingerprint is computed (below).
var started atomic.Bool
var startEnds []stdio.LogEntry // the log's entries read at the start, whose imports are kept once the packages are published
var startEnds []stdio.LogEntry // the log's entries read at the start, whose out-of-step findings are judged below
if err := calls.ReadLog(builds.BuilderModule, builds.BuilderLog).Watch("", stdio.LogFromAll, func(le stdio.LogEntry) error {
if err := known.Put(le.Value); err != nil {
logger.Printf("%s entry %d is not read: %v", builds.BuildLogRead, le.Sequence, err)
return nil
}
if started.Load() {
// A trunk build's generated files out of step with their seat definitions (DLV-I20).
// A trunk build's generated files out of step with their seat definitions (DLV-I20). Its imports are not read
// here: the build module says them as imports-reported (design 47 H2 H-A-517, H-A-532 DQ-7).
ix.ApplyOutOfStepBuild(ctx, le.Value)
// A done build's imports are kept on its module (ADR 0593 §2); at the start they are kept once the packages are.
if err := ix.ApplyBuildEnd(ctx, le.Value); err != nil {
logger.Printf("%s entry %d: its imports are not kept: %v", builds.BuildLogRead, le.Sequence, err)
}
} else {
startEnds = append(startEnds, le)
}
@@ -500,8 +488,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
buildFollow.Store(buildModules)
// Only now, with the toolchains read, are the fingerprints computed once (before it every Go module would be written as
// having no toolchain reported, and back).
// The packages the held modules reach and the state does not hold yet are published at their trunk's taken merge, and
// the imports the log's done builds reported are then kept, before the fingerprints are computed (ADR 0593 §2, §4).
// The packages the held modules reach and the state does not hold yet are published at their trunk's taken merge,
// before the fingerprints are computed (ADR 0593 §2, §4).
done()
packages.Ready(func(jetstream.KeyValue) {
done := step("publishing the packages at start")
@@ -511,20 +499,13 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
done()
})
done = step(fmt.Sprintf("the out-of-step findings of %d build ends", len(startEnds)))
values := make([][]byte, len(startEnds))
for i, le := range startEnds {
ix.ApplyOutOfStepBuild(ctx, le.Value)
values[i] = le.Value
if (i+1)%50000 == 0 {
logger.Printf("start: out-of-step findings: %d of %d entries", i+1, len(startEnds))
}
}
done()
if err := ix.ApplyBuildEndsAtStart(ctx, values, func(i int, err error) {
logger.Printf("%s entry %d: its imports are not kept: %v", builds.BuildLogRead, startEnds[i].Sequence, err)
}); err != nil {
logger.Printf("keeping the view after the build ends at start: %v", err)
}
startEnds = nil
done = step("computing the fingerprints")
if err := ix.RecomputeAtStart(ctx); err != nil {
@@ -622,15 +603,15 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}
}()
})
if err := hub.Handle(meshbuilds.SubjectToolchainAgreed, func(m jetstream.Msg) { heardToolchainAgreed(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
if err := hub.Handle(meshwants.SubjectWaitEnded, func(m jetstream.Msg) { heardWaitEnded(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
if err := hub.Handle(nodebuildgo.SubjectStepEndedAll, func(m jetstream.Msg) { heardStepEnded(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
// A build's import set, said by its build module at its end (design 47 H2 H-A-517, H-A-532 DQ-2).
for _, subject := range []string{nodebuildgo.SubjectImportsReportedAll, nodebuildnode.SubjectImportsReportedAll} {
if err := hub.Handle(subject, func(m jetstream.Msg) { heardImportsReported(ctx, ix, m, logger.Printf) }); err != nil {
return err
}
}
if err := hub.Handle(decidedSubject(cred.Module), func(m jetstream.Msg) { heardDecided(ctx, registry, m, logger.Printf) }); err != nil {
return err
}
@@ -137,13 +137,7 @@ func filesVia(call toolCaller) func(ctx context.Context, repository, sha string,
}
}
// goSumVia reads a module directory's go.sum at a commit: the version line's packages of a module whose build reported
// no imports (ADR 0593 §2). A directory with no go.sum answers nothing.
func goSumVia(call toolCaller) func(ctx context.Context, repository, sha, dir string) ([]byte, error) {
return goFileVia(call, "go.sum")
}
// goModVia reads a module directory's go.mod at a commit, as goSumVia reads its go.sum: the directory replaces of its own
// goModVia reads a module directory's go.mod at a commit: the directory replaces of its own
// repository the version line takes by their content (fingerprint.ReplacedSiblings).
func goModVia(call toolCaller) func(ctx context.Context, repository, sha, dir string) ([]byte, error) {
return goFileVia(call, "go.mod")
@@ -64,16 +64,18 @@ func untilModule(t *testing.T, ctx context.Context, js jetstream.JetStream, name
return m
}
// TestASourceRevisionMovingMeshSDKNamesItAndItsImporters (design 47 H §743; A-476a; ADR 0593 §2 to §4): the indexer whole against
// the bus. Two Go modules of the catalogue, importer, whose go.mod requires mesh-sdk's Go module at the zero version (no
// go.sum line names it, ADR 0573 §2; design 47 H-A-157), and plain, which requires
// nothing of it, are taken in with mesh-sdk as main's first source revision. A source revision moving mesh-sdk to a commit
// changing its buildstep package is taken in as one revision whose movers are mesh-sdk and importer, of another repository,
// and not plain; the packages key of mesh-sdk/go names that commit with a digest per package. Design 47 H2 §804: a key a dry
// TestASourceRevisionMovingMeshSDKNamesItAndItsImporters (design 47 H §743; A-476a as H2 H-A-520 amends it; ADR 0593 §2 to
// §4; test 80): the indexer whole against the bus. Four Go modules of the catalogue are taken in with mesh-sdk as main's first
// source revision: importer, requirer and legacy, whose go.mod requires mesh-sdk's Go module at the zero version (no go.sum
// line names it, ADR 0573 §2; design 47 H-A-157), and plain, which requires nothing of it. importer's build reports that it
// imports mesh-sdk's buildstep package, requirer's that it imports announce (imports-reported, H-A-517), and legacy reports
// none. A source revision moving mesh-sdk to a commit changing buildstep alone is taken in as one revision whose movers are
// mesh-sdk, importer, of another repository, and legacy, by its requirement (H-A-528), never requirer, which imports none of
// it, nor plain (I10/AC1); the packages key of mesh-sdk/go names that commit with a digest per package. Design 47 H2 §804: a key a dry
// run left in the state dry-runs is gone at the start, and the take-in of a branch moving mesh-sdk again, a dry run, leaves
// the trunk's packages state byte for byte as before and no key in dry-runs once it answered.
//
// Design 47 H2 §802 (H-A-453 (3)): the catalogue holds 36 modules, among them lib-a and lib-b, required by app-a (a require) and
// Design 47 H2 §802 (H-A-453 (3)): the catalogue holds 38 modules, among them lib-a and lib-b, required by app-a (a require) and
// app-b (a require and a replace by a directory); a source revision moving the catalogue to a commit that changes a test file
// of lib-a and one of lib-b, and so their trees alone, moves lib-a, lib-b and their importers alone, never the other 32
// modules whose repository's commit moved too.
@@ -81,8 +83,9 @@ func untilModule(t *testing.T, ctx context.Context, js jetstream.JetStream, name
// Design 47 H2 §805 (H-A-453 (3)) and H-A-495 with its addendum: the builder's twenty version-reserved of mesh-sdk in that
// revision's pipeline (twenty artifacts of its Go package, as repin_test.go reads them) are kept in heard and gathered, and
// they and its pipeline-started move no pin: a pin names only a published version. The release of the reserved version (the
// Go package registry seat's published and every artifact's package-published) keeps one re-pin revision of main, importer
// its mover pinned to it; the next pipeline's reservation keeps none, so the revision after it is the next release's.
// Go package registry seat's published and every artifact's package-published) keeps one re-pin revision of main, legacy,
// on the version line, its mover pinned to it, and importer, on the import form, never named again (I10/AC2; H-A-521,
// H-A-530); the next pipeline's reservation keeps none, so the revision after it is the next release's.
func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
const (
sdkGo = "git.novox.be/novox/mesh-sdk/go"
@@ -115,13 +118,17 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
"package.json": "3333333333333333333333333333333333333333", "package-lock.json": "4444444444444444444444444444444444444444",
"tsconfig.json": "5555555555555555555555555555555555555555"}}}
}
var packages, dryRuns, heardKV jetstream.KeyValue
var packages, imports, dryRuns, heardKV jetstream.KeyValue
var heard *takeIns
js, ctx, _, _ := startIndexer(t, func(context.Context, buildLog) {}, func(ctx context.Context, js jetstream.JetStream) {
var err error
if packages, err = js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: index.Bucket(testIndexer, index.PackagesState), History: index.PackagesHistory}); err != nil {
t.Fatal(err)
}
// The state imports, where a reported import set is kept (H-A-527).
if imports, err = js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: index.Bucket(testIndexer, index.ImportsState), History: 1}); err != nil {
t.Fatal(err)
}
// The state taken, which names each repository's taken commit the packages are published at (ADR 0593 §2).
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: index.Bucket(testIndexer, index.TakenState), History: 1}); err != nil {
t.Fatal(err)
@@ -171,15 +178,20 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
if _, err := dryRuns.Put(ctx, index.DryRunPrefix("beta", "0123")+index.PackagesState+".left", []byte(`{"value":"e30="}`)); err != nil {
t.Fatal(err)
}
catalogue := repoAt{trees: map[string]string{"modules/importer": "t1", "modules/plain": "t2"},
catalogue := repoAt{trees: map[string]string{"modules/importer": "t1", "modules/plain": "t2", "modules/requirer": "t3", "modules/legacy": "t4"},
files: map[string]string{"modules/importer/module.json": named("importer"), "modules/plain/module.json": named("plain"),
"modules/requirer/module.json": named("requirer"), "modules/legacy/module.json": named("legacy"),
"modules/requirer/go.mod": goModContent, "modules/requirer/go.sum": "golang.org/x/sys v0.1.0 h1:x=\n",
"modules/legacy/go.mod": goModContent, "modules/legacy/go.sum": "golang.org/x/sys v0.1.0 h1:x=\n",
"modules/importer/go.mod": goModContent, "modules/importer/go.sum": "golang.org/x/sys v0.1.0 h1:x=\n",
"modules/plain/go.mod": "module plain\n\nrequire golang.org/x/sys v0.1.0\n", "modules/plain/go.sum": "golang.org/x/sys v0.1.0 h1:x=\n"},
paths: map[string]map[string]string{"": {"modules/lib-a": "a1", "modules/lib-b": "b1"}}}
registrations := []meshcatalog.Registration{{V: 1, Module: "importer", Origin: "novox/mesh-catalog", Path: "modules/importer", Branches: []string{"main"}},
{V: 1, Module: "plain", Origin: "novox/mesh-catalog", Path: "modules/plain", Branches: []string{"main"}},
{V: 1, Module: "requirer", Origin: "novox/mesh-catalog", Path: "modules/requirer", Branches: []string{"main"}},
{V: 1, Module: "legacy", Origin: "novox/mesh-catalog", Path: "modules/legacy", Branches: []string{"main"}},
{V: 1, Module: "mesh-sdk", Origin: "novox/mesh-sdk", Path: ".", Branches: []string{"main", "beta"}}}
// §802: 34 more modules of the catalogue, 36 with importer and plain: the libraries, their importers and 30 others.
// §802: 34 more modules of the catalogue, 38 with importer, requirer, legacy and plain: the libraries, their importers and 30 others.
goMods := map[string]string{"lib-a": "module " + catalogModule + "lib-a\n", "lib-b": "module " + catalogModule + "lib-b\n",
"app-a": "module app-a\n\nrequire " + catalogModule + "lib-a v0.0.0-00010101000000-000000000000\n",
"app-b": "module app-b\n\nrequire " + catalogModule + "lib-b v0.0.0-00010101000000-000000000000\n\nreplace " + catalogModule + "lib-b => ../lib-b\n"}
@@ -251,6 +263,17 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
if _, ok := plain.Packages[sdkGo]; ok {
t.Fatalf("plain requires %s: %+v", sdkGo, plain.Packages)
}
// importer's and requirer's builds end, reporting their import sets (H-A-517), kept in the state imports; their
// fingerprints stay as they were (ADR 0593 §4, H-A-529), so requirer is no mover below.
for module, imported := range map[string]string{"importer": sdkGo + "/buildstep", "requirer": sdkGo + "/announce"} {
held := untilModule(t, ctx, js, module, func(m meshcatalog.ModulesByModuleValue) bool { return m.Fp2 != "" })
raw, _ := json.Marshal(nodebuildgo.ImportsReported{Node: "n1", Module: module, Fingerprint: held.Fp2, Commit: catalogMerge, Imports: []string{imported}})
if _, err := js.Publish(ctx, nodebuildgo.SubjectImportsReported("n1"), raw); err != nil {
t.Fatal(err)
}
key, _ := meshcatalogclient.ModulesKey(module)
untilKey(t, ctx, imports, key, func(v []byte) bool { return v != nil })
}
say(11, false, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-sdk", Commit: m2})
taken := heard.next(t, "main", 11)
@@ -259,8 +282,8 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
movers = append(movers, e.Module)
}
slices.Sort(movers)
if !slices.Equal(movers, []string{"importer", "mesh-sdk"}) {
t.Errorf("the take-in of mesh-sdk at %s names the movers %v, want mesh-sdk and its importer, not plain", m2, movers)
if !slices.Equal(movers, []string{"importer", "legacy", "mesh-sdk"}) {
t.Errorf("the take-in of mesh-sdk at %s names the movers %v, want mesh-sdk, the importer of buildstep and legacy by its requirement, not requirer or plain", m2, movers)
}
key, _ := index.PackagesKey(sdkGo)
untilKey(t, ctx, packages, key, func(v []byte) bool {
@@ -278,7 +301,7 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
}
slices.Sort(movers)
if !slices.Equal(movers, []string{"app-a", "app-b", "lib-a", "lib-b"}) {
t.Errorf("the catalogue's commit changing lib-a's and lib-b's tests moves %v of its 36 modules, want lib-a, lib-b and their importers alone", movers)
t.Errorf("the catalogue's commit changing lib-a's and lib-b's tests moves %v of its 38 modules, want lib-a, lib-b and their importers alone", movers)
}
// §805, H-A-495: twenty reservations of mesh-sdk's packages in main's revision of source 12, kept and gathered, and its
@@ -365,17 +388,38 @@ func TestASourceRevisionMovingMeshSDKNamesItAndItsImporters(t *testing.T) {
started(r)
release(r, "0.1.28")
if rev := untilRevision(r + 1); rev.CallKind != meshcatalog.CatalogRevisionCallKindRelease || rev.Call != index.ReleaseCall("mesh-sdk", "0.1.28") ||
len(rev.Movers) != 1 || rev.Movers[0].Module != "importer" {
t.Errorf("main.%d = %+v, want the re-pin revision of the release of mesh-sdk 0.1.28, importer its mover: twenty reservations move no pin", r+1, rev)
len(rev.Movers) != 1 || rev.Movers[0].Module != "legacy" {
t.Errorf("main.%d = %+v, want the re-pin revision of the release of mesh-sdk 0.1.28, legacy (the version line) its one mover: twenty reservations move no pin, and importer and requirer (the import form) are never named again", r+1, rev)
}
untilModule(t, ctx, js, "importer", func(m meshcatalog.ModulesByModuleValue) bool { return m.Packages[sdkGo] == "v0.1.28" })
untilModule(t, ctx, js, "legacy", func(m meshcatalog.ModulesByModuleValue) bool { return m.Packages[sdkGo] == "v0.1.28" })
reserve(r+1, "0.1.29", 1)
started(r + 1)
release(r+1, "0.1.29")
if rev := untilRevision(r + 2); rev.Call != index.ReleaseCall("mesh-sdk", "0.1.29") {
t.Errorf("main.%d = %+v, want the re-pin of the release of mesh-sdk 0.1.29: the reservation of 0.1.29 keeps no revision", r+2, rev)
}
untilModule(t, ctx, js, "importer", func(m meshcatalog.ModulesByModuleValue) bool { return m.Packages[sdkGo] == "v0.1.29" })
untilModule(t, ctx, js, "legacy", func(m meshcatalog.ModulesByModuleValue) bool { return m.Packages[sdkGo] == "v0.1.29" })
// DMC-1, H-A-547 (2): the next take-in moving mesh-sdk (m3 changes buildstep again) names it with no version in the
// import-form importer's entry of that take-in's revision, so the importer's build waits for this pipeline's publish;
// legacy, of the version line, keeps its pin.
heard.acked(t, "main")
say(13, false, meshdelivery.SourceMovedEventHeadsItem{Repository: "novox/mesh-sdk", Commit: m3})
taken = heard.next(t, "main", 13)
untilRevision(taken.Revision)
_, entries, err := index.ReadRevision(ctx, objects, index.BranchObject("main", taken.Revision))
if err != nil {
t.Fatal(err)
}
for module, want := range map[string]string{"importer": "", "legacy": "v0.1.29"} {
i := slices.IndexFunc(entries, func(e meshcatalog.CatalogEntry) bool { return e.Module == module })
if i < 0 {
t.Fatalf("main.%d holds no entry of %s", taken.Revision, module)
}
if v, named := entries[i].Packages[sdkGo]; !named || v != want {
t.Errorf("main.%d's entry of %s names mesh-sdk at %q (named %v), want %q", taken.Revision, module, v, named, want)
}
}
// A branch's take-in moving mesh-sdk to m3 is a dry run: its packages stay in dry-runs while it runs, the trunk's are
// untouched, and its keys go once it answered (§804).
@@ -3,22 +3,16 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-indexer/internal/index"
@@ -56,7 +50,7 @@ type hubStarter interface {
}
// startHearing binds the indexer's durable on the shared events stream and then, beside it, its durable on each kept seat
// event's own stream (SEAT_<seat>_<event>) whose event it handles: package-published, toolchain-agreed and the build seats'
// event's own stream (SEAT_<seat>_<event>) whose event it handles: package-published and the build seats'
// step-ended are never on EVENTS, and its tool runner reads only its own twin there, so the program hears them only so
// (design 47 G A-397; mesh-sdk process.EventHub.StartKept).
func startHearing(ctx context.Context, hub hubStarter, js jetstream.JetStream, cred process.Account) error {
@@ -130,39 +124,6 @@ func heardBuildStepEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg
_ = m.Ack()
}
// heardToolchainAgreed keeps the newest toolchain-agreed of its language (A-68); one that does not decode is said and
// acknowledged, one that cannot be kept is left, so the bus gives it again.
func heardToolchainAgreed(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var t meshbuilds.ToolchainAgreed
if err := json.Unmarshal(m.Data(), &t); err != nil {
logf("%s holds what is no toolchain-agreed, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.HearToolchainAgreed(ctx, t); err != nil {
logf("versions: the toolchain-agreed of %s could not be kept, so the bus gives it again: %v", t.Language, err)
leftForBus(m, "the toolchain-agreed of "+t.Language, err, logf)
return
}
_ = m.Ack()
}
// heardWaitEnded keeps the act of an acting part's ended wait for kind 5 (A-78 a), as heardToolchainAgreed keeps its event.
func heardWaitEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var w meshwants.WaitEndedEvent
if err := json.Unmarshal(m.Data(), &w); err != nil {
logf("%s holds what is no wait-ended, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
if err := ix.HearWaitEnded(ctx, w); err != nil {
logf("versions: the wait-ended of %s for %s could not be kept, so the bus gives it again: %v", w.Part, w.Module, err)
leftForBus(m, fmt.Sprintf("the wait-ended of %s for %s", w.Part, w.Module), err, logf)
return
}
_ = m.Ack()
}
// heardStepEnded deletes the input kept for the run ask a build seat's step-ended names (design 47 G §354, A-78 d).
func heardStepEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e nodebuildgo.StepEnded
@@ -179,124 +140,23 @@ func heardStepEnded(ctx context.Context, ix *index.Indexer, m jetstream.Msg, log
_ = m.Ack()
}
// sayVersionsFilled says versions-filled (design 47 G §372) once, on the seat's stream that keeps it with no age limit.
func sayVersionsFilled(conn *nats.Conn, cred process.Account) func(context.Context, meshcatalog.VersionsFilledEvent, string) error {
return func(_ context.Context, e meshcatalog.VersionsFilledEvent, id string) error {
return saySeatEvent(conn, cred, meshcatalog.EventVersionsFilled, id, e)
}
}
// versionsVia asks the builder's tool builder_versions for one name as a kept call (ADR 0668 §1, §2) asked again while the module is in the newest view (A-190) and reads its answer.
func versionsVia(call openCaller, inView func(ctx context.Context, module string) (bool, error), logf func(string, ...any)) index.VersionsAsker {
return func(ctx context.Context, module, name string) (index.BuilderVersionsAnswer, error) {
var a index.BuilderVersionsAnswer
raw, err := keptWhileOpen(ctx, call, logf, "versions."+name, index.BuilderVersionsCall, map[string]any{"name": name},
func(ctx context.Context) (bool, error) { return inView(ctx, module) })
if err != nil {
return a, err
}
if err := json.Unmarshal(raw, &a); err != nil {
return a, fmt.Errorf("the answer of %s is not a name's versions: %w", index.BuilderVersionsCall, err)
}
return a, nil
}
}
// versionsFill is the first fill of the versions in the background (design 47 G §372): started at the start and at each
// catalog revision kept, until it is made; one runs at a time, and a fill that fails is said and made again at the next.
type versionsFill struct {
ix *index.Indexer
ctx context.Context
ask index.VersionsAsker
floor index.FloorSources // what the floor reads (A-490g); a nil reader fills none
logf func(string, ...any)
}
func (f *versionsFill) kick() {
go func() {
if err := f.ix.FillVersions(f.ctx, f.ask); err != nil {
f.logf("versions: the first fill waits: %v", err)
}
}()
go f.fillFloors()
}
// fillFloors fills the floor of each module the versions hold none of, each on its own so that one unanswered read holds no other
// module's (A-490d, A-490f, A-490i): at every start and every revision, not waiting for the builder's half. A read is a kept call
// asked again until it answers, and the indexer holds no timer of its own (ADR 0437 §8).
func (f *versionsFill) fillFloors() {
if f.floor.Tags == nil && f.floor.Holder == nil {
// heardImportsReported keeps a build's import set (design 47 H2 H-A-517, H-A-527): one that does not decode, or names no
// module or fingerprint, is said and acknowledged; one that cannot be kept is left, so the bus gives it again.
func heardImportsReported(ctx context.Context, ix *index.Indexer, m jetstream.Msg, logf func(string, ...any)) {
var e nodebuildgo.ImportsReported
if err := json.Unmarshal(m.Data(), &e); err != nil {
logf("%s holds what is no imports-reported, left: %v", m.Subject(), err)
_ = m.Ack()
return
}
modules, err := f.ix.FloorModules(f.ctx)
if err != nil {
f.logf("versions: the floor waits: %v", err)
err := ix.HearImportsReported(ctx, e)
switch {
case errors.Is(err, index.ErrImportsUnreadable):
logf("%s: %v, left", m.Subject(), err)
case err != nil:
logf("imports: the import set of %s at %s could not be kept, so the bus gives it again: %v", e.Module, e.Fingerprint, err)
leftForBus(m, fmt.Sprintf("the imports-reported of %s at %s", e.Module, e.Fingerprint), err, logf)
return
}
for _, m := range modules {
go func() {
if err := f.ix.FillFloor(f.ctx, m, f.floor); err != nil {
f.logf("versions: the floor of %s waits for the next start or revision: %v", m, err)
}
}()
}
}
// afterRevision runs the fill's kick after each catalog revision kept, once the fill is set.
func afterRevision(say func(context.Context, meshcatalog.CatalogRevisionEvent) error, fill *atomic.Pointer[versionsFill]) func(context.Context, meshcatalog.CatalogRevisionEvent) error {
return func(ctx context.Context, e meshcatalog.CatalogRevisionEvent) error {
err := say(ctx, e)
if f := fill.Load(); f != nil {
f.kick()
}
return err
}
}
// tagsVia reads every tag of a repository that starts with a prefix from the seat git's verb tags as a kept call, page by
// page until none is more (design 47 G §412, A-490c: protected or not).
func tagsVia(call toolCaller) index.TagsReader {
return func(_ context.Context, repository, prefix string) ([]string, error) {
var out []string
for page := int64(1); ; page++ {
var a git.TagsAnswer
in := git.TagsInput{Repository: trunk.RepositoryName(repository), Prefix: prefix, Page: page}
if !strings.Contains(in.Repository, "/") {
return nil, fmt.Errorf("%q is not <owner>/<name>", repository)
}
if err := askGit(call, git.VerbTags, in, &a); err != nil {
return nil, err
}
for _, t := range a.Tags {
out = append(out, t.Tag)
}
if !a.More {
return out, nil
}
}
}
}
// holderVia reads the versions a package holder answers for a package: the seat npm-package-registry's or go-package-registry's
// verb versions (A-490g), as a kept call.
func holderVia(call toolCaller) index.HolderReader {
return func(_ context.Context, ecosystem, name string) ([]string, error) {
seat := npmpackageregistry.Seat
if ecosystem == index.EcosystemGo {
seat = gopackageregistry.Seat
}
raw, err := call("seat:"+seat+"."+npmpackageregistry.VerbVersions, npmpackageregistry.VersionsInput{Name: name, Kind: npmpackageregistry.ArtifactKindPackage})
if err != nil {
return nil, err
}
var a npmpackageregistry.VersionsAnswer
if err := json.Unmarshal(raw, &a); err != nil {
return nil, fmt.Errorf("the answer of %s.versions is not a package's versions: %w", seat, err)
}
var out []string
for _, v := range a.Versions {
out = append(out, v.Version)
}
return out, nil
}
_ = m.Ack()
}
+1
View File
@@ -17,6 +17,7 @@ require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-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-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
github.com/nats-io/nats-server/v2 v2.11.17
@@ -381,6 +381,49 @@ func Packages(module string, files map[string]string) (requires string, packages
return requires, packages, nil
}
// NpmPackage is a mesh npm package's requirements' digest and its content digest, from files, every blob under the
// directory of its package.json (the path of the artifact that publishes it) by path relative to it with its git object id
// (design 47 H2 H-A-546 (1)). It refuses a listing with no package.json at that directory.
//
// Its one package is the npm name, its digest the hex sha256 of the sorted lines "<path relative to it> <object>" of every
// file under it but node_modules and the test files of `node --test`'s default patterns, which the Node build module's unit
// step runs (H-A-547): a file named `*.test.*`, `*-test.*`, `*_test.*` or `test.*`, and everything under a directory named
// test. The requirements' digest is the hex sha256 of the lines "package.json <object>" and "package-lock.json <object>"
// (the second absent with no lock file), as H-A-525 has it for go.mod and go.sum.
func NpmPackage(name string, files map[string]string) (requires string, packages []meshcatalog.PackagesByModuleValuePackagesItem, err error) {
pj, ok := files["package.json"]
if !ok {
return "", nil, fmt.Errorf("the npm package %s has no package.json at its directory", name)
}
req := "package.json " + pj
if lock, ok := files["package-lock.json"]; ok {
req += "\npackage-lock.json " + lock
}
sum := sha256.Sum256([]byte(req))
var lines []string
for p, object := range files {
if npmLeftOut(p) {
continue
}
lines = append(lines, p+" "+object)
}
sort.Strings(lines)
s := sha256.Sum256([]byte(strings.Join(lines, "\n")))
return hex.EncodeToString(sum[:]), []meshcatalog.PackagesByModuleValuePackagesItem{{Package: name, Digest: hex.EncodeToString(s[:])}}, nil
}
// npmLeftOut is whether a file of an npm package, by its path relative to the package, leaves its digest: under
// node_modules or a directory named test, or a test file by `node --test`'s default patterns (H-A-547).
func npmLeftOut(p string) bool {
dir, file := path.Split(p)
for _, e := range strings.Split(strings.TrimSuffix(dir, "/"), "/") {
if e == "node_modules" || e == "test" {
return true
}
}
return strings.HasPrefix(file, "test.") || strings.Contains(file, ".test.") || strings.Contains(file, "-test.") || strings.Contains(file, "_test.")
}
// ignoredDir is whether the go tool takes no package from dir: an element named testdata, or starting with _ or .
func ignoredDir(dir string) bool {
for _, e := range strings.Split(dir, "/") {
@@ -216,6 +216,35 @@ func packageDigestIsItsOwnFiles(t *testing.T) {
if _, _, err := Packages(sdk, map[string]string{"a.go": "x"}); err == nil {
t.Error("a listing with no go.mod was taken as a module")
}
// I11a/AC1 (design 47 H2 H-A-523, H-A-546 (1), H-A-547): an npm package's digest is its files under its package.json's
// directory, by its npm name, leaving out node_modules and node --test's test files; its requirements' digest is its
// package.json and its lock file.
npm := map[string]string{"package.json": "p1", "package-lock.json": "l1", "src/stdio.ts": "a", "dist/stdio.js": "b",
"src/stdio.test.ts": "t1", "src/a-test.ts": "t2", "src/a_test.mjs": "t3", "test.js": "t4", "test/x.ts": "t5",
"node_modules/x/index.js": "n"}
npmReq, npmPkgs, err := NpmPackage("@novox/mesh-sdk", npm)
if err != nil || len(npmPkgs) != 1 || npmPkgs[0].Package != "@novox/mesh-sdk" || npmPkgs[0].Digest == "" || npmReq == "" {
t.Fatalf("NpmPackage = %q, %+v, %v; want one package by its npm name", npmReq, npmPkgs, err)
}
for _, c := range []struct {
file string
moves bool
}{{"src/stdio.ts", true}, {"dist/stdio.js", true}, {"package.json", true}, {"src/stdio.test.ts", false}, {"src/a-test.ts", false},
{"src/a_test.mjs", false}, {"test.js", false}, {"test/x.ts", false}, {"node_modules/x/index.js", false}} {
r, ps, _ := NpmPackage("@novox/mesh-sdk", with(npm, c.file, "zz"))
if moved := ps[0].Digest != npmPkgs[0].Digest; moved != c.moves {
t.Errorf("changing %s of the npm package moved its digest %v, want %v", c.file, moved, c.moves)
}
if c.file == "package.json" && r == npmReq {
t.Error("a changed package.json left the npm package's requirements' digest")
}
}
if r2, _, _ := NpmPackage("@novox/mesh-sdk", with(npm, "package-lock.json", "l2")); r2 == npmReq {
t.Error("a changed lock file left the npm package's requirements' digest")
}
if _, _, err := NpmPackage("@novox/mesh-sdk", map[string]string{"index.js": "x"}); err == nil {
t.Error("a listing with no package.json was taken as an npm package")
}
}
func with(m map[string]string, k, v string) map[string]string {
@@ -1,242 +0,0 @@
package index
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// The builds of a watched branch other than the first release no version (design 47 G §371); the indexer keeps each one's
// edge entries in the state build-edges, under <module>.<branch>, and what the branch's newest build of the module
// published as heard, branch-build.<module>.<branch> in the state heard (§374, A-83).
const (
BuildEdgesState = "build-edges"
// BranchBuildPrefix opens branch-build.<module>.<branch>, each part escaped as a name (A-80).
BranchBuildPrefix = "branch-build."
)
// BranchBuild is what a branch-build key holds: the newest build of a module on a watched branch that was heard published,
// its source revision, the fingerprint of the branch's catalog entry at that revision and each artifact's digest.
type BranchBuild struct {
V int64 `json:"v"`
Version string `json:"version"`
Source int64 `json:"source"`
Fp string `json:"fp"`
Artifacts map[string]string `json:"artifacts"`
At time.Time `json:"at"`
}
// BranchBuildKey is the key of the state heard of a module's newest build on a branch.
func BranchBuildKey(module, branch string) string {
return BranchBuildPrefix + keys.EscapeName(module) + "." + keys.EscapeName(branch)
}
// BuildEdgesKey is the key of the state build-edges of a module's build on a branch, each part escaped as a name.
func BuildEdgesKey(module, branch string) string {
return meshcatalog.BuildEdgesByModuleBranchKey(keys.EscapeName(module), keys.EscapeName(branch))
}
// branchEntryAt is the module's entry in the newest revision of the branch taken in from that source revision (A-83: the
// revision whose source the build names, which the indexer holds itself).
func (ix *Indexer) branchEntryAt(ctx context.Context, module, branch string, source int64) (meshcatalog.CatalogEntry, error) {
if ix.Revisions == nil {
return meshcatalog.CatalogEntry{}, errors.New("the catalog graph is not kept here: no entry says the build's fingerprint")
}
names, err := ix.Revisions.Names(ctx)
if err != nil {
return meshcatalog.CatalogEntry{}, err
}
number := TrunkRevisionOf
if !isTrunkBranch(branch) {
number = func(n string) (int64, bool) { return BranchRevisionOf(branch, n) }
}
var numbers []int64
for _, n := range names {
if r, ok := number(n); ok {
numbers = append(numbers, r)
}
}
slices.SortFunc(numbers, func(a, b int64) int { return cmp.Compare(b, a) })
for _, n := range numbers {
name := RevisionObject(meshcatalog.CatalogRevision{Branch: branch, Revision: n})
rev, entries, err := ReadRevision(ctx, ix.Revisions, name)
if err != nil {
return meshcatalog.CatalogEntry{}, err
}
if rev.Source != source {
continue
}
for _, e := range entries {
if e.Module == module {
return e, nil
}
}
}
return meshcatalog.CatalogEntry{}, fmt.Errorf("the indexer keeps no revision of the branch %s at source revision %d with an entry of %s", branch, source, module)
}
// hearBranchBuild takes the package-published of a build of a watched branch other than the first (A-83): the build is kept as
// heard, and its edge entries are kept in build-edges, keyed by the fingerprint of the entry in the revision of that branch the
// build's source names. A build of an older source revision than the one kept leaves what is kept.
func (ix *Indexer) hearBranchBuild(ctx context.Context, p meshbuilds.PackagePublished) error {
if ix.BuildEdges == nil {
return errors.New("the state build-edges is not kept here")
}
entry, err := ix.branchEntryAt(ctx, p.Module, p.Branch, p.Source)
if err != nil {
return err
}
if entry.Fp == "" {
ix.logf("build-edges: the entry of %s on %s at source revision %d has no fingerprint, so its build keeps none", p.Module, p.Branch, p.Source)
return nil
}
at := ix.now().UTC()
err = write(ctx, ix.Heard, BranchBuildKey(p.Module, p.Branch), func(raw []byte, found bool) ([]byte, bool, error) {
var b BranchBuild
if found && json.Unmarshal(raw, &b) == nil && b.Source > p.Source {
return nil, false, nil
}
if !found || b.Source != p.Source || b.Fp != entry.Fp {
b = BranchBuild{Artifacts: map[string]string{}}
}
b.V, b.Version, b.Source, b.Fp, b.At = 1, p.Version, p.Source, entry.Fp, at
b.Artifacts[p.Artifact] = p.Digest
data, err := json.Marshal(b)
return data, false, err
})
if err != nil {
return err
}
edges := releaseEdges(entry, p.Dependencies)
return write(ctx, ix.BuildEdges, BuildEdgesKey(p.Module, p.Branch), func(raw []byte, found bool) ([]byte, bool, error) {
be := meshcatalog.BuildEdges{V: 1, Fp: entry.Fp, Source: p.Source}
if found {
kept, _, err := meshcatalog.DecodeBuildEdgesByModuleBranchValue(raw)
if err != nil {
return nil, false, err
}
if kept.Source > p.Source {
return nil, false, nil
}
if kept.Source == p.Source && kept.Fp == entry.Fp {
be.Edges = kept.Edges
}
}
for _, e := range edges {
if !slices.ContainsFunc(be.Edges, func(x meshcatalog.VersionEdge) bool { return x.Kind == e.Kind && x.Part == e.Part && x.Word == e.Word }) {
be.Edges = append(be.Edges, e)
}
}
data, err := json.Marshal(be)
return data, false, err
})
}
// PruneBranchBuilds forgets a module's builds of the branches its registration no longer watches beside its first
// (registration-changed, §374): its build-edges keys and its branch-build keys of every other branch.
func (ix *Indexer) PruneBranchBuilds(ctx context.Context, module string, watched []string) error {
keep := map[string]bool{}
if len(watched) > 1 {
for _, b := range watched[1:] {
keep[keys.EscapeName(b)] = true
}
}
var errs []error
forget := func(st Store, key string) {
if _, rev, found, err := st.Get(ctx, key); err != nil {
errs = append(errs, err)
} else if found {
if err := st.Delete(ctx, key, rev); err != nil && !errors.Is(err, ErrConflict) {
errs = append(errs, err)
}
}
}
if ix.BuildEdges != nil {
all, err := ix.BuildEdges.Keys(ctx)
if err != nil {
return err
}
for _, k := range all {
if m, b, ok := meshcatalog.ParseBuildEdgesByModuleBranchKey(k); ok && m == keys.EscapeName(module) && !keep[b] {
forget(ix.BuildEdges, k)
}
}
}
if ix.Heard != nil {
all, err := ix.Heard.Keys(ctx)
if err != nil {
return err
}
prefix := BranchBuildPrefix + keys.EscapeName(module) + "."
for _, k := range all {
if b, ok := strings.CutPrefix(k, prefix); ok && !keep[b] {
forget(ix.Heard, k)
}
}
}
return errors.Join(errs...)
}
// outdatedBranchBuilds are the behind entries of kind 1 of the builds of other watched branches (A-83): the digest a build
// recorded for a package against the digest in the newest build of that package's module on the same branch, as heard, never a
// released digest.
func (ix *Indexer) outdatedBranchBuilds(ctx context.Context, in meshcatalog.OutdatedInput) ([]meshcatalog.Outdated, error) {
if ix.BuildEdges == nil || ix.Heard == nil {
return nil, nil
}
all, err := ix.BuildEdges.Keys(ctx)
if err != nil {
return nil, err
}
slices.Sort(all)
var out []meshcatalog.Outdated
for _, k := range all {
em, eb, ok := meshcatalog.ParseBuildEdgesByModuleBranchKey(k)
if !ok {
continue
}
module, err1 := keys.UnescapeName(em)
branch, err2 := keys.UnescapeName(eb)
if err1 != nil || err2 != nil || (in.Branch != "" && in.Branch != eb) {
continue
}
raw, _, found, err := ix.BuildEdges.Get(ctx, k)
if err != nil || !found {
continue
}
be, _, err := meshcatalog.DecodeBuildEdgesByModuleBranchValue(raw)
if err != nil {
return nil, fmt.Errorf("the key %s of the state %s: %w", k, BuildEdgesState, err)
}
for _, e := range be.Edges {
if e.Kind != 1 || (in.Dependency != "" && in.Dependency != e.Part) {
continue
}
var dep BranchBuild
raw, _, found, err := ix.Heard.Get(ctx, BranchBuildKey(strings.SplitN(e.Part, ":", 2)[0], branch))
if err != nil || !found || json.Unmarshal(raw, &dep) != nil {
continue
}
digest := dep.Artifacts[e.Part]
if digest == "" || digest == e.Digest {
continue
}
o := meshcatalog.Outdated{Module: module, Build: be.Fp, Kind: 1, Recorded: e.Version + " " + e.Digest, Newest: dep.Version + " " + digest,
Dependency: meshcatalog.OutdatedDependency{Artifact: e.Part, Branch: branch}}
if e.Stale {
o.Act = "rebuild"
}
out = append(out, o)
}
}
return out, nil
}
@@ -1,90 +0,0 @@
package index
import (
"context"
"encoding/json"
"strings"
"testing"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
)
// Design 47 G §374, A-83, A-85: a build of a watched branch other than the first releases no version; its edge entries are kept
// in build-edges under <module>.<branch>, the fingerprint being the entry's in the branch's revision whose source the build
// names; outdated compares kind 1 with the same branch's newest build, as heard; registration-changed prunes the branch's
// keys when it is no longer watched.
func TestABuildOfAnotherWatchedBranchKeepsItsEdgesAndIsOutdatedAgainstThatBranch(t *testing.T) {
ctx := context.Background()
ix := &Indexer{Module: testSelf, Versions: newMem(), Heard: newMem(), BuildEdges: newMem(), Revisions: newMemObjects(1 << 20), Registry: &Registry{Registrations: MemoryStore()}}
for _, m := range []string{"lib", "app"} {
raw, _ := json.Marshal(meshcatalog.Registration{Module: m, Branches: []string{"main", "beta"}})
if err := ix.Registry.Registrations.Create(ctx, RegistrationKey(m), raw); err != nil {
t.Fatal(err)
}
}
fp := func(c string) string { return "src2:" + strings.Repeat(c, 64) }
keep := func(source int64, libFp, appFp string) {
t.Helper()
err := ix.KeepBranchEntries(ctx, "beta", source, map[string]meshcatalog.CatalogEntry{
"lib": {Module: "lib", Fp: libFp, Manifest: map[string]any{}, Artifacts: []meshcatalog.Artifact{{Ref: "lib:pkg"}}},
"app": {Module: "app", Fp: appFp, Manifest: map[string]any{}, Artifacts: []meshcatalog.Artifact{{Ref: "app:program"}},
Edges: []meshcatalog.Edge{{Kind: 1, From: "lib:pkg", To: "app:program", Part: "lib:pkg", Stale: true, Word: "imports"}}}}, nil)
if err != nil {
t.Fatal(err)
}
}
keep(7, fp("a"), fp("b"))
keep(8, fp("c"), fp("b"))
pub := func(module, artifact, digest string, source int64, deps ...meshbuilds.Dependency) {
t.Helper()
if err := ix.HearPackagePublished(ctx, meshbuilds.PackagePublished{Module: module, Artifact: artifact, Digest: digest, Version: "0.1.1", Source: source, Branch: "beta", Dependencies: deps}); err != nil {
t.Fatal(err)
}
}
pub("lib", "lib:pkg", "d1", 7)
pub("app", "app:program", "a1", 7, meshbuilds.Dependency{Kind: 1, Part: "lib:pkg", Version: "0.1.1", Digest: "d1"})
if v, _ := ModuleVersions(ctx, ix.Versions, "app"); len(v) != 0 {
t.Errorf("a build of beta released %v", v)
}
raw, _, found, _ := ix.BuildEdges.Get(ctx, BuildEdgesKey("app", "beta"))
be, _, err := meshcatalog.DecodeBuildEdgesByModuleBranchValue(raw)
if !found || err != nil || be.Fp != fp("b") || be.Source != 7 || len(be.Edges) != 1 || be.Edges[0].Digest != "d1" {
t.Fatalf("build-edges of app on beta: %+v (found %v, %v), want the fingerprint of the entry at source 7 and its kind 1 edge", be, found, err)
}
behind := func() []meshcatalog.Outdated {
t.Helper()
a, err := ix.Outdated(ctx, meshcatalog.OutdatedInput{})
if err != nil {
t.Fatal(err)
}
return a.Behind
}
if b := behind(); len(b) != 0 {
t.Fatalf("behind before lib's next build: %+v", b)
}
pub("lib", "lib:pkg", "d2", 8)
b := behind()
if len(b) != 1 || b[0].Module != "app" || b[0].Kind != 1 || b[0].Build != fp("b") || b[0].Version != "" || b[0].Dependency.Branch != "beta" ||
!strings.Contains(b[0].Recorded, "d1") || !strings.Contains(b[0].Newest, "d2") || b[0].Act != "rebuild" {
t.Fatalf("behind after lib's newer build on beta: %+v", b)
}
if err := ix.PruneBranchBuilds(ctx, "app", []string{"main", "beta"}); err != nil {
t.Fatal(err)
}
if _, _, found, _ := ix.BuildEdges.Get(ctx, BuildEdgesKey("app", "beta")); !found {
t.Errorf("a branch still watched lost its build-edges")
}
if err := ix.PruneBranchBuilds(ctx, "app", []string{"main"}); err != nil {
t.Fatal(err)
}
if _, _, found, _ := ix.BuildEdges.Get(ctx, BuildEdgesKey("app", "beta")); found {
t.Errorf("build-edges of app on beta stayed after beta was unwatched")
}
if _, _, found, _ := ix.Heard.Get(ctx, BranchBuildKey("app", "beta")); found {
t.Errorf("branch-build of app on beta stayed after beta was unwatched")
}
if _, _, found, _ := ix.Heard.Get(ctx, BranchBuildKey("lib", "beta")); !found {
t.Errorf("lib's branch-build went with app's")
}
}
@@ -61,11 +61,6 @@ type Indexer struct {
// OldSections is the state of how many accepted modules use each old section (oldsections.go, issue 1966 D4); nil keeps no
// count and the judge refuses no use of an old section.
OldSections Store
// Requirements is the requirements state (requirements.go, DLV-I7): what each consumer's go.sum requires of each mesh
// Go module, kept at each merge; nil keeps none.
Requirements Store
reqMu sync.Mutex
reqKept map[string]bool // consumers whose go.sum this process kept (requirementsKept)
// JudgeID names the judge a verdict says made it; empty is judge.Identity, the running program's.
JudgeID string
// Findings is the indexer's finding writer (design 47 G A-29), where a manifest-accepted whose publish failed twice is kept
@@ -96,13 +91,8 @@ type Indexer struct {
SayFill func(ctx context.Context, event, id string, f meshcatalog.Fill) error
// Versions is the state versions (versions.go, design 47 G §349): each module's released versions; nil keeps none.
Versions Store
// BuildEdges is the state build-edges (branch_builds.go, design 47 G §374): the edge entries of the newest build of a module on a
// watched branch other than the first; nil keeps none.
BuildEdges Store
// SayVersionReleased says the seat mesh-catalog's event version-released under the duplicate id given (§349); nil says nothing.
SayVersionReleased func(ctx context.Context, e meshcatalog.VersionReleasedEvent, id string) error
// SayVersionsFilled says the seat mesh-catalog's event versions-filled, once, under the duplicate id given (§372); nil says nothing.
SayVersionsFilled func(ctx context.Context, e meshcatalog.VersionsFilledEvent, id string) error
// Inputs is the state inputs (run_inputs.go, design 47 G §354): the inputs of the indexer's run asks; nil keeps none.
Inputs Store
// InputObjects is the object store beside the state inputs (`inputs-objects`): an input too large for a key is kept there
@@ -118,9 +108,6 @@ type Indexer struct {
// with its git object id (the seat git's trees with files): the listing a package's digest is computed from.
// Nil publishes no package.
Files func(ctx context.Context, repository, sha string, dirs []string) (map[string]map[string]string, error)
// GoSum reads a module directory's go.sum at a commit (the seat git's file): the mesh Go modules a module with no
// reported import set takes the version line of. Nil reads none: such a module keeps what it held.
GoSum func(ctx context.Context, repository, sha, dir string) ([]byte, error)
// GoMod reads a module directory's go.mod at a commit (the seat git's file): the mesh Go modules of its own
// repository it replaces by a directory (fingerprint.ReplacedSiblings), which the version line takes by their
// content; nil reads none.
@@ -149,24 +136,25 @@ type Indexer struct {
Contains func(ctx context.Context, repository, commit, in string) (bool, error)
Logf func(format string, args ...any)
mu sync.Mutex // guards source, toolchains and previews, which the watches and the forge messages all reach
source sourceNow
toolchains map[string]map[string]nodebuildgo.Toolchain // language, then node (toolchains.go)
buildModules map[string]BuildModule // by language: the build modules whose toolchains are taken in (buildmodules.go)
floors sync.Map // the modules whose floor FillFloor reads now (tag_floor.go), one fill each
versionsFilling atomic.Bool // a FillVersions runs (versions_fill.go)
stepsSince map[string]time.Time // by build seat: since when its steps is unanswered (seed_steps.go)
moving map[string]whole // by modules key: a merge naming a module another repository holds, waiting for that trunk to drop it (moves.go)
fresh map[string]bool // modules whose import form is computed again by hand (FingerprintsAgain), "*" for every one; under freshMu
freshMu sync.Mutex
recompute sync.Mutex // one Recompute at a time
untaken map[string]string // repository to the latest merge applied while the taken state was missing (taken.go)
filling atomic.Bool // a FillTaken runs in the background (KickFill)
fillAgain atomic.Bool // a kick arrived while it ran
underSeats bool // a dry run inside judge.WithSeats: its judge passes do not hold the seat list (verdicts.go)
isDry bool // a dry run (dryrun.go): its packages are a working copy over the live state, and it drops no kept package key (packages.go)
judgeMu sync.Mutex // one judge pass at a time (verdicts.go)
keepMu sync.Mutex // one catalog graph revision kept at a time (keepEntries)
mu sync.Mutex // guards source, toolchains and previews, which the watches and the forge messages all reach
source sourceNow
toolchains map[string]map[string]nodebuildgo.Toolchain // language, then node (toolchains.go)
buildModules map[string]BuildModule // by language: the build modules whose toolchains are taken in (buildmodules.go)
stepsSince map[string]time.Time // by build seat: since when its steps is unanswered (seed_steps.go)
moving map[string]whole // by modules key: a merge naming a module another repository holds, waiting for that trunk to drop it (moves.go)
fresh map[string]bool // modules whose import form is computed again by hand (FingerprintsAgain), "*" for every one; under freshMu
freshMu sync.Mutex
recompute sync.Mutex // one Recompute at a time
untaken map[string]string // repository to the latest merge applied while the taken state was missing (taken.go)
filling atomic.Bool // a FillTaken runs in the background (KickFill)
fillAgain atomic.Bool // a kick arrived while it ran
underSeats bool // a dry run inside judge.WithSeats: its judge passes do not hold the seat list (verdicts.go)
isDry bool // a dry run (dryrun.go): its packages are a working copy over the live state, and it drops no kept package key (packages.go)
// trunkModules is, in a dry run, the live modules state under its view: main's values, whose import form a branch takes
// with main's import set (importset.go, H-A-532 DMC-6); nil reads Modules.
trunkModules Store
judgeMu sync.Mutex // one judge pass at a time (verdicts.go)
keepMu sync.Mutex // one catalog graph revision kept at a time (keepEntries)
// Pins is the state pins (pins.go); nil keeps none. PinsPending says how many messages the indexer's durable consumer of the
// events stream has not been given: a revision is removed only while none is pending (§579).
Pins Store
@@ -179,7 +167,7 @@ type Indexer struct {
catchUpWG sync.WaitGroup // the first start's catch-up in the background (kickCatchUp), for tests to wait on
// Heard keeps what the indexer heard and compares later (A-80): the time a call is unanswered since (steps-since, call-since),
// toolchain.<language>, pending.<module>.<version>, acted.<acting part>.<dependent>, each key part escaped as a name
// (§73), and the mark versions-filled; nil keeps none. It is the state heard, whose key forge keeps the forge messages handled.
// (§73); nil keeps none. It is the state heard, whose key forge keeps the forge messages handled.
Heard Store
judgePending atomic.Bool // the start's judge pass failed: judged again at the next message (verdicts.go)
// SayTakeIn publishes a take-in event (take-in.taken, take-in.pending; design 47 H §743, §744) with its body, under the
@@ -187,6 +175,8 @@ type Indexer struct {
SayTakeIn func(ctx context.Context, event, id string, body any) error
// Held is the state held: each watched branch's source-moved held unacknowledged (held.go, design 47 H §744); nil keeps none.
Held Store
// Imports is the state imports: each module's reported import set (importset.go, design 47 H2 H-A-527); nil keeps none.
Imports Store
// Runs is the state runs: the runs on request the indexer holds a candidate for (runcandidates.go, A-174); nil keeps none.
Runs Store
runMu sync.Mutex // one run event at a time (runcandidates.go)
@@ -245,22 +245,32 @@ func edgesOf(a meshcatalog.CatalogEntry, all map[string]meshcatalog.CatalogEntry
}
modules := slices.Sorted(maps.Keys(all))
delivers := primaryOf(a)
// Kind 1: a package its build imports, from the artifact that publishes it, to each artifact built from that ecosystem (§47).
for _, name := range slices.Sorted(maps.Keys(a.Packages)) {
for _, m := range modules {
b := all[m]
if m == a.Module {
continue
}
for _, art := range b.Artifacts {
if art.Package == nil || art.Package.Name != name {
// Kind 1: a package its build imports, from the artifact that publishes it, to each artifact built from that ecosystem (§47):
// from its reported import set, each import from the package artifact of the longest name holding it (design 47 H2
// H-A-522, H-A-532 DQ-14); from its manifest's packages only until a set is reported.
if imports, reported := importSetOf(a); reported {
for _, imp := range imports {
var holder *meshcatalog.Artifact
for _, m := range modules {
if m == a.Module {
continue
}
for _, to := range importersOf(a, art.Package.Ecosystem) {
add(meshcatalog.Edge{Kind: 1, From: art.Ref, To: to, Stale: true, Word: "packages", Why: name})
for i, art := range all[m].Artifacts {
if p := art.Package; p != nil && (imp == p.Name || strings.HasPrefix(imp, p.Name+"/")) &&
(holder == nil || len(p.Name) > len(holder.Package.Name)) {
holder = &all[m].Artifacts[i]
}
}
}
if holder == nil {
continue
}
for _, to := range importersOf(a, holder.Package.Ecosystem) {
add(meshcatalog.Edge{Kind: 1, From: holder.Ref, To: to, Stale: true, Word: "imports", Why: imp})
}
}
} else {
edgesOfPackages(a, all, modules, add)
}
// Kind 2: an artifact its manifest's `needs` references in another module, published before the artifact that names it
// delivers (A-212, §432).
@@ -453,3 +463,34 @@ func (ix *Indexer) withActs(ctx context.Context, entries map[string]meshcatalog.
}
return WithActs(entries, defs)
}
// importSetOf is the import set the entry's fingerprint was computed with (its inputs' imports) and whether it is reported:
// the entry's import form is set (design 47 H2 H-A-538), and an absent imports is then the empty set (H-A-536); an entry
// on the version line has none.
func importSetOf(a meshcatalog.CatalogEntry) ([]string, bool) {
if a.Inputs == nil || a.Inputs.From == nil || a.Inputs.From.ImportForm == "" {
return nil, false
}
return a.Inputs.From.Imports, true
}
// edgesOfPackages are kind 1 from the entry's packages, its go.mod's requirements, for an entry with no reported import set
// (H-A-522).
func edgesOfPackages(a meshcatalog.CatalogEntry, all map[string]meshcatalog.CatalogEntry, modules []string, add func(meshcatalog.Edge)) {
for _, name := range slices.Sorted(maps.Keys(a.Packages)) {
for _, m := range modules {
b := all[m]
if m == a.Module {
continue
}
for _, art := range b.Artifacts {
if art.Package == nil || art.Package.Name != name {
continue
}
for _, to := range importersOf(a, art.Package.Ecosystem) {
add(meshcatalog.Edge{Kind: 1, From: art.Ref, To: to, Stale: true, Word: "packages", Why: name})
}
}
}
}
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"os"
"slices"
"strings"
"testing"
"time"
@@ -49,6 +50,26 @@ func TestAnEntryCarriesItsEdgesOfKindsOneToFourAndSix(t *testing.T) {
if len(before.Edges) != 0 || len(entries["app"].Edges) != 0 {
t.Errorf("the entries given were changed")
}
// Design 47 H2 H-A-522, H-A-532 DQ-14: with a reported import set, kind 1 comes from it, each import from the package of
// the longest Go module path holding it (lib/go/sub, nested in lib/go), and none from a requirement no import names.
entries["sub"] = meshcatalog.CatalogEntry{Module: "sub", Artifacts: []meshcatalog.Artifact{{Ref: "sub:go", Language: "go", Kind: "package",
Package: &meshcatalog.ArtifactPackage{Ecosystem: EcosystemGo, Name: "git.example/lib/go/sub"}}}}
entries["other"] = meshcatalog.CatalogEntry{Module: "other", Artifacts: []meshcatalog.Artifact{{Ref: "other:go", Language: "go", Kind: "package",
Package: &meshcatalog.ArtifactPackage{Ecosystem: EcosystemGo, Name: "git.example/other/go"}}}}
imp := entries["app"]
imp.Packages = map[string]string{"git.example/lib/go": "1.2.3", "git.example/other/go": "0.1.0"}
imp.Inputs = &meshcatalog.EntryInputs{From: &meshcatalog.FingerprintInputs{Imports: []string{"git.example/lib/go/sub/x"}, ImportForm: "src2:" + strings.Repeat("a", 64)}}
entries["app"] = imp
if got := WithEdges(entries)["app"].Edges; got[0] != (meshcatalog.Edge{Kind: 1, From: "sub:go", To: "app:program", Stale: true, Word: "imports", Why: "git.example/lib/go/sub/x"}) ||
slices.ContainsFunc(got[1:], func(e meshcatalog.Edge) bool { return e.Kind == 1 }) {
t.Errorf("edges with an import set: %+v, want one kind 1 from sub:go and none from the requirements", got)
}
// H-A-536, H-A-538: the entry's import form says its set is reported, an absent imports the empty set: no kind 1 at all.
imp.Inputs.From.Imports = nil
entries["app"] = imp
if got := WithEdges(entries)["app"].Edges; slices.ContainsFunc(got, func(e meshcatalog.Edge) bool { return e.Kind == 1 }) {
t.Errorf("edges with a reported empty import set: %+v, want no kind 1", got)
}
}
// Design 47 G A-208: a revision kept holds each entry with its edges, so the builder and the assigner read them from the entry.
@@ -74,33 +74,6 @@ func TestTheControlRecords(t *testing.T) {
t.Errorf("indexer_bus_state = %+v (%v); want bad and cache, at the modules mark", got, err)
}
})
// DLV-I7 (REG S15, the lead's ruling): the requirements state keeps, per mesh Go module, the highest version each
// consumer's go.sum names; a consumer no longer naming it leaves; indexer_requirements answers the distinct versions,
// highest last, a pseudo-version below the release it precedes.
t.Run("indexer_requirements", func(t *testing.T) {
ctx := context.Background()
ix := &Indexer{Module: testSelf, Requirements: newMem()}
sdk := "git.novox.be/novox/mesh-sdk/go"
sum := func(lines ...string) []byte { return []byte(strings.Join(lines, "\n")) }
ix.keepRequirements(ctx, "novox/a", "modules/x", sum(
sdk+" v0.1.14-0.20261103221822-85ba0a9a70d8 h1:x=", sdk+" v0.1.13/go.mod h1:y=", "github.com/other v1.0.0 h1:z="))
ix.keepRequirements(ctx, "novox/b", ".", sum(sdk+" v0.1.14 h1:x="))
ix.keepRequirements(ctx, "novox/c", ".", sum(sdk+" v0.1.14 h1:x="))
value, _, found, _ := ix.Requirements.Get(ctx, sdk)
got, err := RequirementsOf(value, found)
if err != nil || !reflect.DeepEqual(got, []string{"v0.1.14-0.20261103221822-85ba0a9a70d8", "v0.1.14"}) {
t.Errorf("requirements = %v (%v)", got, err)
}
ix.keepRequirements(ctx, "novox/a", "modules/x", sum("github.com/other v1.0.0 h1:z="))
ix.keepRequirements(ctx, "novox/b", ".", nil)
ix.keepRequirements(ctx, "novox/c", ".", nil)
if _, _, found, _ := ix.Requirements.Get(ctx, sdk); found {
t.Error("a package no consumer requires is still kept")
}
if got, _ := RequirementsOf(nil, false); got == nil || len(got) != 0 {
t.Errorf("none = %#v, want an empty list", got)
}
})
// DLV-I5 (milestone § 2 item 1, design 51 *The versions*): a package's series key keeps the newest trunk version the
// builder numbered and the newest a seat published; an older one, a tagged one and one of another series move neither;
// the per-module digests never read a series key.

Some files were not shown because too many files have changed in this diff Show More