gunk-dev/the-valley

report.go

sourcee5e09626b3e3main's published tip history
12.2 KiB
1package main
2
3import (
4 "crypto/sha256"
5 "encoding/base64"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12
13 "the-valley/change"
14 "the-valley/rebase"
15)
16
17// A family's reports are cut from one observation of it: everything the
18// attempt read and what came of it, in full. The journal keeps the
19// observation whole. When a report leaves part of it out, the state
20// directory also keeps it in a file of its own, which outlives the
21// journal (archive). Each recorded change in the family gets a report of
22// its own, in the format change/report.go defines, about every recorded
23// change in the family, bottom first. A plain branch is no report layer.
24//
25// A report holds what the format allows and no more: 64 layers, 100
26// conflict paths of at most 1024 bytes of UTF-8, 64 blocking requests
27// whose refs are at most 256 bytes, a refusal of at most 2048 bytes, no
28// control character in any of them, and 64 KiB of JSON in all. When the
29// observation holds more, the report is a fallback. It keeps what fits, in
30// the observation's order:
31//
32// - when the family has more than 64 recorded changes, only the change
33// the report is about and the layer that failed;
34// - each conflict path and each blocking request that fits on its own,
35// up to the format's count;
36// - its refusal, with each run of control characters made one space,
37// cut to fit.
38//
39// Its refusal then ends by saying what it leaves out, and naming the file
40// that keeps the whole observation in the restacker's state directory,
41// observations/<digest>.json, by the observation's digest. Two fallbacks
42// that show the same are told apart by that digest. If the report is still more
43// than 64 KiB, it sheds its conflict paths, then its blocking requests,
44// then every layer but the change's own and the failing one.
45
46// Observation is a family as one attempt saw it, in full.
47type Observation struct {
48 Action string `json:"action"` // the planner's: restack or hold
49 Result string `json:"result"` // what the reports say came of it: complete, conflict or blocked
50 Layers []ObservedLayer `json:"layers"` // every layer, plain branches included, bottom first
51 Requests []RequestPlan `json:"requests"` // every related request the planner considered
52 Reasons []string `json:"reasons"` // why the planner held it
53 Notes []string `json:"notes"` // what the planner noted
54 Failing string `json:"failing_layer"` // the change ID of the layer that failed; "" for none
55 Conflicts rawPaths `json:"conflict_paths_base64"` // every path that conflicted, as git gave it
56 Refusal string `json:"refusal"` // why nothing was published, in full; "" for nothing
57}
58
59// rawPaths are file names as git gives them: bytes that need not be
60// UTF-8. JSON holds only UTF-8, and json.Marshal would write each byte
61// that is not as U+FFFD, so a path such as a Latin-1 file name would not
62// read back as git gave it. The journal therefore keeps each path in
63// standard base64, which reads back byte for byte. A report takes only
64// the paths that are UTF-8 as they stand (bound).
65type rawPaths []string
66
67func (ps rawPaths) MarshalJSON() ([]byte, error) {
68 var encoded []string
69 if ps != nil {
70 encoded = make([]string, len(ps))
71 }
72 for i, p := range ps {
73 encoded[i] = base64.StdEncoding.EncodeToString([]byte(p))
74 }
75 return json.Marshal(encoded)
76}
77
78func (ps *rawPaths) UnmarshalJSON(data []byte) error {
79 var encoded []string
80 if err := json.Unmarshal(data, &encoded); err != nil {
81 return err
82 }
83 var out rawPaths
84 if encoded != nil {
85 out = make(rawPaths, len(encoded))
86 }
87 for i, e := range encoded {
88 p, err := base64.StdEncoding.Strict().DecodeString(e)
89 if err != nil {
90 return fmt.Errorf("conflict path %d is not in base64: %w", i, err)
91 }
92 out[i] = string(p)
93 }
94 *ps = out
95 return nil
96}
97
98// ObservedLayer is one layer as the attempt read it.
99type ObservedLayer struct {
100 Name string `json:"name"` // a change's handle, or a plain branch's name
101 ID string `json:"change_id"` // "" for a plain branch
102 Branch string `json:"branch"` // the branch a rebase pushes
103 BranchTip string `json:"branch_tip"` // that branch's tip on origin; "" when origin had none
104 Record string `json:"record"` // the record commit read; "" for a plain branch
105 Version int `json:"version"` // the active version; 0 for a plain branch
106 Head string `json:"head"` // the head rebased
107 State string `json:"state"`
108 Below string `json:"below"` // the layer it sits on, by name; "" for the bottom
109}
110
111// observe is the observation of a family the planner judged, before
112// anything is tried.
113func observe(f *rebase.Family, fp FamilyPlan) Observation {
114 o := Observation{Action: fp.Action, Requests: fp.Requests, Reasons: fp.Reasons, Notes: fp.Notes, Conflicts: []string{}}
115 for _, l := range f.Layers {
116 ol := ObservedLayer{Name: l.Name, ID: l.ID, Branch: l.Branch, BranchTip: l.Tip, Head: l.Head, State: string(l.State())}
117 if l.ID != "" {
118 ol.Record, ol.Version = l.Commit, l.Version
119 }
120 if l.Below != nil {
121 ol.Below = l.Below.Name
122 }
123 o.Layers = append(o.Layers, ol)
124 }
125 return o
126}
127
128// Digest is the first 16 hex digits of the SHA-256 of the observation as
129// the journal keeps it.
130func (o Observation) Digest() string {
131 data, _ := json.Marshal(o)
132 sum := sha256.Sum256(data)
133 return hex.EncodeToString(sum[:])[:16]
134}
135
136// fullReport is the report about the change id that the observation gives,
137// before it is cut to the format's bounds. published is what the attempt
138// published for each change, by ID.
139func fullReport(op, tip, id string, o Observation, published map[string]*change.RestackPublished) *change.RestackReport {
140 r := &change.RestackReport{
141 Schema: change.RestackSchema, ChangeID: id, Target: rebase.Target, TargetTip: change.HeadPrefix + tip,
142 Operation: op, Result: o.Result, Layers: []change.RestackLayer{}, Conflicts: o.Conflicts, Requests: []change.RestackRequest{},
143 }
144 for _, l := range o.Layers {
145 if l.ID == "" {
146 continue
147 }
148 rl := change.RestackLayer{
149 ChangeID: l.ID, Record: change.HeadPrefix + l.Record, Version: l.Version,
150 Head: change.HeadPrefix + l.Head, Branch: l.Branch, Published: published[l.ID],
151 }
152 if l.BranchTip != "" {
153 tip := change.HeadPrefix + l.BranchTip
154 rl.BranchTip = &tip
155 }
156 r.Layers = append(r.Layers, rl)
157 }
158 for _, q := range o.Requests {
159 if !q.Releases {
160 r.Requests = append(r.Requests, change.RestackRequest{Ref: rebase.RequestPrefix + q.Name, Tip: change.HeadPrefix + q.Head})
161 }
162 }
163 if o.Failing != "" {
164 failing := o.Failing
165 r.Failing = &failing
166 }
167 if o.Refusal != "" {
168 refusal := o.Refusal
169 r.Refusal = &refusal
170 }
171 return r
172}
173
174// bound cuts a report to the format's bounds, as the comment at the top of
175// this file describes, and says what it left out: nothing for a report
176// that fits whole. digest names the whole observation. It errs only when
177// not even the change's own layer fits.
178func bound(full *change.RestackReport, digest string) (*change.RestackReport, []string, error) {
179 r := *full
180 var omitted []string
181 if n := len(r.Layers); n > change.MaxRestackLayers {
182 r.Layers = essential(&r)
183 omitted = append(omitted, fmt.Sprintf("%d of the family's %d recorded changes", n-len(r.Layers), n))
184 }
185 paths, cut := []string{}, 0
186 for _, p := range r.Conflicts {
187 if len(paths) < change.MaxConflictPaths && fits(p, change.MaxConflictPath) {
188 paths = append(paths, p)
189 } else {
190 cut++
191 }
192 }
193 if cut > 0 {
194 omitted = append(omitted, fmt.Sprintf("%d of its %d conflict paths", cut, len(r.Conflicts)))
195 }
196 r.Conflicts = paths
197 requests, seen, cut := []change.RestackRequest{}, map[string]bool{}, 0
198 for _, q := range r.Requests {
199 name, ok := strings.CutPrefix(q.Ref, rebase.RequestPrefix)
200 if ok && len(requests) < change.MaxBlockingRequest && change.ValidBranch(name) && utf8.ValidString(name) &&
201 len(q.Ref) <= change.MaxRequestRef && !seen[q.Ref] && change.ValidHead(q.Tip) {
202 seen[q.Ref] = true
203 requests = append(requests, q)
204 } else {
205 cut++
206 }
207 }
208 if cut > 0 {
209 omitted = append(omitted, fmt.Sprintf("%d of its %d blocking requests", cut, len(r.Requests)))
210 }
211 r.Requests = requests
212 refusal := ""
213 if full.Refusal != nil {
214 refusal = plain(*full.Refusal)
215 }
216 if len(refusal) > change.MaxRefusal-noteRoom {
217 refusal = shorten(refusal, change.MaxRefusal-noteRoom)
218 omitted = append(omitted, "the end of its refusal")
219 }
220
221 for {
222 out := r
223 out.Refusal = refusalWith(refusal, omitted, digest)
224 data, err := change.EncodeRestackReport(&out)
225 if err != nil {
226 return nil, nil, err
227 }
228 if len(data) <= change.MaxReportBlob {
229 return &out, omitted, nil
230 }
231 switch {
232 case len(r.Conflicts) > 0:
233 omitted = append(omitted, fmt.Sprintf("the %d conflict paths left, to fit in %d bytes", len(r.Conflicts), change.MaxReportBlob))
234 r.Conflicts = []string{}
235 case len(r.Requests) > 0:
236 omitted = append(omitted, fmt.Sprintf("the %d blocking requests left, to fit in %d bytes", len(r.Requests), change.MaxReportBlob))
237 r.Requests = []change.RestackRequest{}
238 case len(essential(&r)) < len(r.Layers):
239 kept := essential(&r)
240 omitted = append(omitted, fmt.Sprintf("%d more of the family's recorded changes, to fit in %d bytes", len(r.Layers)-len(kept), change.MaxReportBlob))
241 r.Layers = kept
242 default:
243 return nil, nil, fmt.Errorf("no report of %s fits in %d bytes, even with its own layer alone", r.ChangeID, change.MaxReportBlob)
244 }
245 }
246}
247
248// essential is the layers a fallback report keeps: the change's own, and
249// the failing one, in the family's order.
250func essential(r *change.RestackReport) []change.RestackLayer {
251 var keep []change.RestackLayer
252 for _, l := range r.Layers {
253 if l.ChangeID == r.ChangeID || r.Failing != nil && l.ChangeID == *r.Failing {
254 keep = append(keep, l)
255 }
256 }
257 return keep
258}
259
260// fits reports whether s is 1 to max bytes of UTF-8 holding no control
261// character, as a report's conflict path must be.
262func fits(s string, max int) bool {
263 return len(s) >= 1 && len(s) <= max && utf8.ValidString(s) && !strings.ContainsFunc(s, unicode.IsControl)
264}
265
266// plain is s as UTF-8 with each run of control characters one space.
267func plain(s string) string {
268 var b strings.Builder
269 space := false
270 for _, r := range strings.ToValidUTF8(s, "�") {
271 if unicode.IsControl(r) {
272 if !space {
273 b.WriteByte(' ')
274 }
275 space = true
276 continue
277 }
278 space = false
279 b.WriteRune(r)
280 }
281 return strings.TrimSpace(b.String())
282}
283
284// refusalWith is a report's refusal: the observation's, and, when the
285// report leaves anything out, a note of what and of the digest of the
286// whole, cut to fit the format. nil is no refusal.
287func refusalWith(refusal string, omitted []string, digest string) *string {
288 if len(omitted) == 0 && refusal == "" {
289 return nil
290 }
291 note := ""
292 if len(omitted) > 0 {
293 note = fmt.Sprintf("This report leaves out %s; the restacker keeps the whole observation in its state directory, as %s/%s.json.",
294 strings.Join(omitted, ", "), observationsDir, digest)
295 }
296 if room := change.MaxRefusal - len(note) - len(" "); len(refusal) > room {
297 refusal = shorten(refusal, room)
298 }
299 out := strings.TrimSpace(refusal + " " + note)
300 return &out
301}
302
303// noteRoom is what a refusal leaves for the note of what a fallback leaves
304// out, which is never longer.
305const noteRoom = 600
306
307// shorten is s cut at a character boundary to at most n bytes, an ellipsis
308// marking the cut.
309func shorten(s string, n int) string {
310 if len(s) <= n {
311 return s
312 }
313 end := n - len("…")
314 for end > 0 && !utf8.RuneStart(s[end]) {
315 end--
316 }
317 return strings.TrimSpace(s[:max(end, 0)]) + "…"
318}
319
320// sameReport reports whether two reports say the same: the same
321// observations and the same result. The operation that wrote each is not
322// compared, since an unchanged observation written again by a later
323// attempt says nothing new.
324func sameReport(a, b *change.RestackReport) bool {
325 if a == nil || b == nil {
326 return a == b
327 }
328 return bytesOf(a) == bytesOf(b)
329}
330
331func bytesOf(r *change.RestackReport) string {
332 c := *r
333 c.Operation = ""
334 if c.Conflicts == nil {
335 c.Conflicts = []string{}
336 }
337 if c.Requests == nil {
338 c.Requests = []change.RestackRequest{}
339 }
340 if c.Layers == nil {
341 c.Layers = []change.RestackLayer{}
342 }
343 data, _ := json.Marshal(c)
344 return string(data)
345}