gunk-dev/the-valley

report.go

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