gunk-dev/the-valley

plan.go

sourcef703cb5df113main's published tip history
11.3 KiB
1package main
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "math"
8 "sort"
9 "strconv"
10 "strings"
11
12 "the-valley/change"
13 "the-valley/rebase"
14)
15
16// The restacker's own limits on a record it would change. Each is below
17// the push hook's (change/record.go), so a record the restacker leaves at
18// its limit still has room for its owner's own updates.
19const (
20 maxVersions = 900 // versions of one change
21 maxSeq = 99000 // record updates in a change's life
22 maxBytes = 48 << 10 // bytes of the record's encoded JSON
23)
24
25// What the planner would do with a family.
26const (
27 restack = "restack" // rebase every layer onto main's tip
28 hold = "hold" // a layer, a request or a limit stops it; Reasons say which
29 current = "current" // the family already descends from main's tip
30 leave = "leave" // no layer is a ready change, so the restacker has no business with it
31)
32
33// Plan is what one pass would do, from one snapshot of origin.
34type Plan struct {
35 Target string `json:"target"`
36 Tip string `json:"tip"`
37 Evidence string `json:"evidence"` // change.EvidenceFingerprint of every attestation ref
38 Cap int `json:"maxAutomaticVersions"` // the policy's cap as CapOf counts it
39 Operation string `json:"operation"` // the name the pass's writes are built under
40 Recovery *Recovery `json:"recovery"` // what recovery decided of the journal in the state directory; null for none
41 Families []FamilyPlan `json:"families"`
42
43 families []*rebase.Family // each family as captured, as Families
44}
45
46// FamilyPlan is one family of layers, bottom first, and what would become
47// of it.
48type FamilyPlan struct {
49 Layers []LayerPlan `json:"layers"`
50 Action string `json:"action"`
51 Reasons []string `json:"reasons"`
52 Notes []string `json:"notes"`
53 Requests []RequestPlan `json:"requests"`
54 Writes *Writes `json:"writes,omitempty"` // what a pass would push for it; absent for a family left alone or current
55}
56
57// LayerPlan is one layer as the snapshot shows it, with the capacity of
58// the record a restack would change; Capacity is nil for a plain branch.
59type LayerPlan struct {
60 Name string `json:"name"`
61 ID string `json:"id,omitempty"`
62 Branch string `json:"branch"`
63 Head string `json:"head"`
64 State string `json:"state"`
65 Below string `json:"below,omitempty"`
66 Capacity *Capacity `json:"capacity,omitempty"`
67}
68
69// Capacity is how close a record is to each limit, counted as it would be
70// once the restack added a version.
71type Capacity struct {
72 Uploads int `json:"uploads"` // versions the principal uploaded, the new one included
73 Cap int `json:"maxAutomaticVersions"`
74 Versions int `json:"versions"`
75 MaxVersions int `json:"maxVersions"`
76 Seq int `json:"seq"`
77 MaxSeq int `json:"maxSeq"`
78 Bytes int `json:"bytes"`
79 MaxBytes int `json:"maxBytes"`
80 Over []string `json:"over"` // each limit the record would pass, as a sentence
81}
82
83// RequestPlan is an integration request related to a family: how it is
84// related, and whether its outcome is current.
85type RequestPlan struct {
86 Name string `json:"name"`
87 Head string `json:"head"`
88 By []string `json:"by"` // name, head, range
89 Decision string `json:"decision,omitempty"`
90 Current bool `json:"current"`
91 Releases bool `json:"releases"`
92 Why string `json:"why"`
93}
94
95// Request is an integration request on origin: its name under
96// rebase.RequestPrefix and the head it asks to land.
97type Request struct {
98 Name, Head string
99}
100
101// Members is what a request may be related to a family by: the request
102// names of its changes, and its heads. A change's heads are every version
103// head it has ever had, not only the active one, so a request filed for an
104// older version under any name still holds the family. A plain branch's
105// head is its tip.
106type Members struct {
107 Names map[string]bool
108 Heads []string
109}
110
111// membersOf collects a family's request names and heads. A change's names
112// are c-<change ID> and the branch-derived name of every version it has
113// ever had, since a request filed under an earlier version's branch is
114// still about the change. A plain branch's name is its own.
115func membersOf(f *rebase.Family) Members {
116 m := Members{Names: map[string]bool{}}
117 seen := map[string]bool{}
118 head := func(h string) {
119 if h != "" && !seen[h] {
120 seen[h] = true
121 m.Heads = append(m.Heads, h)
122 }
123 }
124 for _, l := range f.Layers {
125 if l.ID == "" {
126 m.Names[rebase.ChangeName(l.Branch)] = true
127 head(l.Head)
128 continue
129 }
130 m.Names[change.RequestName(l.ID)] = true
131 head(l.Head)
132 for _, v := range l.Record.Versions {
133 if v.Branch != "" {
134 m.Names[rebase.ChangeName(v.Branch)] = true
135 }
136 head(rebase.HeadOf(v))
137 }
138 }
139 return m
140}
141
142// Incoming is the commits a request's head would bring to the target: the
143// commits it reaches that the target's tip does not. An error is a head
144// whose commits could not be read, as for an object that is missing or is
145// not a commit.
146type Incoming func(head string) (map[string]bool, error)
147
148// Ancestry answers whether a is an ancestor of b, or b itself. An error is
149// an answer that could not be had, as for an object that is missing or is
150// not a commit.
151type Ancestry func(a, b string) (bool, error)
152
153// Relate says how a request is related to a family: by name, by an exact
154// head, and by an incoming range that contains a head of the family. No
155// answer and a nil error is unrelated. An error is a relation that could
156// not be determined, which the caller must treat as related.
157func Relate(r Request, m Members, in Incoming) ([]string, error) {
158 var by []string
159 if m.Names[r.Name] {
160 by = append(by, "name")
161 }
162 for _, h := range m.Heads {
163 if h == r.Head {
164 by = append(by, "head")
165 break
166 }
167 }
168 if len(by) > 0 {
169 return by, nil
170 }
171 commits, err := in(r.Head)
172 if err != nil {
173 return nil, err
174 }
175 for _, h := range m.Heads {
176 if commits[h] {
177 return []string{"range"}, nil
178 }
179 }
180 return nil, nil
181}
182
183// Currency judges a related request's outcome: whether it lets the family
184// proceed, and why. An outcome is current when its head, its target tip
185// and its evidence fingerprint all equal what the planner sees. A current
186// stale releases the family, since the integrator will not land the
187// request at that head on that tip. So does a current reject, which the
188// caller notes. Anything else holds: no outcome, a record that does not
189// read, an outcome about another head, tip or evidence, which the
190// integrator will judge again, and a failure or a refusal.
191func Currency(o rebase.Outcome, found bool, head, tip, evidence string) (current, releases bool, why string) {
192 switch {
193 case !found:
194 return false, false, "no outcome yet, so the integrator has still to judge it"
195 case o.Decision == "unknown":
196 return false, false, "its outcome record does not read"
197 case o.Head != head:
198 return false, false, fmt.Sprintf("its outcome is about head %s, not %s", short(o.Head), short(head))
199 case o.Tip != tip:
200 return false, false, fmt.Sprintf("its outcome was judged on main at %s, not %s", short(o.Tip), short(tip))
201 case o.Evidence != evidence:
202 return false, false, fmt.Sprintf("its outcome was judged on evidence %s, not %s", o.Evidence, evidence)
203 }
204 switch o.Decision {
205 case "stale":
206 return true, true, "a current stale outcome: it cannot land as it stands"
207 case "reject":
208 return true, true, "a current reject outcome: the integrator rejected it"
209 case "failed":
210 return true, false, "the integrator failed on it at " + o.FailedAt
211 case "land", "voided-withdrawn":
212 return true, false, fmt.Sprintf("a current %s outcome with the request still filed", o.Decision)
213 }
214 return true, false, "the integrator refused it (" + o.Decision + ")"
215}
216
217// CapOf reads the policy's cap on automatic versions as the count the
218// planner compares uploads against. The schema admits any whole number of
219// at least 1, with no upper bound. A cap larger than an int holds is no
220// practical cap: it is counted as the largest int, and no record holds
221// that many versions. An absent cap, or one that is not a whole number of
222// at least 1, is refused, since the schema admits neither.
223func CapOf(stated json.Number) (int, error) {
224 if stated == "" {
225 return 0, errors.New("the composed policy states no restack.maxAutomaticVersions")
226 }
227 n, err := strconv.Atoi(string(stated))
228 switch {
229 case errors.Is(err, strconv.ErrRange) && n > 0:
230 return math.MaxInt, nil
231 case err != nil || n < 1:
232 return 0, fmt.Errorf("the composed policy's restack.maxAutomaticVersions is %s, not a whole number of at least 1", stated)
233 }
234 return n, nil
235}
236
237// CapacityOf counts a record against every limit as it would stand with
238// one more version uploaded by principal. size is the length of that
239// record's encoded JSON.
240func CapacityOf(r *change.Record, principal string, cap, size int) *Capacity {
241 c := &Capacity{
242 Uploads: 1, Cap: cap,
243 Versions: len(r.Versions) + 1, MaxVersions: maxVersions,
244 Seq: r.Seq + 1, MaxSeq: maxSeq,
245 Bytes: size, MaxBytes: maxBytes,
246 }
247 for _, v := range r.Versions {
248 if v.Uploader == principal {
249 c.Uploads++
250 }
251 }
252 if c.Uploads > c.Cap {
253 c.Over = append(c.Over, fmt.Sprintf("%s would have %d versions uploaded by %s, over the cap of %d", r.ChangeID, c.Uploads, principal, c.Cap))
254 }
255 if c.Versions > c.MaxVersions {
256 c.Over = append(c.Over, fmt.Sprintf("%s would have %d versions, over the %d the restacker allows", r.ChangeID, c.Versions, c.MaxVersions))
257 }
258 if c.Seq > c.MaxSeq {
259 c.Over = append(c.Over, fmt.Sprintf("%s's record would be at update %d, over the %d the restacker allows", r.ChangeID, c.Seq, c.MaxSeq))
260 }
261 if c.Bytes > c.MaxBytes {
262 c.Over = append(c.Over, fmt.Sprintf("%s's record would be %d bytes, over the %d the restacker allows", r.ChangeID, c.Bytes, c.MaxBytes))
263 }
264 return c
265}
266
267// nextSize is the length of a record's encoded JSON once a restack adds a
268// version. The rebased head is not known yet, so the version names a
269// stand-in of the same length; the title, the branch and the uploader are
270// the ones the restack would write. 0 is a record the engine would not
271// extend at all, which the version and update limits already hold.
272func nextSize(handle string, r *change.Record, principal string) int {
273 active := r.ActiveVersion()
274 stand := change.HeadPrefix + strings.Repeat("0", len(rebase.HeadOf(active)))
275 next, err := rebase.NextRecord(handle, r, change.Version{Head: stand, Title: active.Title, Branch: active.Branch, Uploader: principal})
276 if err != nil {
277 return 0
278 }
279 b, err := change.Encode(next)
280 if err != nil {
281 return 0
282 }
283 return len(b)
284}
285
286func short(oid string) string {
287 if len(oid) > 12 {
288 return oid[:12]
289 }
290 return oid
291}
292
293// stateLine names a layer's state for a reason, as a change is ready,
294// approved or submitted.
295func stateLine(l *rebase.Layer) string {
296 switch s := l.State(); s {
297 case rebase.Plain:
298 return l.Name + " is a plain branch, which no record is on"
299 case rebase.Draft:
300 return l.Name + " is a draft"
301 case rebase.Withdrawn:
302 return l.Name + " is withdrawn"
303 case rebase.Uncertain:
304 return l.Name + " may have landed already, with no evidence either way"
305 default:
306 return fmt.Sprintf("%s is %s", l.Name, s)
307 }
308}
309
310// sortRequests puts requests in name order, so a plan reads the same each
311// time.
312func sortRequests(rs []RequestPlan) {
313 sort.Slice(rs, func(i, j int) bool { return rs[i].Name < rs[j].Name })
314}