gunk-dev/the-valley

project.go

source535d69c9a69emain's published tip history
15.0 KiB
1package export
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "slices"
9 "sort"
10 "strings"
11 "unicode"
12 "unicode/utf8"
13)
14
15// The schemas of the valley's own JSON the projection reads.
16const (
17 planSchema = "valley-plan/v1"
18 pendingSchema = "valley-pending/v1"
19 detailSchema = "valley-knot/v1"
20)
21
22// ErrInconsistent is the error for inputs read at different graph tips: a
23// knot's detail read after the plan saw a later graph. The publisher reads
24// the inputs again rather than publish them.
25var ErrInconsistent = errors.New("the inputs were read at different graph tips")
26
27// Inputs are what the projection reads: the valley's own JSON, as its
28// commands print it, and the publisher's configuration.
29type Inputs struct {
30 // Plan is `valley plan --all --json`.
31 Plan []byte
32 // Pending is `valley pending --all --json`.
33 Pending []byte
34 // Details are `valley knot show --project P <id> --json`, one for
35 // every knot of every public project.
36 Details [][]byte
37 // Identities are the publication identities of the projects to
38 // export, by project. A project it does not name is not exported.
39 Identities map[string]string
40 // SourceTips are each public project's main.
41 SourceTips map[string]string
42 // Principals is the display mapping principal names pass through.
43 Principals Principals
44 // Groups are the instance's groups, in identifier order, and
45 // Placements where the instance places each project on the web, by
46 // project, as the instance declares them. Every public project has a
47 // group. The export carries the groups of its public projects alone.
48 Groups []Group
49 Placements map[string]Placement
50}
51
52// Principals maps a principal's name to what an export shows in its place,
53// such as operator or agent. A name it does not map is shown as Unmapped.
54type Principals map[string]string
55
56// Unmapped is what an export shows for a principal the display mapping
57// does not name.
58const Unmapped = "contributor"
59
60// Show is what an export shows for the principal name: its mapping, or
61// Unmapped. The empty name, for a field that names nobody, stays empty.
62func (p Principals) Show(name string) string {
63 if name == "" {
64 return ""
65 }
66 if shown, ok := p[name]; ok {
67 return shown
68 }
69 return Unmapped
70}
71
72// check holds every shown name to 1 to 64 bytes of UTF-8 with no control
73// character.
74func (p Principals) check() error {
75 for name, shown := range p {
76 bad := len(shown) == 0 || len(shown) > 64 || !utf8.ValidString(shown) ||
77 containsControl(shown)
78 if bad {
79 return fmt.Errorf("the display mapping shows %q as %q; a shown name is 1 to 64 bytes of text, with no control character", name, shown)
80 }
81 }
82 return nil
83}
84
85func containsControl(s string) bool {
86 for _, r := range s {
87 if unicode.IsControl(r) {
88 return true
89 }
90 }
91 return false
92}
93
94// The valley's JSON, as far as the projection reads it. A field not named
95// here is never read, so a field the valley adds is not exported until the
96// projection names it.
97type (
98 planDoc struct {
99 Schema string `json:"schema"`
100 Now string `json:"now"`
101 Projects []planProject `json:"projects"`
102 }
103 planProject struct {
104 Project string `json:"project"`
105 Error *string `json:"error"`
106 Tip string `json:"tip"`
107 Roots []string `json:"roots"`
108 Knots []planKnot `json:"knots"`
109 InFlight []string `json:"in_flight"`
110 OpenResiduals []Residuals `json:"open_residuals"`
111 }
112 planKnot struct {
113 ID string `json:"id"`
114 Type string `json:"type"`
115 Status string `json:"status"`
116 Active bool `json:"active"`
117 Title string `json:"title"`
118 Created string `json:"created"`
119 CreatedBy string `json:"created_by"`
120 Source string `json:"source"`
121 Parent string `json:"parent"`
122 Owner string `json:"owner"`
123 BlockedBy []string `json:"blocked_by"`
124 Changes []string `json:"changes"`
125 Target string `json:"target"`
126 GraduatedInto string `json:"graduated_into"`
127 CommentCount int `json:"comment_count"`
128 State string `json:"state"`
129 Ready bool `json:"ready"`
130 WaitingOn []string `json:"waiting_on"`
131 ClearedByEnding []string `json:"cleared_by_ending"`
132 Dangling []string `json:"dangling"`
133 Unresolved []string `json:"unresolved"`
134 Children []string `json:"children"`
135 Blocks []string `json:"blocks"`
136 Progress *Progress `json:"progress"`
137 Claim *Claim `json:"claim"`
138 Edges []Edge `json:"edges"`
139 }
140 detailDoc struct {
141 Schema string `json:"schema"`
142 Project string `json:"project"`
143 Tip string `json:"tip"`
144 Knot struct {
145 ID string `json:"id"`
146 Body *string `json:"body"`
147 Comments []Comment `json:"comments"`
148 } `json:"knot"`
149 }
150 pendingDoc struct {
151 Schema string `json:"schema"`
152 Repos []pendingRepo `json:"repos"`
153 }
154 pendingRepo struct {
155 Repo string `json:"repo"`
156 Error *string `json:"error"`
157 Changes []pendingChange `json:"changes"`
158 }
159 pendingChange struct {
160 ChangeID string `json:"change_id"`
161 Handle string `json:"handle"`
162 Target string `json:"target"`
163 Owner string `json:"owner"`
164 State string `json:"state"`
165 Active int `json:"active"`
166 Versions []pendingVersion `json:"versions"`
167 Includes []string `json:"includes"`
168 Knots []KnotRef `json:"knots"`
169 }
170 pendingVersion struct {
171 N int `json:"n"`
172 Head string `json:"head"`
173 Title string `json:"title"`
174 Uploader string `json:"uploader"`
175 Landing string `json:"landing"`
176 Request *struct {
177 Commit string `json:"commit"`
178 } `json:"request"`
179 Outcome *Outcome `json:"outcome"`
180 }
181)
182
183// detailKey names a knot's detail: IDs are unique within a project, not
184// across projects.
185type detailKey struct{ project, id string }
186
187// Build projects the valley's JSON onto the public export. It is a pure
188// function of its inputs. It exports each project whose visibility is
189// public, and everything of it an anonymous reader may see: every knot,
190// with its body and comments, and the changes ready for approval, each
191// with its active version alone. It leaves out what is not the reader's:
192// the plan's operator sections, drafts, branches, older versions,
193// repository URLs, error text and the file each knot is stored in. A
194// reference to a project that is not exported keeps only the reference,
195// and every principal name passes through the display mapping.
196//
197// A public project whose plan or pending listing could not be read, whose
198// knot lacks its detail, or whose detail was read at another graph tip
199// fails the projection, so a partial export is never published. The last
200// of these is ErrInconsistent.
201func Build(in Inputs) (*Export, error) {
202 if err := in.Principals.check(); err != nil {
203 return nil, err
204 }
205 if err := CheckNames(context.Background(), in.Groups, Sorted(in.Placements)); err != nil {
206 return nil, err
207 }
208 var plan planDoc
209 if err := decodeInput("the plan", in.Plan, planSchema, &plan, &plan.Schema); err != nil {
210 return nil, err
211 }
212 var pending pendingDoc
213 if err := decodeInput("the pending listing", in.Pending, pendingSchema, &pending, &pending.Schema); err != nil {
214 return nil, err
215 }
216 details := map[detailKey]detailDoc{}
217 for _, raw := range in.Details {
218 var d detailDoc
219 if err := decodeInput("a knot's detail", raw, detailSchema, &d, &d.Schema); err != nil {
220 return nil, err
221 }
222 key := detailKey{d.Project, d.Knot.ID}
223 if _, twice := details[key]; twice {
224 return nil, fmt.Errorf("the details hold knot %s:%s twice", d.Project, d.Knot.ID)
225 }
226 details[key] = d
227 }
228
229 exported := map[string]bool{}
230 for name, id := range in.Identities {
231 if !ValidIdentity(id) {
232 return nil, fmt.Errorf("project %s has identity %q, which is not 32 lowercase hex digits", name, id)
233 }
234 exported[name] = true
235 }
236 planned := map[string]planProject{}
237 for _, p := range plan.Projects {
238 planned[p.Project] = p
239 }
240 repos := map[string]pendingRepo{}
241 for _, r := range pending.Repos {
242 repos[r.Repo] = r
243 }
244
245 e := &Export{Schema: Schema, Collected: plan.Now, Projects: []Project{}}
246 var names []string
247 for name := range exported {
248 names = append(names, name)
249 }
250 sort.Strings(names)
251 for _, name := range names {
252 p, ok := planned[name]
253 if !ok {
254 return nil, fmt.Errorf("exported project %s is not in the plan", name)
255 }
256 if p.Error != nil {
257 return nil, fmt.Errorf("the plan could not read exported project %s", name)
258 }
259 r, ok := repos[name]
260 if !ok {
261 return nil, fmt.Errorf("exported project %s is not in the pending listing", name)
262 }
263 if r.Error != nil {
264 return nil, fmt.Errorf("the pending listing could not read exported project %s", name)
265 }
266 out, err := project(name, p, r, details, exported, in)
267 if err != nil {
268 return nil, err
269 }
270 e.Projects = append(e.Projects, out)
271 }
272 groups, err := exportedGroups(e.Projects, in.Groups)
273 if err != nil {
274 return nil, err
275 }
276 e.Groups = groups
277 if err := e.Validate(); err != nil {
278 return nil, err
279 }
280 return e, nil
281}
282
283func project(name string, p planProject, r pendingRepo, details map[detailKey]detailDoc,
284 exported map[string]bool, in Inputs) (Project, error) {
285 shown := in.Principals.Show
286 tip := in.SourceTips[name]
287 if !ValidObjectID(tip) {
288 return Project{}, fmt.Errorf("exported project %s has no source tip, or one that is not an object ID", name)
289 }
290 placed := in.Placements[name]
291 if placed.Group == "" {
292 return Project{}, fmt.Errorf("exported project %s belongs to no group, so it has no web URL", name)
293 }
294 out := Project{
295 Name: name, Identity: in.Identities[name],
296 Group: placed.Group, WebName: placed.Name, FormerNames: placed.FormerNames, Aliases: placed.Aliases,
297 GraphTip: p.Tip, SourceTip: tip,
298 Roots: nonNil(p.Roots), Knots: []Knot{}, OpenResiduals: []Residuals{}, Changes: []Change{},
299 }
300 for _, g := range p.OpenResiduals {
301 out.OpenResiduals = append(out.OpenResiduals, Residuals{Parent: g.Parent, Bugs: nonNil(g.Bugs)})
302 }
303
304 // A reference to another project's knot is hidden when that project
305 // is not exported. Each list of the view a hidden reference appears in
306 // says something of the knot's status, so it is dropped from them all.
307 // A knot that waits on a hidden knot says only that it does.
308 hidden := func(ref string) bool {
309 project, _, qualified := strings.Cut(ref, ":")
310 return qualified && !exported[project]
311 }
312 var inProgress []string
313 inFlight := map[string]bool{}
314 for _, id := range p.InFlight {
315 inFlight[id] = true
316 }
317 for _, k := range p.Knots {
318 d, ok := details[detailKey{name, k.ID}]
319 if !ok {
320 return Project{}, fmt.Errorf("knot %s:%s has no detail", name, k.ID)
321 }
322 if d.Tip != p.Tip {
323 return Project{}, fmt.Errorf("%w: the plan read %s at %s, and knot %s at %s", ErrInconsistent, name, p.Tip, k.ID, d.Tip)
324 }
325 if d.Knot.Body == nil {
326 return Project{}, fmt.Errorf("the detail of knot %s:%s holds no body", name, k.ID)
327 }
328 if len(d.Knot.Comments) != k.CommentCount {
329 return Project{}, fmt.Errorf("%w: the plan counts %d comments on %s:%s, and its detail holds %d", ErrInconsistent, k.CommentCount, name, k.ID, len(d.Knot.Comments))
330 }
331 x := Knot{
332 ID: k.ID, Type: k.Type, Status: k.Status, Active: k.Active, Title: k.Title,
333 Created: k.Created, CreatedBy: shown(k.CreatedBy), Source: k.Source, Parent: k.Parent,
334 Owner: shown(k.Owner), BlockedBy: nonNil(k.BlockedBy), Changes: nonNil(k.Changes),
335 Target: k.Target, GraduatedInto: k.GraduatedInto,
336 State: k.State, Ready: k.Ready,
337 WaitingOn: drop(k.WaitingOn, hidden), WaitingOnHidden: slices.ContainsFunc(k.WaitingOn, hidden),
338 ClearedByEnding: drop(k.ClearedByEnding, hidden), Dangling: drop(k.Dangling, hidden),
339 Unresolved: drop(k.Unresolved, hidden), Children: nonNil(k.Children), Blocks: nonNil(k.Blocks),
340 Progress: k.Progress, Edges: []Edge{}, Body: *d.Knot.Body, Comments: []Comment{},
341 CommentCount: k.CommentCount,
342 }
343 if k.Claim != nil {
344 c := *k.Claim
345 c.By = shown(c.By)
346 x.Claim = &c
347 }
348 for _, edge := range k.Edges {
349 if !exported[edge.Project] {
350 edge = Edge{Field: edge.Field, Ref: edge.Ref, Project: edge.Project, ID: edge.ID, State: EdgeHidden}
351 }
352 x.Edges = append(x.Edges, edge)
353 }
354 for _, c := range d.Knot.Comments {
355 c.Author, c.EditedBy = shown(c.Author), shown(c.EditedBy)
356 x.Comments = append(x.Comments, c)
357 }
358 if k.Active && k.Status == "in-progress" && !inFlight[k.ID] {
359 inProgress = append(inProgress, k.ID)
360 }
361 out.Knots = append(out.Knots, x)
362 }
363 out.InFlight = append(nonNil(p.InFlight), inProgress...)
364
365 // includes may name a draft, which the export does not carry.
366 listed := map[string]bool{}
367 for _, c := range r.Changes {
368 listed[c.ChangeID] = true
369 }
370 for _, c := range r.Changes {
371 if c.State != "ready" {
372 return Project{}, fmt.Errorf("the pending listing holds change %s of %s, which is %s, among the ready changes", c.ChangeID, name, c.State)
373 }
374 var active *pendingVersion
375 for i := range c.Versions {
376 if c.Versions[i].N == c.Active {
377 active = &c.Versions[i]
378 }
379 }
380 if active == nil {
381 return Project{}, fmt.Errorf("change %s of %s holds no version %d, its active one", c.ChangeID, name, c.Active)
382 }
383 v := Version{N: active.N, Head: active.Head, Title: active.Title, Uploader: shown(active.Uploader),
384 Landing: active.Landing, Outcome: active.Outcome}
385 if active.Request != nil {
386 v.Request = &Request{Commit: active.Request.Commit}
387 }
388 out.Changes = append(out.Changes, Change{
389 ChangeID: c.ChangeID, Handle: c.Handle, Target: c.Target, Owner: shown(c.Owner), Version: v,
390 Includes: drop(c.Includes, func(id string) bool { return !listed[id] }), Knots: nonNilRefs(c.Knots),
391 })
392 }
393 return out, nil
394}
395
396// exportedGroups are the groups the exported projects belong to, in
397// identifier order, as groups are: a group no public project belongs to
398// is not exported.
399func exportedGroups(projects []Project, groups []Group) ([]Group, error) {
400 used := map[string]bool{}
401 for _, p := range projects {
402 used[p.Group] = true
403 }
404 var out []Group
405 for _, g := range groups {
406 if used[g.ID] {
407 out = append(out, g)
408 delete(used, g.ID)
409 }
410 }
411 for _, p := range projects {
412 if used[p.Group] {
413 return nil, fmt.Errorf("exported project %s belongs to the group %q, which is not declared", p.Name, p.Group)
414 }
415 }
416 return out, nil
417}
418
419// decodeInput reads one of the valley's documents and checks its schema.
420func decodeInput(what string, raw []byte, schema string, into any, got *string) error {
421 if err := json.Unmarshal(raw, into); err != nil {
422 return fmt.Errorf("%s: %w", what, err)
423 }
424 if *got != schema {
425 return fmt.Errorf("%s has schema %q, not %q", what, *got, schema)
426 }
427 return nil
428}
429
430// drop is list without the entries hidden reports, never nil.
431func drop(list []string, hidden func(string) bool) []string {
432 kept := []string{}
433 for _, s := range list {
434 if !hidden(s) {
435 kept = append(kept, s)
436 }
437 }
438 return kept
439}
440
441func nonNil(list []string) []string {
442 if list == nil {
443 return []string{}
444 }
445 return list
446}
447
448func nonNilRefs(list []KnotRef) []KnotRef {
449 if list == nil {
450 return []KnotRef{}
451 }
452 return list
453}