Files
mesh-catalog/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/sourcestart.go
T
2026-11-17 02:02:07 +01:00

249 lines
8.9 KiB
Go

package main
// A watched branch starts from the forge, as a clone does (design 47 G A-401, §430, §15): at its start and on each
// registration-changed of the seat mesh-catalog, the gate writes source.<branch> for every watched branch the registrations name,
// each registered repository at the head of that branch, asked of the seat git's verb branch, the group left empty, and says
// source-moved. A repository whose head cannot be read is left out and said. A head a key holds is never changed here (A-403): from
// then on only a take-in moves it (A-34).
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// registrationChangedEvent is the seat mesh-catalog's event, as the gate's manifest consumes it.
var registrationChangedEvent = declared(meshcatalog.EventRegistrationChanged)
// Registered is what the gate reads of the seat mesh-catalog: its registrations.
type Registered interface {
Registrations() (meshcatalog.RegistrationsAnswer, error)
}
// seatCatalog reads the seat mesh-catalog through the tool runner.
type seatCatalog struct{ ask asking }
func (s seatCatalog) Registrations() (meshcatalog.RegistrationsAnswer, error) {
var a meshcatalog.RegistrationsAnswer
raw, err := s.ask("seat:"+meshcatalog.Seat+"."+meshcatalog.VerbRegistrations, meshcatalog.RegistrationsInput{})
if err != nil {
return a, err
}
answer, said, ok := answerOf(raw)
if !ok {
return a, fmt.Errorf("registrations refused: %s", lastLine(said))
}
if err := json.Unmarshal(answer, &a); err != nil {
return a, fmt.Errorf("the answer of registrations is not readable: %w", err)
}
return a, nil
}
// Branch is the seat git's verb branch: a repository's branch head.
func (s seatGit) Branch(repository, branch string) (gitseat.BranchAnswer, error) {
var a gitseat.BranchAnswer
return a, s.call(gitseat.VerbBranch, gitseat.BranchInput{Repository: repository, Branch: branch}, &a)
}
// Contains is whether commit is the commit in or an ancestor of it.
func (s seatGit) Contains(repository, commit, in string) (bool, error) {
var a gitseat.ContainsAnswer
if err := s.call(gitseat.VerbContains, gitseat.ContainsInput{Repository: repository, Commit: commit, In: in}, &a); err != nil {
return false, err
}
if a.Error != "" {
return false, errors.New(a.Error)
}
return a.Contains, nil
}
// watchedRepositories are the repositories each watched branch is registered for, each once, sorted.
func watchedRepositories(regs []meshcatalog.Registration) map[string][]string {
seen := map[string]map[string]bool{}
for _, r := range regs {
if strings.TrimSpace(r.Origin) == "" {
continue
}
for _, b := range r.Branches {
if strings.TrimSpace(b) == "" {
continue
}
if seen[b] == nil {
seen[b] = map[string]bool{}
}
seen[b][r.Origin] = true
}
}
out := map[string][]string{}
for b, rs := range seen {
for r := range rs {
out[b] = append(out[b], r)
}
sort.Strings(out[b])
}
return out
}
// StartSources adds to the source key of every watched branch the registrations name each registered repository it lacks, and answers the
// branches it wrote. A registrations answer that cannot be read is an error (the event is offered again); a repository whose
// head cannot be read is said and left out.
func (h *Holder) StartSources() ([]string, error) {
started, _, err := h.startSources("")
return started, err
}
// startSleep waits between the start's passes; a test replaces it.
var startSleep = time.Sleep
// errRegistrationsUnread is a start pass's error when the registrations cannot be read.
var errRegistrationsUnread = errors.New("the registrations cannot be read")
// startSourcesAtStart runs the start pass once (A-442), and asks again, as switchToRecords does (2 s doubling to a minute),
// only while the registrations cannot be read: the seat mesh-catalog may serve after the gate does. A repository a pass
// leaves out is said by the pass, and added at the next registration change or by gate_source_start (A-401).
func startSourcesAtStart(h *Holder) {
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
started, leftOut, err := h.startSources("")
if err == nil || !errors.Is(err, errRegistrationsUnread) {
h.logf("[mesh-delivery] the sources started from the forge at the start: %v; left out %v; %v", started, leftOut, err)
return
}
h.logf("[mesh-delivery] the registrations cannot be read yet (%v); asking again in %s", err, wait)
startSleep(wait)
}
}
// startSources starts the branches no key holds, or only branch when it is named; it answers the branches written and the
// repositories left out as "<repository>@<branch>".
func (h *Holder) startSources(only string) (started, leftOut []string, err error) {
if h.Source == nil || h.Catalog == nil || h.Forge == nil {
return nil, nil, errors.New("this gate keeps no source, reads no registrations or reads no forge")
}
h.startMu.Lock()
defer h.startMu.Unlock()
regs, err := h.Catalog.Registrations()
if err != nil {
return nil, nil, fmt.Errorf("%w: %w", errRegistrationsUnread, err)
}
watched := watchedRepositories(regs.Registrations)
if only != "" {
if _, ok := watched[only]; !ok {
return nil, nil, fmt.Errorf("no registration names the branch %s", only)
}
}
names := make([]string, 0, len(watched))
for b := range watched {
if only == "" || b == only {
names = append(names, b)
}
}
sort.Strings(names)
var errs []error
for _, branch := range names {
held, _, err := h.Source.Read(branch)
if err != nil {
errs = append(errs, err)
continue
}
heads := map[string]string{}
for _, repository := range watched[branch] {
if held != nil {
if _, has := held.Heads[repository]; has {
continue // a head a key holds moves by a take-in alone (A-34)
}
}
a, err := h.Forge.Branch(repository, branch)
if err == nil && a.Error != "" {
err = errors.New(a.Error)
}
if err == nil && a.Head == "" {
err = errors.New("the forge named no head")
}
if err != nil {
leftOut = append(leftOut, repository+"@"+branch)
h.logf("[mesh-delivery] source.%s starts without %s: its head cannot be read (%v); it is added at the next registration change or by gate_source_start", branch, repository, err)
continue
}
heads[repository] = a.Head
}
if len(heads) == 0 {
continue
}
wrote := false
rev, err := h.Source.Set(branch, func(prev *Source) (Source, bool) {
next := Source{Heads: map[string]string{}}
if prev != nil {
next.Group = prev.Group
for r, c := range prev.Heads {
next.Heads[r] = c
}
}
wrote = false
for r, c := range heads {
if _, has := next.Heads[r]; !has { // a held head is never changed
next.Heads[r] = c
wrote = true
}
}
return next, wrote
})
if err != nil {
errs = append(errs, fmt.Errorf("source.%s cannot be started: %w", branch, err))
continue
}
if !wrote {
continue
}
started = append(started, branch)
if h.SaySeat == nil {
continue
}
at := h.Now().UTC()
if err := h.SaySeat(seat.SubjectSourceMoved(keys.EscapeName(branch)),
seat.SourceMovedEvent{Branch: branch, Revision: int64(rev), At: &at},
"source-moved."+keys.EscapeName(branch)+"."+strconv.FormatUint(rev, 10)); err != nil {
errs = append(errs, err)
}
}
return started, leftOut, errors.Join(errs...)
}
func (h *Holder) logf(format string, a ...any) {
if h.Logf != nil {
h.Logf(format, a...)
}
}
// SourceStart starts one watched branch by hand, after the hand-act log took it: the same as the start does.
func (h *Holder) SourceStart(branch, why, by string, acts handActs) (map[string]any, error) {
if strings.TrimSpace(branch) == "" || strings.TrimSpace(why) == "" {
return nil, errors.New("say the branch and why its source is started")
}
if h.Source == nil || h.Catalog == nil || h.Forge == nil {
return nil, errors.New("this gate keeps no source, reads no registrations or reads no forge")
}
if acts == nil {
return nil, errors.New("the hand-act log cannot be reached here, so nothing was started")
}
if _, err := acts.Record(meshhandactsclient.Request{What: "started the source of the branch " + branch,
Why: why, Cause: "gate_source_start", Verb: "source-start"}); err != nil {
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was started: %w", err)
}
started, leftOut, err := h.startSources(branch)
out := map[string]any{"branch": branch, "started": started, "left-out": leftOut, "by": by}
if err == nil && len(started) == 0 && len(leftOut) == 0 {
out["note"] = "the key names every registered repository already: only a take-in moves a head"
}
return out, err
}