B7 publish-again-on-events: a publish is put again on a registry holder's running or its node's return, once per sequence, never on a timer

Builds: design 47 H2 H-A-606 (and its round 3), H-A-613 (3), H-A-720 (1), H-A-741 (2); returned's node match waits on contracts' SeatHolderNodes (H-A-742)
This commit is contained in:
2026-11-25 17:45:06 +01:00
parent 72ef5dc7c4
commit 64398c792b
11 changed files with 400 additions and 596 deletions
@@ -289,11 +289,15 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
reserved.r.HeldElsewhere = func(ctx context.Context, module string, skipped []string) {
reserved.heldElsewhere(ctx, module, "the registries hold "+strings.Join(skipped, ", ")+", so the reserve skipped them")
}
publishSet, err := publishSettingsOf(getenv)
publishAck, err := numberFile(getenv("MESH_BUILDER_PUBLISH_ACK_FILE"), defaultPublishAckMinutes)
if err != nil {
return err
}
pq.ackWait = publishSet.PauseMax // a sent item unheard is delivered again after the longest pause (H-A-440 (1))
republishMax, err := numberFile(getenv("MESH_BUILDER_REPUBLISH_MAX_FILE"), versions.DefaultRepublishMaxVersions)
if err != nil {
return err
}
pq.ackWait = time.Duration(publishAck) * time.Minute // a sent item unheard is given again after the publish bound (H-A-613 (3))
actedDays, err := numberFile(getenv("MESH_BUILDER_ACTED_DAYS_FILE"), versions.DefaultActedDays)
if err != nil {
return err
@@ -307,19 +311,17 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}
reasksKV := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.ReAsksState), "builder_ask_again is not heard; an ask that can no longer be answered is still asked again by itself", logger.Printf)
// A version's publish is the builder's own work until its release is written (design 47 G A-457a): an item of the re-ask state.
items := &publishItems{reasks: reasksKV.KV, set: publishSet, now: time.Now, logf: logger.Printf,
items := &publishItems{reasks: reasksKV.KV, now: time.Now, logf: logger.Printf,
reserved: func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) {
return reserved.r.Of(ctx, module, version)
},
republish: republish.Republish, endedWith: reserved.unreleased,
republish: republish.Republish,
// A publish is asked again while the registry's record lacks it (H-A-269 (2), H-A-272; H-A-514 addendum: no backlog count).
judge: func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) {
return republish.Held(ctx, v, registryVersionsVia(calls.Call))
},
markHeld: reserved.markHeld, moveElsewhere: reserved.movedElsewhere,
allDone: func(ctx context.Context) ([]versions.ReservedVersion, error) { return reserved.r.All(ctx) },
send: republish.SendQueued,
retired: reserved.r.Retired} // only each module's newest done build is asked at the start (H-A-291 (1))
send: republish.SendQueued}
// A version that never publishes (withdrawn or taken over) has its publish item ended by the queue too (H-A-290 (2)).
republish.Ended = items.Ended
pq.take = items.take
@@ -327,7 +329,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
// before the publish items of the rest are asked.
reasksKV.Ready(func(jetstream.KeyValue) {
reserved.releasedAtStart(ctx)
items.AskAllDone(ctx)
})
wirePublishItems(reserved, items, awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, releasedKept)
acts.Republish = republish.Republish
@@ -347,6 +348,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
if err := operator.Listen(); err != nil {
return fmt.Errorf("hearing the operator's answers: %w", err)
}
again := &publishingAgain{a: &versions.Againer{Republisher: republish, Acted: retakeActed, MaxVersions: republishMax}}
retake := &retaking{rt: &build.Retaker{Builder: b, Acted: retakeActed, Entry: entryVia(calls.Call), Ask: operator.Ask, Logf: logger.Printf}}
// What waits on the work queue is pulled, and the old state's items are put on it once (§793).
go func() {
@@ -485,6 +487,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
takers := []eventTaker{
{"the operator's answer to an ask about a key", decided.heard}, // §568
{"the retake of a key failed on a transport fault", func(m jetstream.Msg) bool { return retake.heard(ctx, m, logger.Printf) }}, // §568
{"the publish again of reserved versions", func(m jetstream.Msg) bool { return again.heard(ctx, m, logger.Printf) }}, // ADR 0674 §2
{"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) }},
@@ -46,10 +46,10 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
t.Fatal(err)
}
// One consumer per holder (H-A-483 and its addenda): the holder's class durables of an earlier release are retired, the item
// one of them held unacknowledged reaches the one consumer; no item is lost; a failed send comes back after its pause, and a
// live item put while it waits is sent before it returns; a dropped item never comes back.
// one of them held unacknowledged reaches the one consumer; no item is lost; a failed send ends its item and is never sent again
// on a timer; a dropped item never comes back.
t.Run("one consumer", func(t *testing.T) {
const holder, pause = "paused", 3 * time.Second // the pause is far longer than a send of an item put now
const holder = "paused"
bound := testbus.SetupBound(t)
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
type send struct {
@@ -59,7 +59,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
var mu sync.Mutex
published, failed := map[string]bool{}, map[string]bool{}
sentCh := make(chan send, 16)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: pause, PauseMax: time.Minute, Tries: 5},
items := &publishItems{reasks: func() jetstream.KeyValue { return kv },
now: time.Now, logf: t.Logf,
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
mu.Lock()
@@ -145,24 +145,18 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
}
put("fail", versions.PublishClassStart)
put("dropme", versions.PublishClassStart)
var firstFail time.Time
for range 2 {
if s := next(); s.module == "fail" {
firstFail = s.at
}
for range 2 { // the first send of each fails: its item ends, the version stays reserved, nothing hands it back after a pause (H-A-606)
next()
}
put("live", versions.PublishClassLive) // put while both failed items wait out their pause
put("live", versions.PublishClassLive)
if s := next(); s.module != "live" {
t.Fatalf("sent %s, want the live item put while the failed ones wait their pause", s.module)
t.Fatalf("sent %s, want the live item put after the failed ones", s.module)
}
if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil {
t.Fatalf("drop: %v", err)
} else {
t.Log(answer)
}
if s := next(); s.module != "fail" || s.at.Sub(firstFail) < pause {
t.Fatalf("sent %s %s after the failed send, want fail again after its pause %s", s.module, s.at.Sub(firstFail), pause)
}
// Every item is acknowledged and the dropped one is gone: nothing is left to come back.
c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder))
if err != nil {
@@ -202,7 +196,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
var sent []string
published := map[string]bool{} // the modules whose publish is heard
sentCh := make(chan string, 200)
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: time.Second, PauseMax: time.Minute, Tries: 5},
items := &publishItems{reasks: func() jetstream.KeyValue { return kv },
now: time.Now, logf: t.Logf,
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
mu.Lock()
@@ -24,40 +24,17 @@ import (
"mesh-delivery-builder/internal/versions"
)
// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793): each
// reservation of a done build is a publish item in the builder's re-ask state, asked when the build ends and at the builder's
// start; its try puts the publish on the work queue publishes, and each send counts one try in the item and hands a failed one
// back with a longer pause; the release deletes it; after its tries it ends loudly and stays readable in builder_publish_queue.
// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793, H-A-606): the
// ask at a build's end is the first try, and it puts the publish on the work queue publishes; a publish that is refused or fails stays
// reserved, with version-unreleased naming the holder's words, and is put again only on ADR 0674 §2's events (a registry holder's
// running, a returned of its node: versions.Againer) or by builder_publish_again. No timer, pause or count of tries stands on this path.
// publishSettings are the settings publish-pause, publish-pause-max and publish-tries.
type publishSettings struct {
Pause, PauseMax time.Duration
Tries int
}
// defaultPublishSettings are the settings' defaults: 30 s, 30 min and 5 tries (H-A-446 (2)).
var defaultPublishSettings = publishSettings{Pause: 30 * time.Second, PauseMax: 30 * time.Minute, Tries: 5}
// pauseAfter is the pause after the try-th try: the setting doubled per try, up to the maximum.
func (s publishSettings) pauseAfter(try int) time.Duration {
d := s.Pause
for i := 1; i < try && d < s.PauseMax; i++ {
d *= 2
}
return min(d, s.PauseMax)
}
// publishItems asks, tries and ends the publish items.
// publishItems asks and takes the publishes of reserved versions.
type publishItems struct {
reasks func() jetstream.KeyValue // the re-ask state, nil until it is bound
reasks func() jetstream.KeyValue // the re-ask state: the record of a dropped version's publish (builder_publish_drop), nil until bound
now func() time.Time
reserved func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error)
republish func(ctx context.Context, module, version string) ([]string, error)
endedWith func(ctx context.Context, v versions.ReservedVersion, why string) // raises the finding version-unreleased
// allDone are the reservations, done or not: those whose build is done are asked at the start (builtOf).
allDone func(ctx context.Context) ([]versions.ReservedVersion, error)
// retired are the done builds a newer reservation or release of the same module supersedes, with why (H-A-291 (1)); nil
// retires none.
retired func(ctx context.Context, all []versions.ReservedVersion) (map[string]string, error)
// judge is what the registries' own record says of a version's missing artifacts (H-A-272, H-A-274, H-A-275); nil judges none.
judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error)
// markHeld marks the artifacts the registries hold with the built digest published from their record, as their published heard
@@ -66,126 +43,46 @@ type publishItems struct {
markHeld func(ctx context.Context, v versions.ReservedVersion, held []versions.HeldArtifact)
moveElsewhere func(ctx context.Context, v versions.ReservedVersion, j versions.Judged) error
// send sends one item pulled from the work queue (Republisher.SendQueued); nil sends none.
send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate
set publishSettings
now func() time.Time
after func(time.Duration) <-chan time.Time
logf func(string, ...any)
send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate
logf func(string, ...any)
mu sync.Mutex
held map[string][]heldItem // "<module> <version>": the items sent, their publish not yet heard
}
func (p *publishItems) wait(ctx context.Context, d time.Duration) bool {
if d <= 0 {
return ctx.Err() == nil
}
after := p.after
if after == nil {
after = time.After
}
select {
case <-after(d):
return true
case <-ctx.Done():
return false
}
}
// Ask writes the publish item of a version whose build is done, when none stands: its first try is now.
// Ask puts the publish of a version whose build is done on the work queue: its first try, at the build's end (A-473).
func (p *publishItems) Ask(ctx context.Context, module, version string) error {
kv := p.reasks()
if kv == nil {
return errors.New("the re-ask state is not on the bus yet")
}
raw, err := json.Marshal(build.ReAsk{V: 1, Why: "the build ended with its version unreleased", By: "the builder", At: p.now().UTC(), Mode: build.ModePublish, Module: module, Version: version, NextTry: p.now().UTC()})
queued, err := p.republish(ctx, module, version)
if err != nil {
return err
return fmt.Errorf("the publish of %s %s is not put on the work queue %s: %w", module, version, versions.PublishesLocal, err)
}
if _, err := kv.Create(ctx, versions.PublishItemKey(module, version), raw); err != nil && !errors.Is(err, jetstream.ErrKeyExists) {
return fmt.Errorf("the publish item of %s %s cannot be written: %w", module, version, err)
if len(queued) == 0 {
p.logf("%s %s: the publish is not put on the work queue %s: nothing of it is left to queue", module, version, versions.PublishesLocal)
}
return nil
}
// AskAllDone asks the publish item of every reservation whose build is done and that has no release: at the builder's start, so
// what stood before this change moves too, whatever its artifacts.
func (p *publishItems) AskAllDone(ctx context.Context) {
all, err := p.allDone(ctx)
if err != nil {
p.logf("the reservations of done builds are not asked to publish at the start: %v", err)
return
}
var retired map[string]string
if p.retired != nil {
if retired, err = p.retired(ctx, all); err != nil {
p.logf("the superseded builds are not retired at the start: %v", err)
}
}
for _, v := range builtOf(all) {
if why := retired[v.Module+" "+v.Version]; why != "" { // only each module's newest is asked (H-A-291 (1), H-A-275)
p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why)
p.Done(ctx, v.Module, v.Version)
continue
}
if why := versions.NotStanding(v, true); why != "" { // withdrawn: it never publishes (H-A-290 (2))
p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why)
p.Done(ctx, v.Module, v.Version)
continue
}
if err := p.Ask(ctx, v.Module, v.Version); err != nil {
p.logf("%v", err)
}
}
}
// Done deletes a version's publish item and acknowledges its held items: its release is written.
// Done acknowledges a version's held items: its release is written.
func (p *publishItems) Done(ctx context.Context, module, version string) {
for _, h := range p.settle(module, version, func(heldItem) bool { return true }) {
_ = h.m.Ack()
}
kv := p.reasks()
if kv == nil {
return
}
if err := kv.Delete(ctx, versions.PublishItemKey(module, version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
p.logf("the publish item of %s %s is not deleted: %v", module, version, err)
}
}
// Try waits for the item's next try, then, while the version is still reserved, puts its publish on the work queue publishes
// under its message id (design 47 H2 §793; H-A-448): an item the queue holds already is put once. It counts no try: each send
// does, and hands its item back with the pause (take). A put that queued nothing is put again after the pause. A version no
// longer reserved (released, dropped or taken over) has its item deleted.
func (p *publishItems) Try(ctx context.Context, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk) {
if !p.wait(ctx, r.NextTry.Sub(p.now())) {
return
// droppedWhy is the answer of a version's ended publish record (builder_publish_drop), empty when none ended it.
func (p *publishItems) droppedWhy(ctx context.Context, module, version string) string {
kv := p.reasks()
if kv == nil {
return ""
}
cur, err := kv.Get(ctx, e.Key())
if err != nil || cur.Revision() != e.Revision() {
return // deleted by the release, or written again
}
v, held, err := p.reserved(ctx, r.Module, r.Version)
e, err := kv.Get(ctx, versions.PublishItemKey(module, version))
if err != nil {
p.logf("%s %s: its reservation cannot be read, the publish item waits: %v", r.Module, r.Version, err)
return
return ""
}
if why := versions.NotStanding(v, held); why != "" { // dropped, taken over, released or withdrawn (A-456b, H-A-290 (2))
p.logf("%s %s: the publish item is ended: %s", r.Module, r.Version, why)
_ = kv.Delete(ctx, e.Key())
return
}
queued, err := p.republish(ctx, r.Module, r.Version)
if err == nil && len(queued) > 0 {
return
}
r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries))
p.logf("%s %s: the publish is not on the work queue %s (%v); it is put again after %s", r.Module, r.Version, versions.PublishesLocal, err, p.set.pauseAfter(r.Tries))
if data, err := json.Marshal(r); err == nil {
if _, err := kv.Update(ctx, e.Key(), data, e.Revision()); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) {
p.logf("%s: the publish item could not be written: %v", e.Key(), err)
}
if r, err := build.DecodeReAsk(e.Value()); err == nil {
return r.Answer
}
return ""
}
// itemMsg is what take reads of an item pulled from the work queue (jetstream.Msg).
@@ -196,12 +93,11 @@ type itemMsg interface {
Term() error
}
// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448): an item whose publish item ended (dropped, or
// its tries spent) or whose version never publishes is terminated; one whose artifacts are all published is acknowledged; once
// publish-tries sends are spent it is terminated and version-unreleased said; while a published of it may be unheard it is handed
// back with the pause, and one the registries' record confirms is acknowledged (H-A-274); else it is sent, the try counted in its
// publish item, and a send that fails handed back with the pause as its delay, so the queue delivers it again and nothing is put
// again. A sent item is acknowledged when its publish is heard (heard, Done) and delivered again after the ack wait, unheard.
// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448, H-A-606): an item whose version never publishes is
// terminated; one whose artifacts are all published is acknowledged; one the registries' record confirms is acknowledged (H-A-274);
// else it is sent. A sent item is acknowledged when its publish is heard (heard, Done) and given again after the ack wait, unheard.
// A send that fails or is refused ends the item, the version staying reserved with version-unreleased naming the holder's words
// (said by the send): it is put again only on the next event of ADR 0674 §2 or by builder_publish_again, never on a timer.
func (p *publishItems) take(ctx context.Context, m itemMsg) {
var q versions.QueuedPublish
if err := json.Unmarshal(m.Data(), &q); err != nil || q.Module == "" || q.Version == "" {
@@ -209,44 +105,19 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
_ = m.Term()
return
}
kv := p.reasks()
if kv == nil {
p.logf("%s %s: the re-ask state is not on the bus yet; the item is handed back", q.Module, q.Version)
_ = m.NakWithDelay(p.set.Pause)
return
}
key := versions.PublishItemKey(q.Module, q.Version)
e, err := kv.Get(ctx, key)
if errors.Is(err, jetstream.ErrKeyNotFound) { // put by builder_publish_again or the move: its tries are counted from now
if err = p.Ask(ctx, q.Module, q.Version); err == nil {
e, err = kv.Get(ctx, key)
}
}
if err != nil {
p.logf("%s %s: its publish item cannot be read (%v); the item is handed back", q.Module, q.Version, err)
_ = m.NakWithDelay(p.set.Pause)
return
}
r, err := build.DecodeReAsk(e.Value())
if err != nil {
_ = m.Term()
return
}
if r.Answer != "" {
p.logf("%s %s at %s is terminated: its publish item ended: %s", q.Module, q.Version, q.Holder, r.Answer)
if why := p.droppedWhy(ctx, q.Module, q.Version); why != "" {
p.logf("%s %s at %s is terminated: its publish ended: %s", q.Module, q.Version, q.Holder, why)
_ = m.Term()
return
}
v, found, err := p.reserved(ctx, q.Module, q.Version)
if err != nil {
p.logf("%s %s: its reservation cannot be read (%v); the item is handed back", q.Module, q.Version, err)
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
p.logf("%s %s: its reservation cannot be read (%v); the item is given again after the ack wait", q.Module, q.Version, err)
return
}
if why := versions.NotStanding(v, found); why != "" {
p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, why)
_ = m.Term()
_ = kv.Delete(ctx, key)
return
}
if allPublished(v, q) {
@@ -254,17 +125,6 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
_ = m.Ack()
return
}
if r.Tries >= p.set.Tries {
_ = m.Term()
r.Answer = fmt.Sprintf("the publish of %s %s was tried %d times and the version is not released; builder_publish_again tries it again", r.Module, r.Version, r.Tries)
r.Answered = p.now().UTC()
p.logf("%s: %s", key, r.Answer)
if p.endedWith != nil {
p.endedWith(ctx, v, "the publish ended after "+fmt.Sprint(r.Tries)+" tries")
}
p.write(ctx, kv, key, r, e.Revision())
return
}
if why, gone := p.notAgain(ctx, v); gone {
_ = m.Term() // moved to another number, whose own item is asked (H-A-275)
return
@@ -274,8 +134,8 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
_ = m.Ack()
return
}
p.logf("%s %s: the publish is not sent again: %s; handed back for %s", q.Module, q.Version, why, p.set.pauseAfter(r.Tries))
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
p.logf("%s %s at %s: the publish is not sent: %s; the item is ended, the version stays reserved", q.Module, q.Version, q.Holder, why)
_ = m.Term()
return
}
fate := versions.SendFate{Failed: "this builder sends no publish"}
@@ -287,28 +147,14 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
_ = m.Term()
return
}
r.Tries++
r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries))
p.write(ctx, kv, key, r, e.Revision())
if fate.Failed != "" {
p.logf("%s %s at %s: try %d sent no publish: %s; handed back for %s", q.Module, q.Version, q.Holder, r.Tries, fate.Failed, p.set.pauseAfter(r.Tries))
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
p.logf("%s %s at %s: sent no publish: %s; the item is ended, the version stays reserved and is put again on the next event of its holder (H-A-606)", q.Module, q.Version, q.Holder, fate.Failed)
_ = m.Term()
return
}
p.hold(q, m)
}
// write writes a publish item at its revision; a newer write wins.
func (p *publishItems) write(ctx context.Context, kv jetstream.KeyValue, key string, r build.ReAsk, rev uint64) {
data, err := json.Marshal(r)
if err != nil {
return
}
if _, err := kv.Update(ctx, key, data, rev); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) {
p.logf("%s: the publish item could not be written: %v", key, err)
}
}
// allPublished says none of q's artifacts is missing from v: its publish is heard.
func allPublished(v versions.ReservedVersion, q versions.QueuedPublish) bool {
missing := map[string]bool{}
@@ -461,24 +307,6 @@ func numberFile(path string, def int) (int, error) {
return n, nil
}
// publishSettingsOf reads publish-pause (seconds), publish-pause-max (minutes) and publish-tries from their files.
func publishSettingsOf(getenv func(string) string) (publishSettings, error) {
s := defaultPublishSettings
pause, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_FILE"), int(s.Pause/time.Second))
if err != nil {
return s, err
}
pmax, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"), int(s.PauseMax/time.Minute))
if err != nil {
return s, err
}
tries, err := numberFile(getenv("MESH_BUILDER_PUBLISH_TRIES_FILE"), s.Tries)
if err != nil {
return s, err
}
return publishSettings{Pause: time.Duration(pause) * time.Second, PauseMax: time.Duration(pmax) * time.Minute, Tries: tries}, nil
}
// wirePublishItems joins the reservations to the publish items (design 47 G A-457a, A-456a, A-456b, H2 §793): a done build asks its
// item, a release ends it and acknowledges its held items, a drop and a takeover end it and terminate them, a published heard
// acknowledges those it publishes, and a release is recorded in releases, the last kept of each module.
@@ -529,6 +357,9 @@ func publishesOf(module string) func() (publishesStream, error) {
// The consumer's numbers (H-A-446 (2)): at most four sends in flight per holder, and ten deliveries, the work queue's largest;
// the builder ends an item at publish-tries anyway.
// defaultPublishAckMinutes is the setting publish-ack-minutes' default: G section 369's publish bound (H-A-606 round 3 (3)).
const defaultPublishAckMinutes = 10
const (
publishesMaxAckPending = versions.PublishSendsAtOnce
publishesMaxDeliver = 10
@@ -5,9 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
@@ -16,9 +13,6 @@ import (
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"mesh-delivery-builder/internal/build"
"mesh-delivery-builder/internal/versions"
)
@@ -122,26 +116,19 @@ func decodeItem(t *testing.T, raw []byte) build.ReAsk {
return r
}
// TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly: design 47 G A-457a, H2 §793 (H-A-440 (2), H-A-448) — a version's publish
// item is asked once; its try puts the publish on the work queue and counts no try; each send counts one and a failed send hands
// the item back with the pause doubled up to its maximum; after the setting's tries the item is terminated and ends with its words,
// raises the condition and stays; an item whose artifacts are published is acknowledged; the release deletes it; a version no
// longer reserved has it deleted.
func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) {
// TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer: design 47 H2 H-A-606 (A-473) — the ask at a build's end puts the publish on the
// work queue once; a send that fails or is refused ends its item, the version stays reserved and nothing hands it back after a pause;
// an item whose artifacts are published is acknowledged; a version no longer reserved is terminated; a publish its drop ended is
// terminated whatever puts it again.
func TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer(t *testing.T) {
ctx := context.Background()
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
now := time.Date(2026, 11, 17, 1, 0, 0, 0, time.UTC)
var queued, ended, sent []string
var queued, sent []string
reserved := true
v := versions.ReservedVersion{Module: "m", Version: "0.1.2", Artifacts: map[string]string{"m:a": "sha256:a"}, BuiltAt: now}
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: 30 * time.Second, PauseMax: 2 * time.Minute, Tries: 4},
now: func() time.Time { return now }, logf: t.Logf,
after: func(d time.Duration) <-chan time.Time {
now = now.Add(d)
c := make(chan time.Time, 1)
c <- now
return c
},
fate := versions.SendFate{Failed: "no holder answers"}
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, now: func() time.Time { return now }, logf: t.Logf,
reserved: func(_ context.Context, _, ver string) (versions.ReservedVersion, bool, error) {
if ver == "0.3.0" { // every artifact published, its release not written yet
return versions.ReservedVersion{Module: "m", Version: ver, Artifacts: map[string]string{"m:a": "sha256:a"}, Published: map[string]bool{"m:a": true}, BuiltAt: now}, true, nil
@@ -154,305 +141,41 @@ func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) {
},
send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate {
sent = append(sent, q.Module+" "+q.Version)
return versions.SendFate{Failed: "no holder answers"}
},
endedWith: func(_ context.Context, v versions.ReservedVersion, why string) {
ended = append(ended, v.Version+": "+why)
return fate
}}
key := versions.PublishItemKey("m", "0.1.2")
if err := p.Ask(ctx, "m", "0.1.2"); err != nil || p.Ask(ctx, "m", "0.1.2") != nil || len(kv.vals) != 1 {
t.Fatalf("asked: %v, %d items, want one item however often it is asked", err, len(kv.vals))
}
e, _ := kv.Get(ctx, key)
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
if len(queued) != 1 || decodeItem(t, kv.vals[key]).Tries != 0 {
t.Fatalf("the try queued %v, tries %d: want the publish put once, no try counted", queued, decodeItem(t, kv.vals[key]).Tries)
}
var settled []string
for range 5 {
m := queuedMsg(t, "m", "0.1.2")
p.take(ctx, m)
settled = append(settled, m.settled...)
}
got := decodeItem(t, kv.vals[key])
if len(sent) != 4 || got.Tries != 4 || got.Answer == "" || got.Answered.IsZero() || len(ended) != 1 || !strings.Contains(ended[0], "4 tries") {
t.Fatalf("sent %v, item %+v, ended %v: want four sends, then the end said with its words and the condition", sent, got, ended)
}
if want := "[nak 30s nak 1m0s nak 2m0s nak 2m0s term]"; fmt.Sprint(settled) != want {
t.Errorf("the items were settled %v, want %s (handed back with the pause doubled and capped, then terminated)", settled, want)
if err := p.Ask(ctx, "m", "0.1.2"); err != nil || len(queued) != 1 || len(kv.vals) != 0 {
t.Fatalf("asked: %v, queued %v, %d items: want the publish put once and no item kept", err, queued, len(kv.vals))
}
m := queuedMsg(t, "m", "0.1.2")
if p.take(ctx, m); fmt.Sprint(m.settled) != "[term]" || len(sent) != 4 {
t.Errorf("an item of an ended publish item was settled %v, sent %d: want it terminated unsent", m.settled, len(sent))
p.take(ctx, m)
if len(sent) != 1 || !slices.Equal(m.settled, []string{"term"}) {
t.Fatalf("a failed send: sent %v, settled %v, want one send and the item terminated, never handed back with a pause", sent, m.settled)
}
fate = versions.SendFate{Sent: true}
m = queuedMsg(t, "m", "0.1.2")
p.take(ctx, m)
if len(m.settled) != 0 {
t.Fatalf("a sent item is settled %v, want it held until its publish is heard", m.settled)
}
// An item whose artifacts are all published is acknowledged unsent; its publish item stays until its release is written (A-456b).
_ = p.Ask(ctx, "m", "0.3.0")
pk := versions.PublishItemKey("m", "0.3.0")
m = queuedMsg(t, "m", "0.3.0")
if p.take(ctx, m); fmt.Sprint(m.settled) != "[ack]" || len(sent) != 4 || !kv.has(pk) {
t.Errorf("an item whose artifacts are published was settled %v, sent %d, kept %v: want it acknowledged unsent, its publish item kept", m.settled, len(sent), kv.has(pk))
p.take(ctx, m)
if !slices.Equal(m.settled, []string{"ack"}) {
t.Errorf("an item whose artifacts are published settled %v, want ack", m.settled)
}
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
// At the start every reservation of a done build with no release is asked, one item each.
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
p.allDone = func(context.Context) ([]versions.ReservedVersion, error) {
published := versions.ReservedVersion{Module: "n", Version: "0.2.0", Artifacts: map[string]string{"n:a": "sha256:a"}, Published: map[string]bool{"n:a": true}, BuiltAt: now}
withdrawn := versions.ReservedVersion{Module: "w", Version: "0.4.0", BuiltAt: now, Withdrawn: map[string]string{"0.4.0": "fp"}}
return builtOf([]versions.ReservedVersion{v, published, withdrawn, {Module: "o", Version: "0.1.0"}}), nil // the last build has not ended
}
_ = p.Ask(ctx, "w", "0.4.0") // asked before its reservation was withdrawn
p.AskAllDone(ctx)
if _, ok := kv.vals[versions.PublishItemKey("w", "0.4.0")]; len(kv.vals) != 2 || ok {
t.Errorf("the start left %d items (withdrawn's kept: %v), want one per done unreleased reservation and none for a withdrawn one (H-A-290 (2))", len(kv.vals), ok)
}
// A start with three unreleased done versions of one module asks only the newest and retires the two (H-A-291 (1), H-A-275).
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
_ = p.Ask(ctx, "s", "0.1.3") // asked in an earlier run
p.allDone = func(context.Context) ([]versions.ReservedVersion, error) {
var out []versions.ReservedVersion
for _, ver := range []string{"0.1.3", "0.1.10", "0.1.2"} { // one series (H-A-293)
out = append(out, versions.ReservedVersion{Module: "s", Version: ver, Artifacts: map[string]string{"s:a": "sha256:a"}, BuiltAt: now})
}
return out, nil
}
p.retired = (&versions.Reserver{}).Retired
p.AskAllDone(ctx)
if _, ok := kv.vals[versions.PublishItemKey("s", "0.1.10")]; len(kv.vals) != 1 || !ok {
t.Errorf("the start left the items %v, want only the newest, s 0.1.10, asked and the two older retired", slices.Collect(maps.Keys(kv.vals)))
}
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
// A released version's item is deleted; a version no longer reserved has it deleted at its next try.
p.Done(ctx, "m", "0.1.2")
p.Done(ctx, "n", "0.2.0")
if len(kv.vals) != 0 {
t.Errorf("the release left %v", kv.vals)
}
// A withdrawn reservation has its item ended at its try, nothing queued (H-A-290 (2)).
queued = nil
_ = p.Ask(ctx, "m", "0.1.2")
v.Withdrawn = map[string]string{"0.1.2": "fp"}
e, _ = kv.Get(ctx, key)
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
if len(kv.vals) != 0 || len(queued) != 0 {
t.Errorf("a withdrawn reservation left its item %v, queued %v", kv.vals, queued)
}
v.Withdrawn = nil
_ = p.Ask(ctx, "m", "0.1.2")
reserved = false
e, _ = kv.Get(ctx, key)
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
if len(kv.vals) != 0 {
t.Errorf("a dropped reservation left its item %v", kv.vals)
m = queuedMsg(t, "m", "0.1.2")
p.take(ctx, m)
if !slices.Equal(m.settled, []string{"term"}) {
t.Errorf("an item of a version no longer reserved settled %v, want term", m.settled)
}
}
// TestThePublishSettingsAreReadFromTheirFiles: design 47 G A-457a, H2 H-A-446 (2) — the three settings, 30 s, 30 min and 5 tries
// unless set, and a
// content that is no number is refused naming its file.
func TestThePublishSettingsAreReadFromTheirFiles(t *testing.T) {
dir := t.TempDir()
write := func(name, v string) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte(v), 0o600); err != nil {
t.Fatal(err)
}
return p
}
env := map[string]string{}
got, err := publishSettingsOf(func(k string) string { return env[k] })
if err != nil || got != defaultPublishSettings || got.Pause != 30*time.Second || got.PauseMax != 30*time.Minute || got.Tries != 5 {
t.Fatalf("defaults = %+v (%v)", got, err)
}
env["MESH_BUILDER_PUBLISH_PAUSE_FILE"], env["MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"], env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("p", "5\n"), write("m", "2"), write("t", "3")
if got, err = publishSettingsOf(func(k string) string { return env[k] }); err != nil || got != (publishSettings{5 * time.Second, 2 * time.Minute, 3}) {
t.Errorf("set = %+v (%v)", got, err)
}
env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("bad", "many")
if _, err = publishSettingsOf(func(k string) string { return env[k] }); err == nil || !strings.Contains(err.Error(), "bad") {
t.Errorf("a content that is no number: %v", err)
}
}
// TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch: design 47 G A-457a, A-456b — a mode-publish value of the re-ask state
// reaches the item's try through reAsked; a done build gets an item; the catalog's version-released, a drop and a takeover delete it
// and the release is kept by module.
func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T) {
ctx := context.Background()
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
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) }}
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, 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) {
return rv.r.Of(ctx, m, v)
},
republish: func(_ context.Context, m, v string) ([]string, error) { tried <- m + " " + v; return nil, nil }}
releases := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
wirePublishItems(rv, items, releases, 2)
done := func(fp string) versions.ReservedVersion {
v, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: fp})
if err != nil {
t.Fatal(err)
}
if err := rv.Built(ctx, "m", v.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil {
t.Fatal(err)
}
return v
}
first := done("src2:one")
key := versions.PublishItemKey("m", first.Version)
if !kv.has(key) {
t.Fatalf("a done build has no publish item: %v", kv.vals)
}
// A build whose artifacts are all published still gets its item, until its release is written (A-456b).
if _, _, err := rv.r.Published(ctx, versions.NameOf("m", "a"), first.Version, "sha256:a"); err != nil {
t.Fatal(err)
}
items.Done(ctx, "m", first.Version)
if err := rv.Built(ctx, "m", first.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil {
t.Fatal(err)
}
if !kv.has(key) {
t.Fatalf("a build with every artifact published has no item: %v", kv.vals)
}
// The watch hands the item to its try, which queues the publish.
e, _ := kv.Get(ctx, key)
reAsked(ctx, nil, versions.Acts{}, items, kv, e, t.Logf)
select {
case got := <-tried:
if got != "m "+first.Version {
t.Errorf("tried %q", got)
}
case <-time.After(10 * time.Second):
t.Fatal("a mode-publish value was not handed to the item's try")
}
// A takeover by another build deletes the older's item and asks the newer's.
second := done("src2:two")
if kv.has(key) {
t.Errorf("the taken-over reservation kept its item")
}
secondKey := versions.PublishItemKey("m", second.Version)
if !kv.has(secondKey) {
t.Fatalf("the newer build has no item: %v", kv.vals)
}
// version-released deletes the item and keeps the release.
msg := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"m","version":"` + second.Version + `","source":1,"artifacts":[]}`)}
if !rv.heard(ctx, msg) || !msg.acked {
t.Fatal("version-released was not taken in")
}
if kv.has(secondKey) {
t.Errorf("a released version kept its publish item")
}
if ok, _ := rv.ReleasedFor(ctx, "m", "src2:two"); !ok {
t.Errorf("the release is not kept by fingerprint")
}
// A drop deletes the item too.
third := done("src2:three")
// H2 H-A-592 (1): another version than the one standing is refused naming the standing one; so is a drop while its fingerprint builds
if _, err := rv.dropped(ctx, "m", "0.1", "0.1.99", "op", "never", time.Unix(0, 0)); err == nil || !strings.Contains(err.Error(), third.Version) {
t.Errorf("a drop naming another version answered %v, want a refusal naming %s", err, third.Version)
}
rv.looking = func(module, fp string) bool { return module == "m" && fp == "src2:three" }
if _, err := rv.dropped(ctx, "m", "0.1", third.Version, "op", "never", time.Unix(0, 0)); err == nil || !strings.Contains(err.Error(), "building") {
t.Errorf("a drop while the fingerprint builds answered %v, want a refusal", err)
}
rv.looking = nil
answer, err := rv.dropped(ctx, "m", "0.1", third.Version, "op", "never", time.Unix(0, 0))
if err != nil || !strings.Contains(answer, third.Version) || !strings.Contains(answer, "src2:three") {
t.Fatalf("the drop answered %q (%v), want it to name the version and the fingerprint it forgot", answer, err)
}
if kv.has(versions.PublishItemKey("m", third.Version)) {
t.Errorf("a dropped reservation kept its item")
}
}
// Design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275, and design 47 H2 H-A-514 addendum: a publish is asked again judged from
// what the builder recorded and the registries' record alone, never from how many events its consumer holds unheard: a
// reservation marking every artifact published is acknowledged; a record holding every missing artifact with the built digest
// marks them published from it; a record holding the version at another digest moves the build to the next free number and
// ends this item; a record lacking it is asked again; a skipped try spends no try and is written again with its pause.
func TestAPublishIsAskedAgainFromWhatTheBuilderRecorded(t *testing.T) {
ctx := context.Background()
now := time.Date(2026, 11, 21, 15, 21, 0, 0, time.UTC)
v := versions.ReservedVersion{Module: "node-tools", Version: "0.1.37", Artifacts: map[string]string{"node-tools:program": "sha256:7c9b10"}, BuiltAt: now}
at := versions.HeldArtifact{Ref: "node-tools:program", Seat: versions.SeatArtifacts, Name: "node-tools/program", Version: "0.1.37", Digest: "sha256:7c9b10"}
other := at
other.Digest = "sha256:83bec1"
for _, c := range []struct {
name string
published bool
judged versions.Judged
wantAsked, wantMark, wantMov bool
}{
{name: "its reservation marks it published: acknowledged, no ask", published: true},
{name: "the registry holds it: marked from its record, no ask", judged: versions.Judged{All: true, Held: []versions.HeldArtifact{at}}, wantMark: true},
{name: "the registry holds the number at another digest: moved, no ask", judged: versions.Judged{Elsewhere: []versions.HeldArtifact{other}}, wantMov: true},
{name: "the registry lacks it: asked, whatever the events consumer holds", judged: versions.Judged{Lacks: "none"}, wantAsked: true},
} {
t.Run(c.name, func(t *testing.T) {
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
asked, judged, marked, moved := 0, 0, 0, 0
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: func() time.Time { return now }, logf: t.Logf,
reserved: func(context.Context, string, string) (versions.ReservedVersion, bool, error) {
if c.published {
w := v
w.Published = map[string]bool{"node-tools:program": true}
return w, true, nil
}
return v, true, nil
},
send: func(context.Context, versions.QueuedPublish) versions.SendFate {
asked++
return versions.SendFate{Sent: true}
},
judge: func(context.Context, versions.ReservedVersion) (versions.Judged, error) {
judged++
return c.judged, nil
},
markHeld: func(_ context.Context, _ versions.ReservedVersion, h []versions.HeldArtifact) {
if len(h) == 1 && h[0].Digest == "sha256:7c9b10" {
marked++
}
},
moveElsewhere: func(context.Context, versions.ReservedVersion, versions.Judged) error {
moved++
delete(kv.vals, versions.PublishItemKey(v.Module, v.Version)) // the takeover ends the old item
return nil
}}
if err := p.Ask(ctx, v.Module, v.Version); err != nil {
t.Fatal(err)
}
key := versions.PublishItemKey(v.Module, v.Version)
m := queuedMsg(t, v.Module, v.Version)
m.data = []byte(strings.ReplaceAll(string(m.data), `"node-tools:a"`, `"node-tools:program"`))
p.take(ctx, m)
if (asked == 1) != c.wantAsked || (marked == 1) != c.wantMark || (moved == 1) != c.wantMov {
t.Fatalf("asked %d, marked %d, moved %d; want asked %v, marked %v, moved %v", asked, marked, moved, c.wantAsked, c.wantMark, c.wantMov)
}
if c.published {
if fmt.Sprint(m.settled) != "[ack]" || judged != 0 {
t.Errorf("a version its reservation marks published settled %v, the registry read %d times; want acknowledged, none read", m.settled, judged)
}
return
}
if c.wantMov {
if _, ok := kv.vals[key]; ok || fmt.Sprint(m.settled) != "[term]" {
t.Errorf("the moved version's old item is written again, or its item settled %v, not terminated", m.settled)
}
return
}
got := decodeItem(t, kv.vals[key])
if got.Tries != map[bool]int{true: 1, false: 0}[c.wantAsked] || (c.wantAsked && !got.NextTry.After(now)) {
t.Errorf("tries %d, next try %s: want a try spent only when sent, the item written with its pause", got.Tries, got.NextTry)
}
if !c.wantAsked && fmt.Sprint(m.settled) != "[nak 30s]" {
t.Errorf("an item not sent was settled %v, want it handed back with the pause and no try spent", m.settled)
}
})
reserved = true
r, _ := json.Marshal(build.ReAsk{V: 1, Mode: build.ModePublish, Module: "m", Version: "0.1.2", Answer: "dropped by a person: why"})
kv.vals[versions.PublishItemKey("m", "0.1.2")], kv.revs[versions.PublishItemKey("m", "0.1.2")] = r, 1
before := len(sent)
m = queuedMsg(t, "m", "0.1.2")
p.take(ctx, m)
if !slices.Equal(m.settled, []string{"term"}) || len(sent) != before {
t.Errorf("a dropped publish: settled %v, sent %d more, want it terminated and not sent", m.settled, len(sent)-before)
}
}
@@ -46,10 +46,8 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi
return
}
if r.Mode == build.ModePublish {
// A version's publish item (design 47 G A-457a): its try waits for its pause, so it is made beside the watch.
if items != nil {
go items.Try(ctx, kv, e, r)
}
// A version's publish record (builder_publish_drop's, or one an earlier builder wrote): read by take, never tried on a timer
// (design 47 H2 H-A-606).
return
}
if r.Mode == build.ModeBuild {
@@ -8,6 +8,7 @@ import (
"github.com/nats-io/nats.go/jetstream"
"mesh-delivery-builder/internal/build"
"mesh-delivery-builder/internal/versions"
)
// The builder's retake of a key failed on a transport fault, on the node-engine seat's events (design 47 G §568, ADR 0673): the
@@ -87,3 +88,26 @@ func (d *decisions) heard(m jetstream.Msg) bool {
d.handle(m)
return true
}
// publishingAgain is the builder's publish again on ADR 0674 §2's events (design 47 H2 H-A-606): the wiring of versions.Againer to the
// events consumer.
type publishingAgain struct{ a *versions.Againer }
// heard hands a message of the events consumer to the publish again: one whose state cannot take it is left for the bus to give
// again (Nak); every message goes on to the other parts.
func (g *publishingAgain) heard(ctx context.Context, m jetstream.Msg, logf func(string, ...any)) (stop bool) {
meta, err := m.Metadata()
if err != nil {
return false
}
handled, err := g.a.Heard(ctx, m.Subject(), m.Data(), meta.Sequence.Stream)
if handled && err != nil {
logf("%v; heard again", err)
if nakErr := m.Nak(); nakErr != nil {
logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
}
givenUp(m, "its event", err, logf)
return true
}
return false
}
@@ -0,0 +1,179 @@
package versions
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-sdk/go/seatlist"
)
// DefaultRepublishMaxVersions is the setting republish-max-versions' default: the most versions one event queues (design 47 G §633).
const DefaultRepublishMaxVersions = 50
// Againer puts the publish of every reserved version again on the events of ADR 0674 §2 (design 47 H2 H-A-606, G §588): the node-engine
// seat's `running` of a module whose catalog entry claims a registry seat, and its `manifest-reads-changed` with `why` `returned` of a
// node a registry seat's holder runs on. Each message is acted on once, by its stream sequence (state `acted`, key `publish:<subject>`),
// and queues at most MaxVersions versions per event, newest first, at that holder only; what the work queue holds already is not queued
// again (ADR 0674 §3).
type Againer struct {
Republisher *Republisher
// Acted is the state acted, written with the lifetime of acted-days.
Acted ReserveStore
// Nodes answers each holder of a registry seat with its node, from the seat-holders view (seatlist.HolderNodesIn); nil answers none.
Nodes func(seat string) []seatlist.HolderNode
// MaxVersions is the setting republish-max-versions; zero is DefaultRepublishMaxVersions.
MaxVersions int
}
func (a *Againer) logf(f string, args ...any) { a.Republisher.logf(f, args...) }
func againKey(subject string) string { return ActedKey("publish:" + subject) }
// Heard takes one message of the node-engine seat's running or manifest-reads-changed in, at stream sequence seq, and acts on it once:
// handled is false for a subject that is neither. An error leaves it not acted on, so it is read again.
func (a *Againer) Heard(ctx context.Context, subject string, data []byte, seq uint64) (handled bool, err error) {
running := strings.HasPrefix(subject, strings.TrimSuffix(nodeengine.SubjectRunningAll, "*.*"))
changed := strings.HasPrefix(subject, "mesh.seat.node-engine.event."+nodeengine.EventManifestReadsChanged+".")
if !running && !changed {
return false, nil
}
key := againKey(subject)
raw, rev, found, err := a.Acted.Get(ctx, key)
if err != nil {
return true, fmt.Errorf("the acted sequence of %s cannot be read: %w", subject, err)
}
if found {
var done Acted
if json.Unmarshal(raw, &done) == nil && done.Sequence >= seq {
return true, nil
}
}
var holders func(seat string) []string
if running {
holders = a.runningHolders(ctx, data)
} else {
holders = a.returnedHolders(data)
}
if holders != nil {
if err := a.again(ctx, holders); err != nil {
return true, err
}
}
val, _ := json.Marshal(Acted{Sequence: seq})
if found {
_, err = a.Acted.Update(ctx, key, val, rev)
} else {
_, err = a.Acted.Create(ctx, key, val)
}
if err != nil && !errors.Is(err, ErrConflict) {
return true, fmt.Errorf("the acted sequence of %s cannot be kept: %w", subject, err)
}
return true, nil
}
// runningHolders is the holder function of a running: the module that is running holds each registry seat its catalog entry claims.
// nil when it holds none, or when no version waits (no call is made then).
func (a *Againer) runningHolders(ctx context.Context, data []byte) func(seat string) []string {
var ev nodeengine.Running
if err := json.Unmarshal(data, &ev); err != nil || ev.Module == "" {
a.logf("a running that does not read is not acted on: %v", err)
return nil
}
if ev.Stopped || ev.Fingerprint == "" {
return nil
}
if vs, err := a.unreleased(ctx); err != nil || len(vs) == 0 {
return nil
}
e, err := a.Republisher.Entry(ctx, ev.Fingerprint)
if err != nil {
a.logf("the catalog entry %s of %s cannot be read, so no publish is put again for it: %v", ev.Fingerprint, ev.Module, err)
return nil
}
var claimed []string
for _, s := range e.Serves {
if seat, _, _ := strings.Cut(s, "."); slices.Contains(RegistrySeats, seat) && !slices.Contains(claimed, seat) {
claimed = append(claimed, seat)
}
}
if len(claimed) == 0 {
return nil
}
return func(seat string) []string {
if slices.Contains(claimed, seat) {
return []string{ev.Module}
}
return nil
}
}
// returnedHolders is the holder function of a manifest-reads-changed with why returned: the holders of each registry seat that run on
// the node it names. nil for another why, or when none runs there.
func (a *Againer) returnedHolders(data []byte) func(seat string) []string {
var ev nodeengine.ManifestReadsChanged
if err := json.Unmarshal(data, &ev); err != nil || ev.Node == "" {
a.logf("a manifest-reads-changed that does not read is not acted on: %v", err)
return nil
}
if ev.Why != nodeengine.ManifestReadsChangedWhyReturned || a.Nodes == nil {
return nil
}
on := map[string]string{}
for _, seat := range RegistrySeats {
for _, h := range a.Nodes(seat) {
if h.Node == ev.Node {
on[seat] = h.Module
break
}
}
}
if len(on) == 0 {
return nil
}
return func(seat string) []string {
if m, ok := on[seat]; ok {
return []string{m}
}
return nil
}
}
// unreleased are the reserved versions whose build is done and with an artifact unpublished.
func (a *Againer) unreleased(ctx context.Context) ([]ReservedVersion, error) {
all, err := a.Republisher.Reserved.All(ctx)
if err != nil {
return nil, err
}
var out []ReservedVersion
for _, v := range all {
if !v.BuiltAt.IsZero() && len(v.Missing()) > 0 {
out = append(out, v)
}
}
return out, nil
}
// again queues the unreleased versions at the holders holdersOf names, at most MaxVersions of them.
func (a *Againer) again(ctx context.Context, holdersOf func(seat string) []string) error {
vs, err := a.unreleased(ctx)
if err != nil {
return fmt.Errorf("the reserved versions cannot be read: %w", err)
}
if len(vs) == 0 {
return nil
}
max := a.MaxVersions
if max <= 0 {
max = DefaultRepublishMaxVersions
}
queued, err := a.Republisher.queue(ctx, vs, holdersOf, max)
if len(queued) > 0 {
a.logf("publish again on an event: %d versions put on the work queue: %s", len(queued), strings.Join(queued, ", "))
}
return err
}
@@ -336,7 +336,7 @@ func (r *Republisher) end(ctx context.Context, module, version, why string) {
// the start.
const DefaultActedDays = 30
var actedMarkForms = []string{EscapeToken("retake:"), EscapeToken("retake-asked:"), EscapeToken("retake-ask:")}
var actedMarkForms = []string{EscapeToken("retake:"), EscapeToken("retake-asked:"), EscapeToken("retake-ask:"), EscapeToken("publish:")}
// ActedFormOf says whether key is a mark (known, with a lifetime) or the release record (known, with none), or of no form.
func ActedFormOf(key string) (mark, known bool) {
@@ -13,8 +13,10 @@ import (
"testing"
"time"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-sdk/go/seatlist"
)
// republishBed is a Republisher over memory states: reservations of module m (a bundle by the oci seat and a Go package by
@@ -553,10 +555,76 @@ func TestActedKeysHaveForms(t *testing.T) {
{ActedKey("retake-ask:ask-1"), true, true},
{ReleasedKey("m"), false, true},
{"junk", false, false},
{ActedKey("publish:x"), false, false},
{ActedKey("publish:mesh.seat.node-engine.event.running.ace.oci"), true, true},
} {
if mark, known := ActedFormOf(c.key); mark != c.mark || known != c.known {
t.Errorf("%q: mark %v, known %v, want %v, %v", c.key, mark, known, c.mark, c.known)
}
}
}
// TestAPublishIsPutAgainOnAHoldersEventsOnceBySequence: design 47 H2 H-A-606 (ADR 0674 §2, §3) — a registry holder's running and a
// returned of its node put each unreleased version again, at that holder, once per stream sequence, at most the bound per event, newest
// first; a module that holds no registry seat, a stopped running and another node's returned put nothing; a mark is kept for each.
func TestAPublishIsPutAgainOnAHoldersEventsOnceBySequence(t *testing.T) {
ctx := context.Background()
b := newRepublishBed(t)
b.window = true
b.reserve(t, "m1")
b.reserve(t, "m2")
b.reserve(t, "m3")
acted := &reserveMem{mem: newMem()}
a := &Againer{Republisher: b.Republisher, Acted: acted, MaxVersions: 2,
Nodes: func(seat string) []seatlist.HolderNode {
if seat == SeatArtifacts {
return []seatlist.HolderNode{{Module: "holder", Node: "ace"}}
}
return nil
}}
running := func(module, fp string, stopped bool) []byte {
raw, _ := json.Marshal(nodeengine.Running{Module: module, Node: "ace", Fingerprint: fp, Stopped: stopped})
return raw
}
sub := "mesh.seat.node-engine.event.running.ace."
puts := func() []string {
var out []string
for _, q := range b.puts {
out = append(out, q.Holder+" "+q.Module)
}
return out
}
if handled, err := a.Heard(ctx, "mesh.seat.node-engine.event.other.ace", nil, 1); handled || err != nil {
t.Fatalf("another subject: handled %v, %v", handled, err)
}
for _, c := range []struct {
name, subject string
data []byte
seq uint64
want []string
}{
{"a module that holds no registry seat", sub + "m1", running("m1", "src2:m1", false), 2, nil},
{"a stopped holder", sub + "holder", running("holder", "src2:holder", true), 3, nil},
{"the holder's running, two of three versions, newest first", sub + "holder", running("holder", "src2:holder", false), 4, []string{"holder m3", "holder m2"}},
{"the same sequence heard again", sub + "holder", running("holder", "src2:holder", false), 4, nil},
{"another node's return", "mesh.seat.node-engine.event.manifest-reads-changed.bee", mustJSON(nodeengine.ManifestReadsChanged{Node: "bee", Why: nodeengine.ManifestReadsChangedWhyReturned}), 5, nil},
{"a change that is no return", "mesh.seat.node-engine.event.manifest-reads-changed.ace", mustJSON(nodeengine.ManifestReadsChanged{Node: "ace", Why: "changed"}), 6, nil},
{"the holder's node returned", "mesh.seat.node-engine.event.manifest-reads-changed.ace", mustJSON(nodeengine.ManifestReadsChanged{Node: "ace", Why: nodeengine.ManifestReadsChangedWhyReturned}), 7, []string{"holder m3", "holder m2"}},
} {
b.puts, b.ids = nil, map[string]bool{}
handled, err := a.Heard(ctx, c.subject, c.data, c.seq)
if !handled || err != nil || !slices.Equal(puts(), c.want) {
t.Errorf("%s: handled %v, %v, put %v, want %v", c.name, handled, err, puts(), c.want)
}
}
if _, _, found, _ := acted.Get(ctx, againKey(sub+"holder")); !found {
t.Error("the running's mark is not kept in the state acted")
}
}
func mustJSON(v any) []byte {
raw, err := json.Marshal(v)
if err != nil {
panic(err)
}
return raw
}
@@ -198,7 +198,7 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
m.Streams[3].Duplicates != 24 || m.Streams[3].MaxDeliveries != 10 || m.Streams[3].MaxAgeDays != 7 || m.Streams[3].MaxMiB != 64 {
t.Errorf("streams = %+v, want waits with wait-held.** and wait-ended.**, 7 days, 16 MiB, the builds' stream (build.ended.**, 7 days, kept last per subject: design 47 G A-181) and the findings' stream", m.Streams)
}
if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 14 || m.Config["acted-days"].Default != float64(30) || m.Config["acted-days"].Maximum != 365 || // H-A-720 (1)
if c, ok := m.Config["toolchain-wait-minutes"]; !ok || c.Default != float64(60) || len(m.Config) != 13 || m.Config["acted-days"].Default != float64(30) || m.Config["acted-days"].Maximum != 365 || // H-A-720 (1)
// design 47 H2 §775, H-A-381 (2): the kept-call pace and the taken key's bound, read by the process
m.Config["kept-call-pace-first"].Default != "1s" || m.Config["kept-call-pace-max"].Default != "30s" || m.Config["ask-taken-bound"].Default != "10m" ||
@@ -208,8 +208,9 @@ func TestManifestDeclarations(t *testing.T) { // 1607/AC1
m.Config["revision-wait-minutes"].Default != float64(2) || m.Config["package-wait-minutes"].Default != float64(10) ||
// H-A-492: the record of a version's digests runs under the builder's own bound, a setting of 60 s by default
m.Config["record-bound-seconds"].Default != float64(60) ||
m.Config["publish-pause"].Default != float64(30) || m.Config["publish-pause-max"].Default != float64(30) || m.Config["publish-tries"].Default != float64(5) || m.Config["publish-tries"].Maximum != 10 {
t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), record-bound-seconds of 60 (H-A-492), the publish settings 30 s, 30 min and 5 tries, at most 10 (design 47 G §588, §633, A-457a; H2 H-A-446 (2))", m.Config)
m.Config["republish-max-versions"].Default != float64(50) || m.Config["publish-ack-minutes"].Default != float64(10) || // H-A-606: no pause, maximum or tries of a publish
m.Config["publish-pause"].Default != nil || m.Config["publish-pause-max"].Default != nil || m.Config["publish-tries"].Default != nil {
t.Errorf("config = %+v, want toolchain-wait-minutes of 60, revision-wait-minutes of 2 (H-A-156), package-wait-minutes of 10 (H-A-165), record-bound-seconds of 60 (H-A-492), republish-max-versions of 50 and publish-ack-minutes of 10, and no pause, maximum or tries of a publish (design 47 G §588, §633; H2 H-A-606, H-A-613 (3))", m.Config)
}
// Design 47 G §349: version.numbered is no longer said; old-form-closed on the family version, apart from the builds' ends.
if want := []string{"build.asked-again", "version.old-form-closed"}; !reflect.DeepEqual(m.Emits, want) {
@@ -268,7 +269,7 @@ func TestManifestProcess(t *testing.T) { // 1607/AC1
t.Errorf("health = %v, want kind unit alone", p["health"])
}
env, _ := p["env"].(map[string]any)
if len(env) != 10 || env["MESH_BUILDER_RECORD_BOUND_FILE"] != "${dir:state}/record-bound-seconds" || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_TRIES_FILE"] != "${dir:state}/publish-tries" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" {
if len(env) != 9 || env["MESH_BUILDER_RECORD_BOUND_FILE"] != "${dir:state}/record-bound-seconds" || env["MESH_BUILDER_REVISION_WAIT_FILE"] != "${dir:state}/revision-wait-minutes" || env["MESH_BUILDER_PACKAGE_WAIT_FILE"] != "${dir:state}/package-wait-minutes" || env["MESH_BUILDER_PUBLISH_ACK_FILE"] != "${dir:state}/publish-ack-minutes" || env["MESH_BUILDER_REPUBLISH_MAX_FILE"] != "${dir:state}/republish-max-versions" || env["MESH_BROKER_FILE"] != "${dir:state}/broker" || env["MESH_BUILDER_TOOLCHAIN_WAIT_FILE"] != "${dir:state}/toolchain-wait-minutes" {
t.Errorf("env = %v, want the broker file and the path of the toolchain wait's file, never the setting itself (design 47 G §672, A-71)", p["env"])
}
for k, v := range env {
+25 -42
View File
@@ -216,22 +216,6 @@
"default": "5m",
"runtime": true
},
"publish-pause": {
"type": "number",
"description": "seconds before a version's second publish try, doubled per try up to publish-pause-max (design 47 G A-457a).",
"minimum": 1,
"maximum": 3600,
"trusted": false,
"default": 30
},
"publish-pause-max": {
"type": "number",
"description": "minutes, the most a pause between a version's publish tries grows to (design 47 G A-457a).",
"minimum": 1,
"maximum": 1440,
"trusted": false,
"default": 30
},
"acted-days": {
"type": "number",
"description": "how many days a mark of an event or an ask acted on (state acted) is kept after its last write; the mark outlives every delivery of its event by far (design 47 H2 H-A-720).",
@@ -248,13 +232,21 @@
"trusted": false,
"default": 16
},
"publish-tries": {
"republish-max-versions": {
"type": "number",
"description": "how many times the builder tries a done build's publish before it ends loudly (log and condition) and leaves it readable in builder_publish_queue, at most 10, the work queue publishes' max-deliveries (design 47 G A-457a; H2 H-A-446 (2)).",
"description": "the most versions one event of a registry seat's holder (its running, or the return of its node) puts on the work queue publishes, newest first (design 47 G section 633, H2 H-A-606).",
"minimum": 1,
"maximum": 10,
"maximum": 10000,
"trusted": false,
"default": 5
"default": 50
},
"publish-ack-minutes": {
"type": "number",
"description": "minutes a sent publish waits for its published before the work queue gives it again, the publish bound (design 47 G section 369, H2 H-A-613 (3)).",
"minimum": 1,
"maximum": 1440,
"trusted": false,
"default": 10
}
},
"logs": [
@@ -324,22 +316,6 @@
"mode": "0600",
"content": "${config:record-bound-seconds}"
},
{
"id": "publish-pause",
"type": "file",
"path": "${dir:state}/publish-pause",
"owner": "mesh-delivery-builder",
"mode": "0600",
"content": "${config:publish-pause}"
},
{
"id": "publish-pause-max",
"type": "file",
"path": "${dir:state}/publish-pause-max",
"owner": "mesh-delivery-builder",
"mode": "0600",
"content": "${config:publish-pause-max}"
},
{
"id": "acted-days",
"type": "file",
@@ -357,12 +333,20 @@
"content": "${config:released-kept}"
},
{
"id": "publish-tries",
"id": "republish-max",
"type": "file",
"path": "${dir:state}/publish-tries",
"path": "${dir:state}/republish-max-versions",
"owner": "mesh-delivery-builder",
"mode": "0600",
"content": "${config:publish-tries}"
"content": "${config:republish-max-versions}"
},
{
"id": "publish-ack",
"type": "file",
"path": "${dir:state}/publish-ack-minutes",
"owner": "mesh-delivery-builder",
"mode": "0600",
"content": "${config:publish-ack-minutes}"
},
{
"id": "builder",
@@ -384,9 +368,8 @@
"MESH_BUILDER_REVISION_WAIT_FILE": "${dir:state}/revision-wait-minutes",
"MESH_BUILDER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes",
"MESH_BUILDER_RECORD_BOUND_FILE": "${dir:state}/record-bound-seconds",
"MESH_BUILDER_PUBLISH_PAUSE_FILE": "${dir:state}/publish-pause",
"MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE": "${dir:state}/publish-pause-max",
"MESH_BUILDER_PUBLISH_TRIES_FILE": "${dir:state}/publish-tries",
"MESH_BUILDER_REPUBLISH_MAX_FILE": "${dir:state}/republish-max-versions",
"MESH_BUILDER_PUBLISH_ACK_FILE": "${dir:state}/publish-ack-minutes",
"MESH_BUILDER_ACTED_DAYS_FILE": "${dir:state}/acted-days",
"MESH_BUILDER_RELEASED_KEPT_FILE": "${dir:state}/released-kept"
},