gunk-dev/the-valley

report.go

source2886163c0514main's published tip history
16.3 KiB
1package change
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "regexp"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12)
13
14// A restack report is what the host restacker observed when it tried to
15// rebase a ready change onto its target: the inputs it read, what came of
16// the attempt, and what it published. It lives at
17// refs/the-valley/restack/<target>/<change ID>. The ref points at a report
18// commit whose tree holds one file, report.json, in the schema
19// valley-restack-report/v1:
20//
21// {
22// "schema": "valley-restack-report/v1",
23// "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
24// "target": "main",
25// "target_tip": "git-sha1:<40 hex>",
26// "operation": "20261017T203500Z-1",
27// "result": "conflict",
28// "layers": [
29// {"change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
30// "record": "git-sha1:<40 hex>", "version": 2, "branch": "topic",
31// "head": "git-sha1:<40 hex>", "published": null}
32// ],
33// "failing_layer": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
34// "conflict_paths": ["src/main.go"],
35// "blocking_requests": [],
36// "refusal": null
37// }
38//
39// The layers are the changes the attempt rebased together, bottom first,
40// each as it was read: its record commit, its active version, and that
41// version's branch and head. published is null for a layer whose branch
42// the attempt did not move. Otherwise it is the head the branch was moved
43// to, and the version and record commit that recorded it, both null when
44// no version was added.
45//
46// Each report commit has the report it replaces as its one parent, and the
47// first has none, so the ref holds the change's whole history of reports.
48//
49// A report is an observation and grants nothing. It is not evidence that
50// a version's content is unchanged or approved. A reader decides whether
51// it still applies by comparing what it observed with what origin holds
52// now.
53//
54// It is read as strictly as a record: valid UTF-8, no key twice, no field
55// the schema does not have, every field of exactly its type, and every
56// string and list within its bound. The push hook reads a pushed report
57// with ParseRestackReport, and valley status reads it back the same way.
58
59// RestackSchema names the report format.
60const RestackSchema = "valley-restack-report/v1"
61
62// RestackPrefix opens every restack report's ref.
63const RestackPrefix = "refs/the-valley/restack/"
64
65// RestackRef is the ref a change's restack report lives at.
66func RestackRef(target, id string) string {
67 return RestackPrefix + target + "/" + id
68}
69
70// ParseRestackRef splits a report's ref into its target and change ID. It
71// reports false for a ref that is not refs/the-valley/restack/<target>/<ID>
72// with a branch name as the target and a change ID as the ID.
73func ParseRestackRef(ref string) (target, id string, ok bool) {
74 rest, found := strings.CutPrefix(ref, RestackPrefix)
75 if !found {
76 return "", "", false
77 }
78 slash := strings.LastIndexByte(rest, '/')
79 if slash < 0 {
80 return "", "", false
81 }
82 target, id = rest[:slash], rest[slash+1:]
83 if !ValidBranch(target) || !ValidID(id) {
84 return "", "", false
85 }
86 return target, id, true
87}
88
89// What came of an attempt. A conflict and a block move no branch and add
90// no version. partial is an attempt that moved its branches and did not
91// add every version; complete is one that did both. superseded is an
92// attempt given up because its inputs moved while it ran.
93const (
94 RestackConflict = "conflict"
95 RestackBlocked = "blocked"
96 RestackPartial = "partial"
97 RestackComplete = "complete"
98 RestackSuperseded = "superseded"
99)
100
101// The bounds a report is held to.
102const (
103 MaxRestackLayers = 64 // layers in one report
104 MaxConflictPaths = 100 // conflict paths in one report
105 MaxConflictPath = 1024 // bytes in one conflict path
106 MaxBlockingRequest = 64 // blocking requests in one report
107 MaxRequestRef = 256 // bytes in one blocking request's ref
108 MaxRefusal = 2048 // bytes in a refusal
109 MaxOperation = 64 // bytes in an operation identifier
110)
111
112// The bounds on the objects that hold reports, which every reader holds a
113// report to before it reads anything past them. A report commit names a
114// tree, at most one parent, an author, a committer and a short message,
115// and its tree names one file.
116const (
117 MaxReportCommit = 4 << 10 // bytes in a report commit
118 MaxReportTree = 1 << 10 // bytes in its tree
119 MaxReportBlob = 64 << 10 // bytes in its report.json
120 MaxReportUpdates = 64 // report updates in one push
121)
122
123// RestackReport is one restack report.
124type RestackReport struct {
125 Schema string `json:"schema"`
126 ChangeID string `json:"change_id"`
127 Target string `json:"target"`
128 TargetTip string `json:"target_tip"`
129 Operation string `json:"operation"`
130 Result string `json:"result"`
131 Layers []RestackLayer `json:"layers"`
132 Failing *string `json:"failing_layer"`
133 Conflicts []string `json:"conflict_paths"`
134 Requests []string `json:"blocking_requests"`
135 Refusal *string `json:"refusal"`
136}
137
138// RestackLayer is one change an attempt rebased, as the attempt read it,
139// and what it published for it.
140type RestackLayer struct {
141 ChangeID string `json:"change_id"`
142 Record string `json:"record"`
143 Version int `json:"version"`
144 Branch string `json:"branch"`
145 Head string `json:"head"`
146 Published *RestackPublished `json:"published"`
147}
148
149// RestackPublished is what an attempt published for a layer: the head its
150// branch was moved to, and the version and record commit that recorded
151// that head, both nil when no version was added.
152type RestackPublished struct {
153 Head string `json:"head"`
154 Version *int `json:"version"`
155 Record *string `json:"record"`
156}
157
158// Layer is the layer of the change given, if the report has one.
159func (r *RestackReport) Layer(id string) (RestackLayer, bool) {
160 for _, l := range r.Layers {
161 if l.ChangeID == id {
162 return l, true
163 }
164 }
165 return RestackLayer{}, false
166}
167
168// ParseRestackReport reads report.json, strictly.
169func ParseRestackReport(data []byte) (*RestackReport, error) {
170 v, err := readJSON(data)
171 if err != nil {
172 return nil, err
173 }
174 o, err := fieldsOf(v, "the report", "schema", "change_id", "target", "target_tip", "operation", "result",
175 "layers", "failing_layer", "conflict_paths", "blocking_requests", "refusal")
176 if err != nil {
177 return nil, err
178 }
179 r := &RestackReport{}
180 for _, f := range []struct {
181 name string
182 into *string
183 }{
184 {"schema", &r.Schema}, {"change_id", &r.ChangeID}, {"target", &r.Target},
185 {"target_tip", &r.TargetTip}, {"operation", &r.Operation}, {"result", &r.Result},
186 } {
187 if *f.into, err = stringOf(o[f.name], f.name); err != nil {
188 return nil, err
189 }
190 }
191 if r.Failing, err = optionalString(o["failing_layer"], "failing_layer"); err != nil {
192 return nil, err
193 }
194 if r.Refusal, err = optionalString(o["refusal"], "refusal"); err != nil {
195 return nil, err
196 }
197 if r.Conflicts, err = stringsOf(o["conflict_paths"], "conflict_paths", MaxConflictPaths); err != nil {
198 return nil, err
199 }
200 if r.Requests, err = stringsOf(o["blocking_requests"], "blocking_requests", MaxBlockingRequest); err != nil {
201 return nil, err
202 }
203 layers := o["layers"]
204 if layers.kind != kindArray {
205 return nil, fmt.Errorf("its layers is %s, where an array is expected", layers.kind)
206 }
207 if len(layers.items) > MaxRestackLayers {
208 return nil, fmt.Errorf("it holds %d layers, more than the %d a report may", len(layers.items), MaxRestackLayers)
209 }
210 r.Layers = []RestackLayer{}
211 for i, item := range layers.items {
212 l, err := layerOf(item, fmt.Sprintf("layers[%d]", i))
213 if err != nil {
214 return nil, err
215 }
216 r.Layers = append(r.Layers, l)
217 }
218 if err := r.Check(); err != nil {
219 return nil, err
220 }
221 return r, nil
222}
223
224func layerOf(v *value, where string) (RestackLayer, error) {
225 o, err := fieldsOf(v, where, "change_id", "record", "version", "branch", "head", "published")
226 if err != nil {
227 return RestackLayer{}, err
228 }
229 var l RestackLayer
230 for _, f := range []struct {
231 name string
232 into *string
233 }{
234 {"change_id", &l.ChangeID}, {"record", &l.Record}, {"branch", &l.Branch}, {"head", &l.Head},
235 } {
236 if *f.into, err = stringOf(o[f.name], where+"."+f.name); err != nil {
237 return RestackLayer{}, err
238 }
239 }
240 if l.Version, err = integerOf(o["version"], where+".version", MaxVersions); err != nil {
241 return RestackLayer{}, err
242 }
243 p := o["published"]
244 if isNull(p) {
245 return l, nil
246 }
247 where += ".published"
248 po, err := fieldsOf(p, where, "head", "version", "record")
249 if err != nil {
250 return RestackLayer{}, err
251 }
252 l.Published = &RestackPublished{}
253 if l.Published.Head, err = stringOf(po["head"], where+".head"); err != nil {
254 return RestackLayer{}, err
255 }
256 if !isNull(po["version"]) {
257 n, err := integerOf(po["version"], where+".version", MaxVersions)
258 if err != nil {
259 return RestackLayer{}, err
260 }
261 l.Published.Version = &n
262 }
263 if l.Published.Record, err = optionalString(po["record"], where+".record"); err != nil {
264 return RestackLayer{}, err
265 }
266 return l, nil
267}
268
269// Check holds a report to everything the schema says beyond the types of
270// its fields: the formats and bounds of its strings and lists, and what
271// its fields say about one another. The change it is about is one of its
272// layers, no layer appears twice, and a failing layer is one of them. A
273// conflict names its failing layer. A conflict or a block published
274// nothing, and a complete attempt published a version for every layer. A
275// published version comes with the record commit that holds it.
276func (r *RestackReport) Check() error {
277 switch {
278 case r.Schema != RestackSchema:
279 return fmt.Errorf("its schema is %q, where %q is expected", r.Schema, RestackSchema)
280 case !ValidID(r.ChangeID):
281 return fmt.Errorf("its change_id %q is not a change ID: 32 letters from k to z", r.ChangeID)
282 case !ValidBranch(r.Target) || !utf8.ValidString(r.Target):
283 return fmt.Errorf("its target %q is not a branch name in UTF-8", r.Target)
284 case !ValidHead(r.TargetTip):
285 return fmt.Errorf("its target_tip %q is not %s and 40 lowercase hex digits", r.TargetTip, HeadPrefix)
286 case !operationName.MatchString(r.Operation) || len(r.Operation) > MaxOperation:
287 return fmt.Errorf("its operation %q is not 1 to %d letters, digits, dots, colons, dashes and underscores", r.Operation, MaxOperation)
288 case !validResult(r.Result):
289 return fmt.Errorf("its result is %q, where %q, %q, %q, %q or %q is expected", r.Result,
290 RestackConflict, RestackBlocked, RestackPartial, RestackComplete, RestackSuperseded)
291 case len(r.Layers) == 0:
292 return errors.New("it holds no layer, and a report holds at least the change it is about")
293 case len(r.Layers) > MaxRestackLayers:
294 return fmt.Errorf("it holds %d layers, more than the %d a report may", len(r.Layers), MaxRestackLayers)
295 case len(r.Conflicts) > MaxConflictPaths:
296 return fmt.Errorf("it holds %d conflict paths, more than the %d a report may", len(r.Conflicts), MaxConflictPaths)
297 case len(r.Requests) > MaxBlockingRequest:
298 return fmt.Errorf("it holds %d blocking requests, more than the %d a report may", len(r.Requests), MaxBlockingRequest)
299 case r.Refusal != nil && !validText(*r.Refusal, MaxRefusal):
300 return fmt.Errorf("its refusal is not 1 to %d bytes free of control characters", MaxRefusal)
301 }
302 seen := map[string]bool{}
303 published, versioned := false, true
304 for i, l := range r.Layers {
305 where := fmt.Sprintf("layers[%d]", i)
306 switch {
307 case !ValidID(l.ChangeID):
308 return fmt.Errorf("its %s.change_id %q is not a change ID: 32 letters from k to z", where, l.ChangeID)
309 case seen[l.ChangeID]:
310 return fmt.Errorf("its %s names the change %s, which an earlier layer names", where, l.ChangeID)
311 case !ValidHead(l.Record):
312 return fmt.Errorf("its %s.record %q is not %s and 40 lowercase hex digits", where, l.Record, HeadPrefix)
313 case l.Version < 1 || l.Version > MaxVersions:
314 return fmt.Errorf("its %s.version is %d, outside 1 to %d", where, l.Version, MaxVersions)
315 case !ValidBranch(l.Branch) || !utf8.ValidString(l.Branch):
316 return fmt.Errorf("its %s.branch %q is not a branch name in UTF-8", where, l.Branch)
317 case !ValidHead(l.Head):
318 return fmt.Errorf("its %s.head %q is not %s and 40 lowercase hex digits", where, l.Head, HeadPrefix)
319 }
320 seen[l.ChangeID] = true
321 p := l.Published
322 if p == nil {
323 versioned = false
324 continue
325 }
326 published = true
327 switch {
328 case !ValidHead(p.Head):
329 return fmt.Errorf("its %s.published.head %q is not %s and 40 lowercase hex digits", where, p.Head, HeadPrefix)
330 case (p.Version == nil) != (p.Record == nil):
331 return fmt.Errorf("its %s.published names a version without its record, or a record without its version, and the two come together", where)
332 case p.Version != nil && (*p.Version < 1 || *p.Version > MaxVersions):
333 return fmt.Errorf("its %s.published.version is %d, outside 1 to %d", where, *p.Version, MaxVersions)
334 case p.Record != nil && !ValidHead(*p.Record):
335 return fmt.Errorf("its %s.published.record %q is not %s and 40 lowercase hex digits", where, *p.Record, HeadPrefix)
336 }
337 versioned = versioned && p.Version != nil
338 }
339 for i, path := range r.Conflicts {
340 if !validText(path, MaxConflictPath) {
341 return fmt.Errorf("its conflict_paths[%d] is not 1 to %d bytes free of control characters", i, MaxConflictPath)
342 }
343 }
344 for i, ref := range r.Requests {
345 name, ok := strings.CutPrefix(ref, "refs/the-valley/integration-requests/"+r.Target+"/")
346 if !ok || !ValidBranch(name) || len(ref) > MaxRequestRef {
347 return fmt.Errorf("its blocking_requests[%d] %q is not an integration request's ref on %s of at most %d bytes", i, ref, r.Target, MaxRequestRef)
348 }
349 }
350 switch {
351 case !seen[r.ChangeID]:
352 return fmt.Errorf("no layer names the change %s, and a report is about one of its layers", r.ChangeID)
353 case r.Failing != nil && !seen[*r.Failing]:
354 return fmt.Errorf("its failing_layer %q is none of its layers", *r.Failing)
355 case r.Result == RestackConflict && r.Failing == nil:
356 return errors.New("its result is conflict, and a conflict names its failing_layer")
357 case (r.Result == RestackConflict || r.Result == RestackBlocked) && published:
358 return fmt.Errorf("its result is %s, and a %s publishes nothing", r.Result, r.Result)
359 case r.Result == RestackComplete && !versioned:
360 return errors.New("its result is complete, and a complete attempt published a version for every layer")
361 }
362 return nil
363}
364
365// EncodeRestackReport writes a report as report.json. It refuses a report
366// ParseRestackReport would refuse, so what it writes always reads back as
367// the same report.
368func EncodeRestackReport(r *RestackReport) ([]byte, error) {
369 if err := r.Check(); err != nil {
370 return nil, fmt.Errorf("the report cannot be written: %w", err)
371 }
372 out := *r
373 if out.Conflicts == nil {
374 out.Conflicts = []string{}
375 }
376 if out.Requests == nil {
377 out.Requests = []string{}
378 }
379 var buf bytes.Buffer
380 enc := json.NewEncoder(&buf)
381 enc.SetEscapeHTML(false)
382 enc.SetIndent("", " ")
383 if err := enc.Encode(&out); err != nil {
384 return nil, err
385 }
386 return buf.Bytes(), nil
387}
388
389// operationName is the shape of an operation identifier: a local name the
390// restacker gives one attempt.
391var operationName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]*$`)
392
393func validResult(s string) bool {
394 switch s {
395 case RestackConflict, RestackBlocked, RestackPartial, RestackComplete, RestackSuperseded:
396 return true
397 }
398 return false
399}
400
401// validText reports whether s is 1 to max bytes of UTF-8 holding no
402// control character.
403func validText(s string, max int) bool {
404 if len(s) < 1 || len(s) > max || !utf8.ValidString(s) {
405 return false
406 }
407 return !strings.ContainsFunc(s, unicode.IsControl)
408}
409
410func isNull(v *value) bool {
411 return v.kind == kindLiteral && v.text == "null"
412}
413
414// optionalString reads a string or null.
415func optionalString(v *value, name string) (*string, error) {
416 if isNull(v) {
417 return nil, nil
418 }
419 s, err := stringOf(v, name)
420 if err != nil {
421 return nil, fmt.Errorf("its %s is %s, where a string or null is expected", name, v.kind)
422 }
423 return &s, nil
424}
425
426// stringsOf reads an array of at most max strings.
427func stringsOf(v *value, name string, max int) ([]string, error) {
428 if v.kind != kindArray {
429 return nil, fmt.Errorf("its %s is %s, where an array is expected", name, v.kind)
430 }
431 if len(v.items) > max {
432 return nil, fmt.Errorf("its %s holds %d entries, more than the %d it may", name, len(v.items), max)
433 }
434 list := []string{}
435 for i, item := range v.items {
436 s, err := stringOf(item, fmt.Sprintf("%s[%d]", name, i))
437 if err != nil {
438 return nil, err
439 }
440 list = append(list, s)
441 }
442 return list, nil
443}