Files
mesh-catalog/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/switch.go
T

283 lines
9.8 KiB
Go

package main
// The switch to the delivery record (design 47 *The delivery record*: "The switch carries today's state in, once"): at
// the new gate's start, every group in flight and its merge as the old sections hold them become records, keyed by the
// milestone and the heads. It is safe to run twice: a group in flight whose record is there already leaves it as it is
// (Records.Open), and a group state the record holds already is not written again (Records.SetGroup), so delivering milestone
// G again after a revert makes no second record and asks nothing again. The old sections are read, never written (§613).
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
mdc "git.novox.be/novox/mesh-delivery/contracts/go/clients/meshdeliveryclient"
seat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// oldDelivery is a delivery as the old section `deliveries` kept it, as far as the switch reads it.
type oldDelivery struct {
ID string `json:"id"`
Repository string `json:"repository"`
Commit string `json:"commit"`
Number int `json:"number"`
Branch string `json:"branch"`
Group string `json:"group"`
State string `json:"state"`
InSource bool `json:"in_source"`
NewerHead string `json:"newer_head"`
ClosedUnmerged bool `json:"closed_unmerged"`
}
// milestone is the name a delivery's record is kept under: its group's, a lone pull request's branch, its id.
func (d oldDelivery) milestone() string {
switch {
case d.Group != "":
return d.Group
case d.Branch != "":
return d.Branch
}
return d.ID
}
// recordGroupOf is a merge, as the old section merges holds it, as the record's group state.
func recordGroupOf(m Merge, members []string) RecordGroup {
g := RecordGroup{Group: m.Group, Members: members, Ask: m.Ask, Approved: m.Approved}
for _, p := range m.Pulls {
g.Pulls = append(g.Pulls, RecordPull{Repository: p.Repository, Number: p.Number, Head: p.Head.Head, State: string(p.State),
Commit: p.Commit, Words: p.Words})
}
return g
}
// switchGroup is one group in flight as the switch finds it: its milestone, its heads and its members.
type switchGroup struct {
milestone string
heads map[string]string
members []string
}
// inFlight are the groups in flight in the old section deliveries: every milestone with a delivery not final, its live
// members' heads as `<repository>@<number>` to the full commit.
func (h *Holder) inFlight() ([]switchGroup, error) {
if h.Old == nil {
return nil, nil
}
keys, err := h.Old.Keys("deliveries")
if err != nil {
return nil, fmt.Errorf("the old section deliveries cannot be read for the switch: %w", err)
}
by := map[string]*switchGroup{}
for _, key := range keys {
raw, _, err := h.Old.Get("deliveries", key)
if err != nil {
return nil, fmt.Errorf("the old delivery %s cannot be read for the switch: %w", key, err)
}
var d oldDelivery
if raw == nil || json.Unmarshal(raw, &d) != nil || d.ID == "" {
continue // a mark an earlier owner kept, or no delivery
}
final := d.State == "merged" || d.State == "held" || d.State == "closed"
if final && !(d.State == "merged" && !d.InSource) || d.Number == 0 || d.NewerHead != "" || d.ClosedUnmerged {
continue
}
name := d.milestone()
g := by[name]
if g == nil {
g = &switchGroup{milestone: name, heads: map[string]string{}}
by[name] = g
}
g.heads[mdc.ApprovedKey(d.Repository, d.Number)] = d.Commit
g.members = append(g.members, d.ID)
}
out := make([]switchGroup, 0, len(by))
for _, g := range by {
sort.Strings(g.members)
out = append(out, *g)
}
sort.Slice(out, func(i, j int) bool { return out[i].milestone < out[j].milestone })
return out, nil
}
// Switch carries today's state into the records, once and safe to run again: each group in flight becomes a record at
// its heads, or at the heads its merge was approved at when `merges` holds one, with that merge as its group state.
// It answers how many records it opened and how many it found there.
func (h *Holder) Switch() (opened, found int, err error) {
if h.Records == nil {
return 0, 0, nil
}
groups, err := h.inFlight()
if err != nil {
return 0, 0, err
}
for _, g := range groups {
var merge *Merge
if h.Merges != nil {
if merge, err = h.Merges.Get(g.milestone); err != nil {
return opened, found, fmt.Errorf("the merge of %s cannot be read for the switch: %w", g.milestone, err)
}
}
heads := g.heads
if merge != nil && len(merge.Approved) > 0 {
heads = merge.Approved
}
r, made, err := h.Records.Open(g.milestone, heads, false)
if err != nil {
return opened, found, fmt.Errorf("the switch cannot open the record of %s: %w", g.milestone, err)
}
if made {
opened++
} else {
found++
}
if merge != nil {
if err := h.Records.SetGroup(r, recordGroupOf(*merge, g.members)); err != nil {
return opened, found, fmt.Errorf("the switch cannot carry the merge of %s: %w", g.milestone, err)
}
}
}
if err := h.carryOwed(); err != nil {
return opened, found, err
}
return opened, found, h.carryApprovals()
}
// oldMerge is a group's merge as the old state merges holds it, with its key and revision; nil when it holds none.
func (h *Holder) oldMerge(group string) (*Merge, uint64, error) {
if h.Old == nil {
return nil, 0, nil
}
key, err := mdc.MergesKey(group)
if err != nil {
return nil, 0, err
}
raw, rev, err := h.Old.Get(mdc.SwitchedMerges, key)
if err != nil || raw == nil {
return nil, 0, err
}
m, err := DecodeMerge(raw)
if err != nil {
return nil, 0, err
}
return &m, rev, nil
}
// carryOwed says every act the old state owed holds as owed, under its switched id (the state, the key and its revision:
// meshdeliveryclient.SwitchedActID), so the forge bridge performs what the old bridge did not and counts as performed what
// it did (design 47 G §169). No merge act is made from the old state merges (G §167, §542). Said at every switch, it is the same act each time. A key that cannot be read as an act is said
// as refused and skipped.
func (h *Holder) carryOwed() error {
if h.Old == nil || h.Owed == nil {
return nil
}
now := h.Now().UTC()
keys, err := h.Old.Keys(mdc.SwitchedOwed)
if err != nil {
return fmt.Errorf("the state owed cannot be read for the switch: %w", err)
}
for _, key := range keys {
raw, rev, err := h.Old.Get(mdc.SwitchedOwed, key)
if err != nil {
return fmt.Errorf("the owed act %s cannot be read for the switch: %w", key, err)
}
if raw == nil {
continue
}
repository, number, head, _, kerr := mdc.ParseOwedKey(key)
var o Owed
id, ierr := mdc.SwitchedActID(mdc.SwitchedOwed, key, rev)
if derr := json.Unmarshal(raw, &o); kerr != nil || derr != nil || ierr != nil {
h.Refuse(fmt.Errorf("the owed act %s is not carried by the switch: %v", key, errors.Join(kerr, derr, ierr)))
continue
}
said := seatOwedOf(o, id, repository, number, head, &now)
if r := h.recordHolding(repository, head); r != nil {
err = h.owe(r, said)
} else {
err = h.Owed.Say(said)
}
if err != nil {
return fmt.Errorf("the owed act %s cannot be said for the switch: %w", key, err)
}
}
return nil
}
// recordHolding is the open record that holds a pull request of the repository at the head, nil when none does.
func (h *Holder) recordHolding(repository, head string) *Record {
if h.Records == nil {
return nil
}
current, err := h.Records.Current()
if err != nil {
return nil
}
for _, r := range current {
for _, m := range membersOf(r) {
if strings.EqualFold(m.Repository, repository) && sameCommit(m.Head, head) {
return r
}
}
}
return nil
}
// approver is who an Approve carried across the switch was given by (design 47 §542).
const approver = "the operator"
// carryApprovals says, for each key of the old section merges the old bridge had not performed, `approval-carried` of each
// pull request it had not merged, once (design 47 §542, §592): the runner takes it as that pull request's `approval` step.
// The keys stay, read no more. Said at every switch, it is the same event under the same id each time, which the bus keeps once.
func (h *Holder) carryApprovals() error {
if h.Old == nil || h.SaySeat == nil {
return nil
}
names, err := h.Old.Keys(mdc.SwitchedMerges)
if err != nil {
return fmt.Errorf("the old section merges cannot be read for the switch: %w", err)
}
now := h.Now().UTC()
for _, key := range names {
raw, _, err := h.Old.Get(mdc.SwitchedMerges, key)
if err != nil {
return fmt.Errorf("the old merge %s cannot be read for the switch: %w", key, err)
}
if raw == nil {
continue
}
m, err := DecodeMerge(raw)
if err != nil {
h.Refuse(fmt.Errorf("the old merge %s is not carried by the switch: %v", key, err))
continue
}
for approved, head := range m.Approved {
repository, number, ok := parseApprovedKey(approved)
if !ok || mergedIn(m, repository, number) {
continue
}
body := seat.ApprovalCarriedEvent{Approver: approver, At: now, Commit: head, Pull: int64(number), Repository: repository}
subject := seat.SubjectApprovalCarried(keys.EscapeName(repository), fmt.Sprint(number))
if err := h.SaySeat(subject, body, fmt.Sprintf("approval-carried.%s.%d", repository, number)); err != nil {
return fmt.Errorf("the approval of %s#%d cannot be said carried: %w", repository, number, err)
}
if err := h.approvalOpen(repository, number, head); err != nil {
return fmt.Errorf("the finding of the approval of %s#%d cannot be written: %w", repository, number, err)
}
}
}
return nil
}
// mergedIn is whether a merge's pull request of that repository and number was merged.
func mergedIn(m Merge, repository string, number int) bool {
for _, p := range m.Pulls {
if strings.EqualFold(p.Repository, repository) && p.Number == number && p.State == mdc.MergeMerged {
return true
}
}
return false
}