diff --git a/modules/mesh-delivery-builder/builds/builds.go b/modules/mesh-delivery-builder/builds/builds.go index d94e0ac0c..5a0305648 100644 --- a/modules/mesh-delivery-builder/builds/builds.go +++ b/modules/mesh-delivery-builder/builds/builds.go @@ -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: diff --git a/modules/mesh-delivery-builder/builds/log.go b/modules/mesh-delivery-builder/builds/log.go index 3fd4aa855..ba703fa22 100644 --- a/modules/mesh-delivery-builder/builds/log.go +++ b/modules/mesh-delivery-builder/builds/log.go @@ -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) } diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go index 9e164d827..a75bbcf42 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/main.go @@ -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, /"}, - "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})...) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reservedname_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reservedname_test.go index a91daa9e8..ad941811f 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reservedname_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder-tools/reservedname_test.go @@ -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"}) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/buckets.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/buckets.go index 083d6993b..30973694c 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/buckets.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/buckets.go @@ -9,12 +9,12 @@ import ( // ownBuckets are the buckets of the builder's own states, each `_` 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), diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/catalog.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/catalog.go index 5ff5f0bd4..ff2b00580 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/catalog.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/catalog.go @@ -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) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread.go deleted file mode 100644 index 1b6934a21..000000000 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread.go +++ /dev/null @@ -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 -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread_test.go deleted file mode 100644 index fef97a57f..000000000 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/filledread_test.go +++ /dev/null @@ -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) - } - }) - } -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go index b50b6af37..8e0db2c85 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/findings.go @@ -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."}) - } -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/gone_integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/gone_integration_test.go index f2f59963c..5982081a5 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/gone_integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/gone_integration_test.go @@ -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) - } -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go index ca19716f6..eb446854f 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/integration_test.go @@ -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: @ + 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() diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go index 8ec595725..d4f7a7e95 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/main.go @@ -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) }) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names.go index e54fac5e0..79a4253af 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names.go @@ -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 }() diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names_test.go index c22673e35..b04f6539b 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/names_test.go @@ -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 { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishbounds.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishbounds.go index cb9628e1d..a04aa0ffa 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishbounds.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishbounds.go @@ -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)) { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go index fe51c912e..3ab7f6cdc 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishes_integration_test.go @@ -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 diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go index 9eb75367d..c516dff68 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/publishitem_test.go @@ -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) { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go index d57314066..e3951c9a6 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reasks.go @@ -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 diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go index 87f09a7a1..1098c5150 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/refused_test.go @@ -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) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go index d7b42077d..f386d5672 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve.go @@ -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 == "" { diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go index 6a20ddd58..adde32fc0 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/reserve_test.go @@ -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) diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/seats.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/seats.go index d45ffe18d..953443671 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/seats.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/seats.go @@ -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 -} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/testdata/catalogue-8b8b0f66-disk-load.module.json b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/testdata/catalogue-8b8b0f66-disk-load.module.json new file mode 100644 index 000000000..f19a46849 --- /dev/null +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/testdata/catalogue-8b8b0f66-disk-load.module.json @@ -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" + ] +} diff --git a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go index 6fc60acf6..0ac59ccad 100644 --- a/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go +++ b/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/versions.go @@ -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..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 (`/`, `.`): 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 == ':' }) -} diff --git a/modules/mesh-delivery-builder/internal/build/entry_test.go b/modules/mesh-delivery-builder/internal/build/entry_test.go index f2e4f2f12..5511dbeb4 100644 --- a/modules/mesh-delivery-builder/internal/build/entry_test.go +++ b/modules/mesh-delivery-builder/internal/build/entry_test.go @@ -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) } diff --git a/modules/mesh-delivery-builder/internal/build/imports_test.go b/modules/mesh-delivery-builder/internal/build/imports_test.go index 1d8fe7b3e..0552da6ad 100644 --- a/modules/mesh-delivery-builder/internal/build/imports_test.go +++ b/modules/mesh-delivery-builder/internal/build/imports_test.go @@ -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) + } } } diff --git a/modules/mesh-delivery-builder/internal/build/numbers.go b/modules/mesh-delivery-builder/internal/build/numbers.go index 8e0cd70e6..f19915d91 100644 --- a/modules/mesh-delivery-builder/internal/build/numbers.go +++ b/modules/mesh-delivery-builder/internal/build/numbers.go @@ -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, :). 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) diff --git a/modules/mesh-delivery-builder/internal/build/reserve_test.go b/modules/mesh-delivery-builder/internal/build/reserve_test.go index bb63848d4..87eaccaef 100644 --- a/modules/mesh-delivery-builder/internal/build/reserve_test.go +++ b/modules/mesh-delivery-builder/internal/build/reserve_test.go @@ -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 ":@.", 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 { diff --git a/modules/mesh-delivery-builder/internal/build/reservedone_test.go b/modules/mesh-delivery-builder/internal/build/reservedone_test.go index 693b48cb8..96e611e8a 100644 --- a/modules/mesh-delivery-builder/internal/build/reservedone_test.go +++ b/modules/mesh-delivery-builder/internal/build/reservedone_test.go @@ -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") diff --git a/modules/mesh-delivery-builder/internal/build/revisionwait.go b/modules/mesh-delivery-builder/internal/build/revisionwait.go index 676d30c56..417f92c43 100644 --- a/modules/mesh-delivery-builder/internal/build/revisionwait.go +++ b/modules/mesh-delivery-builder/internal/build/revisionwait.go @@ -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 -} diff --git a/modules/mesh-delivery-builder/internal/build/run.go b/modules/mesh-delivery-builder/internal/build/run.go index 71569ba45..cb4cd5f2b 100644 --- a/modules/mesh-delivery-builder/internal/build/run.go +++ b/modules/mesh-delivery-builder/internal/build/run.go @@ -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 { diff --git a/modules/mesh-delivery-builder/internal/build/run_test.go b/modules/mesh-delivery-builder/internal/build/run_test.go index 383bca35b..632defe31 100644 --- a/modules/mesh-delivery-builder/internal/build/run_test.go +++ b/modules/mesh-delivery-builder/internal/build/run_test.go @@ -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 diff --git a/modules/mesh-delivery-builder/internal/build/step.go b/modules/mesh-delivery-builder/internal/build/step.go index ad2bf357b..6b2031979 100644 --- a/modules/mesh-delivery-builder/internal/build/step.go +++ b/modules/mesh-delivery-builder/internal/build/step.go @@ -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 } diff --git a/modules/mesh-delivery-builder/internal/build/step_test.go b/modules/mesh-delivery-builder/internal/build/step_test.go index 9a62217c5..c0ab5bc6e 100644 --- a/modules/mesh-delivery-builder/internal/build/step_test.go +++ b/modules/mesh-delivery-builder/internal/build/step_test.go @@ -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)}} diff --git a/modules/mesh-delivery-builder/internal/build/stuck.go b/modules/mesh-delivery-builder/internal/build/stuck.go index 84f08cc4c..a2c8173db 100644 --- a/modules/mesh-delivery-builder/internal/build/stuck.go +++ b/modules/mesh-delivery-builder/internal/build/stuck.go @@ -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 (`/`) 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, ` `. 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.` // (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.`, 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, /, 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" diff --git a/modules/mesh-delivery-builder/internal/versions/again.go b/modules/mesh-delivery-builder/internal/versions/again.go index 3c3798756..3010c1bbe 100644 --- a/modules/mesh-delivery-builder/internal/versions/again.go +++ b/modules/mesh-delivery-builder/internal/versions/again.go @@ -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) -} diff --git a/modules/mesh-delivery-builder/internal/versions/claim.go b/modules/mesh-delivery-builder/internal/versions/claim.go index b54113236..7a8c860f3 100644 --- a/modules/mesh-delivery-builder/internal/versions/claim.go +++ b/modules/mesh-delivery-builder/internal/versions/claim.go @@ -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 -} diff --git a/modules/mesh-delivery-builder/internal/versions/entrynames.go b/modules/mesh-delivery-builder/internal/versions/entrynames.go index e317b4a52..4d5ab9f08 100644 --- a/modules/mesh-delivery-builder/internal/versions/entrynames.go +++ b/modules/mesh-delivery-builder/internal/versions/entrynames.go @@ -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 - } -} diff --git a/modules/mesh-delivery-builder/internal/versions/entrynames_test.go b/modules/mesh-delivery-builder/internal/versions/entrynames_test.go index 7cb1276b3..4d94d3ce6 100644 --- a/modules/mesh-delivery-builder/internal/versions/entrynames_test.go +++ b/modules/mesh-delivery-builder/internal/versions/entrynames_test.go @@ -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) - } -} diff --git a/modules/mesh-delivery-builder/internal/versions/floor.go b/modules/mesh-delivery-builder/internal/versions/floor.go deleted file mode 100644 index a186bcb3f..000000000 --- a/modules/mesh-delivery-builder/internal/versions/floor.go +++ /dev/null @@ -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:.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 `.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 -} diff --git a/modules/mesh-delivery-builder/internal/versions/heard.go b/modules/mesh-delivery-builder/internal/versions/heard.go index 12dc34c6b..e29038afe 100644 --- a/modules/mesh-delivery-builder/internal/versions/heard.go +++ b/modules/mesh-delivery-builder/internal/versions/heard.go @@ -1,10 +1,5 @@ package versions -import ( - "context" - "fmt" -) - // The registry seats' events the builder hears on its durable consumer of each `.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 -} diff --git a/modules/mesh-delivery-builder/internal/versions/names.go b/modules/mesh-delivery-builder/internal/versions/names.go index 46a9b9607..678ac807a 100644 --- a/modules/mesh-delivery-builder/internal/versions/names.go +++ b/modules/mesh-delivery-builder/internal/versions/names.go @@ -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 `.`; 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 / 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 (`.`), 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) diff --git a/modules/mesh-delivery-builder/internal/versions/oldform.go b/modules/mesh-delivery-builder/internal/versions/oldform.go index f7730ac48..c51f62c8f 100644 --- a/modules/mesh-delivery-builder/internal/versions/oldform.go +++ b/modules/mesh-delivery-builder/internal/versions/oldform.go @@ -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 diff --git a/modules/mesh-delivery-builder/internal/versions/publish.go b/modules/mesh-delivery-builder/internal/versions/publish.go index 8751ed50b..d4c146e36 100644 --- a/modules/mesh-delivery-builder/internal/versions/publish.go +++ b/modules/mesh-delivery-builder/internal/versions/publish.go @@ -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.`. -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.`. 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." diff --git a/modules/mesh-delivery-builder/internal/versions/reserve.go b/modules/mesh-delivery-builder/internal/versions/reserve.go index dd7a6f645..c62df7d04 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve.go @@ -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) } } diff --git a/modules/mesh-delivery-builder/internal/versions/reserve_test.go b/modules/mesh-delivery-builder/internal/versions/reserve_test.go index 51a093ee0..d04dd022d 100644 --- a/modules/mesh-delivery-builder/internal/versions/reserve_test.go +++ b/modules/mesh-delivery-builder/internal/versions/reserve_test.go @@ -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 { diff --git a/modules/mesh-delivery-builder/internal/versions/reservedname_test.go b/modules/mesh-delivery-builder/internal/versions/reservedname_test.go index c947d8eb8..9d7d71870 100644 --- a/modules/mesh-delivery-builder/internal/versions/reservedname_test.go +++ b/modules/mesh-delivery-builder/internal/versions/reservedname_test.go @@ -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 { diff --git a/modules/mesh-delivery-builder/internal/versions/store.go b/modules/mesh-delivery-builder/internal/versions/store.go index 5cdb30ca5..2ee317f35 100644 --- a/modules/mesh-delivery-builder/internal/versions/store.go +++ b/modules/mesh-delivery-builder/internal/versions/store.go @@ -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 -} diff --git a/modules/mesh-delivery-builder/internal/versions/tools.go b/modules/mesh-delivery-builder/internal/versions/tools.go index 8a562cbf5..f173729cc 100644 --- a/modules/mesh-delivery-builder/internal/versions/tools.go +++ b/modules/mesh-delivery-builder/internal/versions/tools.go @@ -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." diff --git a/modules/mesh-delivery-builder/internal/versions/versions.go b/modules/mesh-delivery-builder/internal/versions/versions.go index b04dd7ca9..aec87cb9b 100644 --- a/modules/mesh-delivery-builder/internal/versions/versions.go +++ b/modules/mesh-delivery-builder/internal/versions/versions.go @@ -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 `_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.