Files
mesh-delivery/modules/mesh-delivery-builder/internal/versions/republish.go
T
jschoubben bda61ae64c H-A-290: the builder's publish queue sends live publishes first, in passes, never a withdrawn build
The tool runner's release waited forty minutes behind old versions: every start asked a publish again for every done
build, and each send relisted and reread the whole queue. A publish whose build ended in this run now goes before any
asked again at a start (the class kept on the key's value, a live key of a build before the start made a start key at
the start); a pass lists a holder's keys once and sends them four at a time; a withdrawn or taken-over build is dropped
with its publish item ended at enqueue, at the pass and at the start; a send that returns unsent says why, and every call
it makes honours its one bound; builder_publish_queue reads its states in pages and answers counts per holder and class,
the oldest and newest queue time, a list capped at fifty and one module's items with their class.

Builds: design 47 H H-A-290 (1)-(5), H-A-269, H-A-271, H-A-275
2026-11-21 18:59:58 +01:00

887 lines
34 KiB
Go

package versions
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
)
// **A reserved version of a done build is published by the builder until its release is written** (design 47 G §588, A-457a): the
// publish is an item of the builder's re-ask state, asked when the build ends and at its start, tried with a growing pause and
// ended loudly after its tries; each registry seat's holder, as the seat-holders view names it (A-416, A-416a), has one queue of
// versions, kept in the state `publish-queue`, sent one at a time. A send is the registry seat's `publish` with the digest and no
// parts (A-73): the holder takes the bytes from the artifact store by digest, and refuses what no store holds. Nothing waits on a
// node-engine `running` or `manifest-reads-changed` any more.
const (
// PublishQueueState is the builder's old state section of the queues, capped at PublishQueueMiB.
PublishQueueState = "publish-queue"
PublishQueueMiB = 4
// ActedState holds, one key per subject, the last stream sequence the builder acted on; capped at ActedMiB.
ActedState = "acted"
ActedMiB = 1
// PublishQueueTool is builder_publish_queue.
PublishQueueTool = "builder_publish_queue"
// QueueFull is what version-unreleased says of a version the queue's cap refused.
QueueFull = "queue full"
// NotStoredWords opens what a refused artifact is said as.
NotStoredWords = "not stored: "
// VerbPublish is the registry seats' verb a publish again sends, VerbVersions the one whose record says what a seat holds
// (H-A-272).
VerbPublish = "publish"
VerbVersions = "versions"
// PublishClassLive is the class of a publish whose build ended in this run, which a pipeline's build step waits on;
// PublishClassStart that of a publish asked again at a start, of a build that ended before it. A holder's queue sends every
// live one before any of the start, each class oldest first (design 47 H H-A-290 (1)).
PublishClassLive = "build-ended-this-run"
PublishClassStart = "asked-again-at-start"
// PublishSendsAtOnce bounds the sends of one holder's queue that run at once (H-A-290 (3)).
PublishSendsAtOnce = 4
// PublishQueueListCap caps the queued versions and the publish items builder_publish_queue lists (H-A-290 (5)).
PublishQueueListCap = 50
)
// RepublishTransfer is a publish again's transfer name, the builder's own (the registry part's publish: the caller names its
// transfer): safe as a transfer id, which holds none of "/", ".", " ", "*" or ">" (mesh-sdk's parts receiver refuses them), so a
// version's dots are dashes (design 47 G §588).
func RepublishTransfer(module, version, artifact string) string {
return strings.NewReplacer("/", "-", ".", "-", " ", "-", "*", "-", ">", "-", "@", "-").Replace("republish-" + module + "-" + version + "-" + artifact)
}
// RegistrySeats are the four registry seats a version is published to.
var RegistrySeats = []string{SeatImages, SeatArtifacts, SeatGoPackages, SeatNPM}
// SeatOfArtifact is the registry seat of one artifact of the catalog graph entry: from its package's ecosystem when the
// entry names one (go, npm, image), else from its kind (SeatOf).
func SeatOfArtifact(a meshcatalog.Artifact) (string, bool) {
if a.Package != nil {
switch a.Package.Ecosystem {
case "go":
return SeatGoPackages, true
case "npm":
return SeatNPM, true
case "image":
return SeatImages, true
}
}
seat, _, ok := SeatOf(a.Kind, a.Language)
return seat, ok
}
// QueuedPublish is the value of a publish-queue key `<holder module>.<module>.<version>` (each token escaped, §73): the
// artifacts of the version this holder publishes, by reference with their digests, when it was queued and whether its
// publish has begun.
type QueuedPublish struct {
V int `json:"v"`
Holder string `json:"holder"`
Module string `json:"module"`
Version string `json:"version"`
Artifacts map[string]string `json:"artifacts"`
Queued time.Time `json:"queued"`
Begun bool `json:"begun,omitempty"`
// Class is PublishClassLive or PublishClassStart (H-A-290 (1)); a value written before it had one is of the start.
Class string `json:"class,omitempty"`
}
// rank is the place of q's class in a holder's queue: the live first.
func (q QueuedPublish) rank() int {
if q.Class == PublishClassLive {
return 0
}
return 1
}
// sortQueued sorts a holder's queued versions in the order they are sent: the live class first, each class oldest first.
func sortQueued(qs []QueuedPublish) {
sort.SliceStable(qs, func(i, j int) bool {
if a, b := qs[i].rank(), qs[j].rank(); a != b {
return a < b
}
return qs[i].Queued.Before(qs[j].Queued)
})
}
// QueueFilter is the filter of every queued version: a queue key has three tokens, which AllFilter (two) never lists on the bus.
const QueueFilter = "*.*.*"
// QueueKey is the key of holder's queued version of module.
func QueueKey(holder, module, version string) string {
return EscapeToken(holder) + "." + EscapeToken(module) + "." + EscapeToken(version)
}
// Acted is the value of an acted key: the last stream sequence acted on for its subject.
type Acted struct {
Sequence uint64 `json:"sequence"`
}
// QueueStore is the queue's bucket: compare-and-set, deletion and how many bytes it holds, for its cap.
type QueueStore interface {
ReserveStore
Bytes(ctx context.Context) (uint64, error)
}
// Publish is one artifact's publish again: what the registry seat's publish takes, without parts.
type Publish struct {
Seat, Kind, Name, Version, Digest, Fingerprint, Commit, Transfer string
}
// Republisher publishes reserved versions again (design 47 G §588).
type Republisher struct {
Reserved *Reserver
Queue QueueStore
// Entry reads the catalog graph entry of a fingerprint (the seat mesh-catalog's verb entry).
Entry func(ctx context.Context, fingerprint string) (meshcatalog.CatalogEntry, error)
// Send sends one publish to a registry seat; an error is the holder's refusal or the call's fault, in its words.
Send func(ctx context.Context, p Publish) error
// Unreleased says version-unreleased about a version with the holder's words.
Unreleased func(ctx context.Context, v ReservedVersion, why string)
Now func() time.Time
Logf func(string, ...any)
// Go starts the sending of a holder's queue; nil starts a goroutine.
Go func(func())
// Holders answers a registry seat's holders: the catalog's SeatHolders, the part's one holder function that its FollowSeat
// of the assignments takes too, read from the builder's start (design 47 G A-416, A-416a); nil answers none.
Holders func(seat string) []string
// Started is when this run of the builder started: a version whose build ended at or after it is of the live class, one
// that ended before it of the start's (H-A-290 (1)). Zero makes every version live.
Started time.Time
// Ended ends the publish item of a version that never publishes, its reservation withdrawn or taken over (H-A-290 (2));
// nil ends none.
Ended func(ctx context.Context, module, version string)
mu sync.Mutex
busy map[string]bool
// lastQueued is the newest time a version was queued at: a clock that has not moved between two versions (a coarse clock,
// or a fixed one) must not make the queue's order the order of its keys, so each is queued after the last.
lastQueued time.Time
}
// queuedAt is the time a version is queued at: now, or a nanosecond after the last one queued when now is not after it, so the
// order the versions were queued in (newest reservation first) is the order they are sent in.
func (r *Republisher) queuedAt() time.Time {
r.mu.Lock()
defer r.mu.Unlock()
at := r.now()
if !at.After(r.lastQueued) {
at = r.lastQueued.Add(time.Nanosecond)
}
r.lastQueued = at
return at
}
func (r *Republisher) now() time.Time {
if r.Now != nil {
return r.Now().UTC()
}
return time.Now().UTC()
}
func (r *Republisher) logf(f string, a ...any) {
if r.Logf != nil {
r.Logf(f, a...)
}
}
// classOf is the class of v's publish: live when its build ended in this run (H-A-290 (1)).
func (r *Republisher) classOf(v ReservedVersion) string {
if v.BuiltAt.Before(r.Started) {
return PublishClassStart
}
return PublishClassLive
}
// NotStanding says why the reservation of a version, as Of answers it (found), never publishes: it stands no more at the
// version (released, dropped or taken over by a newer build), or it was withdrawn (design 47 H H-A-225, H-A-279). Empty when it
// stands (H-A-290 (2)).
func NotStanding(v ReservedVersion, found bool) string {
switch {
case !found:
return "its reservation stands no more at the version (released, dropped or taken over)"
case hasKey(v.Withdrawn, v.Version):
return "its reservation was withdrawn"
}
return ""
}
// drop deletes every queued key of module's version and ends its publish item: it never publishes (H-A-290 (2)), said with why.
func (r *Republisher) drop(ctx context.Context, module, version, why string) {
ctx = context.WithoutCancel(ctx)
keys, err := r.Queue.KeysOf(ctx, "*."+EscapeToken(module)+"."+EscapeToken(version))
if err != nil {
r.logf("publish again: %s %s never publishes (%s), and its queued keys cannot be listed: %v", module, version, why, err)
}
for _, k := range keys {
if err := r.Queue.Delete(ctx, k); err != nil {
r.logf("%s cannot be deleted from %s: %v", k, PublishQueueState, err)
}
}
r.end(ctx, module, version, why)
}
// end ends module's version's publish item, said with why.
func (r *Republisher) end(ctx context.Context, module, version, why string) {
r.logf("publish again: %s %s is not published: %s; its queued key is dropped and its publish item ended", module, version, why)
if r.Ended != nil {
r.Ended(context.WithoutCancel(ctx), module, version)
}
}
// ActedKey is the acted key of a subject.
func ActedKey(subject string) string { return EscapeToken(subject) }
// holdersFn answers a seat's holders from Holders.
func (r *Republisher) holdersFn(seat string) []string {
if r.Holders == nil {
return nil
}
return r.Holders(seat)
}
// view is a reserved version with the artifacts of it a holder would publish.
type view struct {
v ReservedVersion
arts map[string]meshcatalog.Artifact // reference -> its catalog artifact
}
// queue queues vs newest first, at most max of them (0 is no limit), each artifact to the first holder holdersOf names for
// its seat. It answers the versions queued, `<module> <version>`.
func (r *Republisher) queue(ctx context.Context, vs []ReservedVersion, holdersOf func(seat string) []string, max int) ([]string, error) {
sort.SliceStable(vs, func(i, j int) bool { return vs[i].At.After(vs[j].At) })
var queued []string
var errs []error
started := map[string]bool{}
// Every holder given a version is drained, whatever a later version met: a version queued and never drained waits forever.
defer func() {
for holder := range started {
r.drainLater(ctx, holder)
}
}()
for _, v := range vs {
if max > 0 && len(queued) >= max {
break
}
if why := NotStanding(v, true); why != "" {
r.drop(ctx, v.Module, v.Version, why)
continue
}
if v.Fingerprint == "" || v.BuiltAt.IsZero() {
r.logf("publish again: %s %s is not queued: it holds no fingerprint or its build has not ended with every digest", v.Module, v.Version)
continue
}
e, err := r.Entry(ctx, v.Fingerprint)
if err != nil {
// One version's unreadable entry leaves only that version unqueued; the others go on.
errs = append(errs, fmt.Errorf("the catalog entry %s of %s %s cannot be read: %w", v.Fingerprint, v.Module, v.Version, err))
continue
}
byHolder := map[string]map[string]string{}
for _, ref := range v.Missing() {
if _, no := v.Unstored[ref]; no {
r.logf("publish again: %s %s: %s is not queued: a holder refused it as not stored", v.Module, v.Version, ref)
continue
}
found := false
for _, a := range e.Artifacts {
seat, ok := SeatOfArtifact(a)
if a.Ref != ref || !ok {
continue
}
found = true
if hs := holdersOf(seat); len(hs) > 0 {
if byHolder[hs[0]] == nil {
byHolder[hs[0]] = map[string]string{}
}
byHolder[hs[0]][ref] = v.Artifacts[ref]
} else {
r.logf("publish again: %s %s: %s is not queued: the registry seat %s has no holder in the seat-holders view", v.Module, v.Version, ref, seat)
}
}
if !found {
r.logf("publish again: %s %s: %s is not queued: the catalog entry %s names no registry seat for it", v.Module, v.Version, ref, v.Fingerprint)
}
}
did := false
for holder, arts := range byHolder {
ok, err := r.enqueue(ctx, v, holder, arts)
if err != nil {
return queued, err
}
did = did || ok
started[holder] = true
}
if did {
queued = append(queued, v.Module+" "+v.Version)
}
}
return queued, errors.Join(errs...)
}
// enqueue puts one holder's artifacts of a version in its queue: not again when it is queued already, and not past the
// section's cap (said as queue full).
func (r *Republisher) enqueue(ctx context.Context, v ReservedVersion, holder string, arts map[string]string) (bool, error) {
key := QueueKey(holder, v.Module, v.Version)
if _, _, found, err := r.Queue.Get(ctx, key); err != nil {
return false, err
} else if found {
r.logf("publish again: %s %s is queued at %s already", v.Module, v.Version, holder)
return false, nil
}
raw, _ := json.Marshal(QueuedPublish{V: 1, Holder: holder, Module: v.Module, Version: v.Version, Artifacts: arts, Queued: r.queuedAt(), Class: r.classOf(v)})
used, err := r.Queue.Bytes(ctx)
if err != nil {
return false, fmt.Errorf("the size of the state %s cannot be read: %w", PublishQueueState, err)
}
if used+uint64(len(raw)) > PublishQueueMiB<<20 {
if r.Unreleased != nil {
r.Unreleased(ctx, v, QueueFull)
}
return false, nil
}
if _, err := r.Queue.Create(ctx, key, raw); err != nil {
if errors.Is(err, ErrConflict) {
return false, nil
}
return false, fmt.Errorf("%s cannot be queued: %w", key, err)
}
r.logf("publish again: %s %s is queued to publish at %s: %d artifacts, class %s", v.Module, v.Version, holder, len(arts), r.classOf(v))
return true, nil
}
// Republish is builder_publish_again: with module and version, that reserved version's missing artifacts; with module
// alone, each reserved version of it whose artifacts are not all published; with neither, every version the finding
// version-unreleased names. It queues as the events do (no limit but the cap), at the holders Holders answers (design 47 G
// A-416), and answers the versions it queued.
func (r *Republisher) Republish(ctx context.Context, module, version string) ([]string, error) {
var vs []ReservedVersion
if module == "" {
over, err := r.Reserved.Overdue(ctx, nil)
if err != nil {
return nil, err
}
for _, o := range over {
if v, ok, err := r.Reserved.Of(ctx, o.Module, o.Version); err == nil && ok {
vs = append(vs, v)
}
}
} else {
all, err := r.Reserved.All(ctx)
if err != nil {
return nil, err
}
for _, v := range all {
if v.Module == module && (version == "" || v.Version == version) && len(v.Missing()) > 0 {
vs = append(vs, v)
}
}
if len(vs) == 0 {
return nil, fmt.Errorf("%s holds no reserved version%s with an artifact unpublished", module, map[bool]string{true: " " + version, false: ""}[version != ""])
}
}
return r.queue(ctx, vs, r.holdersFn, 0)
}
// Queued is builder_publish_queue's answer, small at any size of the queue (design 47 H H-A-290 (5)): the queued versions'
// count per holder and class with the oldest and newest queue time, the first PublishQueueListCap of them in the order they are
// sent (each with its class), the acted keys with their sequences, and the publish items, counted and capped alike.
type Queued struct {
Total int `json:"total"`
Counts []QueueCount `json:"counts"`
// Queue are the first queued versions, per holder in the order they are sent (the live class first, each class oldest first);
// with a module named, only that module's.
Queue []QueuedPublish `json:"queue"`
// Listed says how many of Total the answer lists.
Listed int `json:"listed"`
Acted map[string]uint64 `json:"acted"`
// ItemCount is how many publish items stand; Items the first of them by their next try (design 47 G A-457a), each with its
// tries and its next try; an item that ended says why.
ItemCount int `json:"item-count"`
Items []PublishItem `json:"items"`
}
// QueueCount is how many versions one holder's queue holds of one class, and when the oldest and the newest were queued.
type QueueCount struct {
Holder string `json:"holder"`
Class string `json:"class"`
Count int `json:"count"`
Oldest time.Time `json:"oldest"`
Newest time.Time `json:"newest"`
}
// PublishItemKeyPrefix opens the key of a publish item in the builder's re-ask state.
const PublishItemKeyPrefix = "publish."
// PublishItem is the builder's own record of a version's publish (design 47 G A-457a): a value of the re-ask state, its tries and
// its next try. It is asked when the build ends and at the builder's start, rewritten with one more try and a longer pause after
// each, and deleted when the version is released; after the setting's number of tries it ends, saying so (Answer), and stays.
type PublishItem struct {
Module string `json:"module"`
Version string `json:"version"`
Tries int `json:"tries"`
NextTry time.Time `json:"next-try"`
Why string `json:"why,omitempty"`
Answer string `json:"answer,omitempty"`
Answered time.Time `json:"answered,omitzero"`
}
// PublishItemKey is the key of module's version's publish item.
func PublishItemKey(module, version string) string {
return PublishItemKeyPrefix + EscapeToken(module) + "." + EscapeToken(version)
}
// AnswerQueue is builder_publish_queue over the three states as the tools bundle reads them (H-A-290 (5)): each state read in
// bulk (Reader.All), the answer counted and capped at PublishQueueListCap whatever the queue holds; module (and version) narrow the
// listed queue to one module's (one version's), so an item's class can be read.
func AnswerQueue(queue, acted, reasks Reader, module, version string) (Queued, error) {
out := Queued{Counts: []QueueCount{}, Queue: []QueuedPublish{}, Acted: map[string]uint64{}, Items: []PublishItem{}}
vals, err := queue.values()
if err != nil {
return out, fmt.Errorf("the state %s cannot be read: %w", PublishQueueState, err)
}
counts := map[[2]string]*QueueCount{}
var listed []QueuedPublish
for _, raw := range vals {
var q QueuedPublish
if json.Unmarshal(raw, &q) != nil {
continue
}
if q.Class == "" {
q.Class = PublishClassStart
}
out.Total++
c := counts[[2]string{q.Holder, q.Class}]
if c == nil {
c = &QueueCount{Holder: q.Holder, Class: q.Class, Oldest: q.Queued, Newest: q.Queued}
counts[[2]string{q.Holder, q.Class}] = c
}
c.Count++
if q.Queued.Before(c.Oldest) {
c.Oldest = q.Queued
}
if q.Queued.After(c.Newest) {
c.Newest = q.Queued
}
if (module == "" || q.Module == module) && (version == "" || q.Version == version) {
listed = append(listed, q)
}
}
for _, c := range counts {
out.Counts = append(out.Counts, *c)
}
sort.Slice(out.Counts, func(i, j int) bool {
if out.Counts[i].Holder != out.Counts[j].Holder {
return out.Counts[i].Holder < out.Counts[j].Holder
}
return out.Counts[i].Class < out.Counts[j].Class
})
sort.SliceStable(listed, func(i, j int) bool { return listed[i].Holder < listed[j].Holder })
byHolder := map[string][]QueuedPublish{}
var holders []string
for _, q := range listed {
if byHolder[q.Holder] == nil {
holders = append(holders, q.Holder)
}
byHolder[q.Holder] = append(byHolder[q.Holder], q)
}
for _, h := range holders {
qs := byHolder[h]
sortQueued(qs)
for _, q := range qs {
if len(out.Queue) == PublishQueueListCap {
break
}
out.Queue = append(out.Queue, q)
}
}
out.Listed = len(out.Queue)
avals, err := acted.values()
if err != nil {
return out, fmt.Errorf("the state %s cannot be read: %w", ActedState, err)
}
for k, raw := range avals {
var a Acted
if json.Unmarshal(raw, &a) == nil {
out.Acted[k] = a.Sequence
}
}
rvals, err := reasks.values()
if err != nil {
return out, fmt.Errorf("the re-ask state cannot be read: %w", err)
}
for k, raw := range rvals {
if !strings.HasPrefix(k, PublishItemKeyPrefix) {
continue
}
var it PublishItem
if json.Unmarshal(raw, &it) == nil {
out.Items = append(out.Items, it)
}
}
out.ItemCount = len(out.Items)
sort.SliceStable(out.Items, func(i, j int) bool { return out.Items[i].NextTry.Before(out.Items[j].NextTry) })
if len(out.Items) > PublishQueueListCap {
out.Items = out.Items[:PublishQueueListCap]
}
return out, nil
}
// PublishQueueDescription is builder_publish_queue's description.
const PublishQueueDescription = "The versions the builder will publish again (its state " + PublishQueueState + ", design 47 G section 588, H H-A-290): " +
"how many each registry seat holder's queue holds per class (build-ended-this-run, sent first, or asked-again-at-start) with the oldest and newest " +
"queue time; the first 50 in the order they are sent, each with its class, its artifacts' digests, when it was queued and whether its publish has " +
"begun (module, and version, list only that module's, so one item's class can be read); the keys of the state " + ActedState + ", the last stream " +
"sequence the builder acted on for each subject; and the publish items (design 47 G A-457a), counted, the first 50 by next try, each version's " +
"tries and next try, and why one ended after its tries. Read-only."
// PublishAgainDescription is builder_publish_again's description.
const PublishAgainDescription = "Publish reserved versions again (design 47 G section 588), which builds nothing: with module and version, that reserved " +
"version's missing artifacts; with module alone, each reserved version of that module whose artifacts are not all published; with neither, every " +
"version the finding version-unreleased names, newest first. It queues them as the builder's publish items do, and answers at once " +
"with the versions it queued; each outcome is said as package-published, or left in version-unreleased with the holder's words. A hand act, " +
"recorded in the hand-act log."
// Resume takes up, at the builder's start, every queued version again, a begun one sent anew (§588): a version whose reservation
// was withdrawn or taken over is dropped with its publish item ended (H-A-290 (2)), and one of the live class whose build ended
// before this run is of the start's now (H-A-290 (1)). It reads the reservations once.
func (r *Republisher) Resume(ctx context.Context) error {
keys, err := r.Queue.KeysOf(ctx, QueueFilter)
if err != nil {
return fmt.Errorf("the state %s cannot be listed: %w", PublishQueueState, err)
}
all, err := r.Reserved.All(ctx)
if err != nil {
return fmt.Errorf("the queued publishes are not taken up: %w", err)
}
reserved := make(map[string]ReservedVersion, len(all))
for _, v := range all {
reserved[v.Module+" "+v.Version] = v
}
holders := map[string]bool{}
for _, k := range keys {
raw, rev, found, err := r.Queue.Get(ctx, k)
if err != nil || !found {
continue
}
var q QueuedPublish
if json.Unmarshal(raw, &q) != nil {
continue
}
v, ok := reserved[q.Module+" "+q.Version]
if why := NotStanding(v, ok); why != "" {
if err := r.Queue.Delete(ctx, k); err != nil {
r.logf("%s cannot be deleted from %s: %v", k, PublishQueueState, err)
}
r.end(ctx, q.Module, q.Version, why)
continue
}
if class := r.classOf(v); q.Class != class {
q.Class = class
if raw, err := json.Marshal(q); err == nil {
if _, err := r.Queue.Update(ctx, k, raw, rev); err != nil {
r.logf("%s keeps its class %s at the start: %v", k, q.Class, err)
}
}
}
holders[q.Holder] = true
}
for h := range holders {
r.drainLater(ctx, h)
}
return nil
}
func (r *Republisher) drainLater(ctx context.Context, holder string) {
r.mu.Lock()
if r.busy == nil {
r.busy = map[string]bool{}
}
if r.busy[holder] {
r.mu.Unlock()
return
}
r.busy[holder] = true
r.mu.Unlock()
run := func() {
defer func() { r.mu.Lock(); delete(r.busy, holder); r.mu.Unlock() }()
r.Drain(ctx, holder)
}
if r.Go != nil {
r.Go(run)
return
}
go run()
}
// Drain sends holder's queued versions in passes (H-A-290 (3)): a pass lists the holder's keys once, reads each once, and sends
// them in their order (the live class first, each class oldest first), PublishSendsAtOnce at a time; the keys are listed again
// only when the pass is spent. Each send is bounded by UnreleasedBound; a key is deleted when its outcome is said.
func (r *Republisher) Drain(ctx context.Context, holder string) {
for ctx.Err() == nil {
keys, err := r.Queue.KeysOf(ctx, EscapeToken(holder)+".*.*")
if err != nil {
r.logf("the queue of %s cannot be listed: %v", holder, err)
return
}
items := make([]QueuedPublish, 0, len(keys))
for _, k := range keys {
if raw, _, found, err := r.Queue.Get(ctx, k); err == nil && found {
var q QueuedPublish
if json.Unmarshal(raw, &q) == nil {
items = append(items, q)
}
}
}
if len(items) == 0 {
return
}
sortQueued(items)
sem := make(chan struct{}, PublishSendsAtOnce)
var wg sync.WaitGroup
for _, q := range items {
if ctx.Err() != nil {
break
}
sem <- struct{}{}
wg.Add(1)
go func() {
defer func() { <-sem; wg.Done() }()
r.send(ctx, q)
}()
}
wg.Wait()
}
}
// send publishes one queued version's artifacts and says the outcome, then deletes its key. Every call it makes honours the one
// bound it is given, UnreleasedBound (a context's bound, no timer, ADR 0437 §8), and a send that returns without sending says why
// (H-A-290 (4)).
func (r *Republisher) send(ctx context.Context, q QueuedPublish) {
key := QueueKey(q.Holder, q.Module, q.Version)
defer func() {
if err := r.Queue.Delete(context.WithoutCancel(ctx), key); err != nil {
r.logf("%s cannot be deleted from %s: %v", key, PublishQueueState, err)
}
}()
bound, cancel := context.WithTimeout(ctx, UnreleasedBound)
defer cancel()
if !q.Begun {
q.Begun = true
raw, _ := json.Marshal(q)
if _, rev, found, err := r.Queue.Get(bound, key); err == nil && found {
_, _ = r.Queue.Update(bound, key, raw, rev)
}
}
v, found, err := r.Reserved.Of(bound, q.Module, q.Version)
if err != nil {
r.logf("publish again: %s %s is not sent to %s: its reservation cannot be read: %v; its publish item asks it again", q.Module, q.Version, q.Holder, err)
return
}
if why := NotStanding(v, found); why != "" {
r.end(ctx, q.Module, q.Version, why)
return
}
e, err := r.Entry(bound, v.Fingerprint)
if err != nil {
r.say(ctx, v, fmt.Sprintf("the catalog entry %s cannot be read: %v", v.Fingerprint, err))
return
}
refs := make([]string, 0, len(q.Artifacts))
for ref := range q.Artifacts {
refs = append(refs, ref)
}
sort.Strings(refs)
for _, ref := range refs {
seat, name, kind, ok := publishTarget(e, q.Module, ref)
if !ok {
r.say(ctx, v, ref+": the catalog entry names no registry seat for it")
return
}
err := r.Send(bound, Publish{Seat: seat, Kind: kind, Name: name, Version: v.Version, Digest: q.Artifacts[ref], Fingerprint: v.Fingerprint,
Commit: v.Commit, Transfer: RepublishTransfer(q.Module, v.Version, strings.TrimPrefix(ref, q.Module+":"))})
if err == nil {
r.logf("publish again: %s %s: %s sent to %s as %s %s, digest %s; the package-published is said when the seat says published", q.Module, q.Version, ref, seat, name, v.Version, q.Artifacts[ref])
}
if err != nil {
r.logf("publish again: %s %s: %s refused by %s: %v", q.Module, q.Version, ref, seat, err)
words := err.Error()
if strings.Contains(words, strings.TrimSuffix(NotStoredWords, ": ")) {
if ok, merr := r.Reserved.MarkUnstored(bound, q.Module, q.Version, ref, words); merr != nil {
r.logf("%s %s: the unstored %s is not kept: %v", q.Module, q.Version, ref, merr)
} else if ok {
r.say(ctx, v, ref+" "+NotStoredWords+words)
}
continue
}
r.say(ctx, v, ref+": "+words)
}
}
}
// publishTarget is the registry seat, the name and the kind module's artifact ref is published as, from its catalog entry; ok is
// false when the entry names no registry seat for it.
func publishTarget(e meshcatalog.CatalogEntry, module, ref string) (seat, name, kind string, ok bool) {
var art *meshcatalog.Artifact
for i := range e.Artifacts {
if e.Artifacts[i].Ref == ref {
art = &e.Artifacts[i]
}
}
if art == nil {
return "", "", "", false
}
if seat, ok = SeatOfArtifact(*art); !ok {
return "", "", "", false
}
name = NameOf(module, strings.TrimPrefix(ref, module+":"))
if art.Package != nil && art.Package.Name != "" {
name = art.Package.Name
}
return seat, name, art.Kind, true
}
func (r *Republisher) say(ctx context.Context, v ReservedVersion, why string) {
r.logf("%s %s is not published again: %s", v.Module, v.Version, why)
if r.Unreleased != nil {
r.Unreleased(ctx, v, why)
}
}
// MarkUnstored records that a holder refused artifact of module's reserved version as not stored; it answers whether that
// was new (said once).
func (r *Reserver) MarkUnstored(ctx context.Context, module, version, artifact, words string) (bool, error) {
series, _, err := SplitVersion(version)
if err != nil {
return false, err
}
key := ReservedKey(module, series)
for {
cur, rev, found, err := r.get(ctx, key)
if err != nil || !found || cur.Version != version {
return false, err
}
if _, was := cur.Unstored[artifact]; was {
return false, nil
}
if cur.Unstored == nil {
cur.Unstored = map[string]string{}
}
cur.Unstored[artifact] = words
raw, _ := json.Marshal(cur)
if _, err := r.Store.Update(ctx, key, raw, rev); errors.Is(err, ErrConflict) {
continue
} else if err != nil {
return false, fmt.Errorf("%s cannot be written: %w", key, err)
}
return true, nil
}
}
// UnheardBound is how many messages the builder's durable on the events stream may hold pending and unacknowledged while a
// publish is asked again (design 47 H H-A-269 (2), H-A-272): at or above it a published of the version may still be unheard, so
// the try is skipped. A constant of the builder, no setting.
const UnheardBound = 100
// HeldVersion is one version a registry seat's verb versions answers of a name, with its digest.
type HeldVersion struct {
Version, Digest string
}
// HeldArtifact is an artifact of a reservation as a registry seat's record holds it at the reservation's version: its reference,
// the seat and the name it is published as, the version and the digest the seat holds.
type HeldArtifact struct {
Ref, Seat, Name, Version, Digest string
}
// Judged is what the registries' record says of a reserved version's missing artifacts (design 47 H H-A-272, H-A-274, H-A-275):
// those held at the version with the built digest (Held), those held at the version with another digest (Elsewhere), and, when an
// artifact is held at neither, the first one lacking (Lacks). All says every missing artifact is held with its built digest.
type Judged struct {
Held, Elsewhere []HeldArtifact
Lacks string
All bool
}
// Held judges v's missing artifacts against the registries' record (design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275): each
// artifact's registry seat and name as a publish again sends them, its record read through the seat's verb versions (versionsOf).
// A version with no missing artifact is All.
func (r *Republisher) Held(ctx context.Context, v ReservedVersion, versionsOf func(ctx context.Context, seat, name string) ([]HeldVersion, error)) (Judged, error) {
missing := v.Missing()
if len(missing) == 0 {
return Judged{All: true}, nil
}
e, err := r.Entry(ctx, v.Fingerprint)
if err != nil {
return Judged{}, fmt.Errorf("the catalog entry %s of %s %s cannot be read: %w", v.Fingerprint, v.Module, v.Version, err)
}
var out Judged
for _, ref := range missing {
seat, name, _, ok := publishTarget(e, v.Module, ref)
if !ok {
if out.Lacks == "" {
out.Lacks = ref + ": the catalog entry names no registry seat for it"
}
continue
}
held, err := versionsOf(ctx, seat, name)
if err != nil {
return Judged{}, fmt.Errorf("%s's versions of %s cannot be read: %w", seat, name, err)
}
at, found := HeldArtifact{}, false
for _, h := range held {
if strings.TrimPrefix(h.Version, "v") != v.Version {
continue
}
at, found = HeldArtifact{Ref: ref, Seat: seat, Name: name, Version: h.Version, Digest: h.Digest}, true
if h.Digest == v.Artifacts[ref] {
break
}
}
switch {
case !found:
if out.Lacks == "" {
out.Lacks = fmt.Sprintf("%s holds no %s %s", seat, name, v.Version)
}
case at.Digest == v.Artifacts[ref]:
out.Held = append(out.Held, at)
default:
out.Elsewhere = append(out.Elsewhere, at)
}
}
out.All = len(out.Held) == len(missing)
return out, nil
}
// HeldNumbers are the versions (MAJOR.MINOR.PATCH) a registry seat's record holds of any of module's artifacts refs, as the catalog
// entry of fingerprint names their seats and names (design 47 H H-A-275): a number one holds is never reserved. An artifact the
// entry names no registry seat for is read nowhere.
func (r *Republisher) HeldNumbers(ctx context.Context, module, fingerprint string, refs []string, versionsOf func(ctx context.Context, seat, name string) ([]HeldVersion, error)) ([]string, error) {
e, err := r.Entry(ctx, fingerprint)
if err != nil {
return nil, fmt.Errorf("the catalog entry %s of %s cannot be read: %w", fingerprint, module, err)
}
var out []string
for _, ref := range refs {
seat, name, _, ok := publishTarget(e, module, ref)
if !ok {
continue
}
held, err := versionsOf(ctx, seat, name)
if err != nil {
return out, fmt.Errorf("%s's versions of %s cannot be read: %w", seat, name, err)
}
for _, h := range held {
if v := strings.TrimPrefix(h.Version, "v"); v != "" && !slices.Contains(out, v) {
out = append(out, v)
}
}
}
return out, nil
}