gunk-dev/the-valley

graph.go

source23915b53d9camain's published tip history
18.0 KiB
1package knot
2
3import (
4 "errors"
5 "fmt"
6 "path"
7 "slices"
8 "sort"
9 "strings"
10 "time"
11)
12
13// Entry is one entry of a graph's tree, as a listing of it gives it: a
14// path from the root, the entry's mode as git writes it, and its object.
15// A listing holds every tree below the root as well as every file.
16type Entry struct {
17 Path string
18 Mode string
19 OID string
20}
21
22// Index is a graph's layout: where each knot and each comment is, read
23// from the tree's listing alone. A knot's ID and type are in its path, so
24// an index resolves an edge without reading any knot.
25type Index struct {
26 // Knots maps each knot's ID to its file.
27 Knots map[string]File
28 // Comments maps each comment's path to its file.
29 Comments map[string]File
30 // Files maps every file's path to its object.
31 Files map[string]string
32 // knotAt maps each knot's path to its ID.
33 knotAt map[string]string
34}
35
36// File is one knot's or comment's file in a graph.
37type File struct {
38 Path string
39 OID string
40 // For a knot: its ID, type and slug. For a comment: the ID of the
41 // knot it is on, its stamp and its operation.
42 ID, Type, Slug string
43 Stamp, Op string
44}
45
46// CommentID is a comment's ID: its file's name without .md,
47// <stamp>-<op>. No two comments on one knot share it, and it stays the
48// comment's for good, since a comment's file is never moved or deleted.
49func (f File) CommentID() string { return f.Stamp + "-" + f.Op }
50
51// Layout reads a graph's listing into its index, and refuses any listing
52// that is not exactly a graph's layout: the root holds only the four type
53// directories and comments/; a type directory holds only knots of its
54// type, named <id>-<slug>.md; comments/ holds only a directory per knot,
55// named by the knot's ID, holding only comments named <stamp>-<op>.md.
56// Every directory has the mode 40000, exactly as git writes it, and every
57// file is a plain file, mode 100644: no symlink, executable or submodule.
58// Every directory a path passes through is an entry of the listing in its
59// own right, as it is in any listing of a tree git wrote. No directory is
60// empty, no name repeats, and no ID is used twice. The counts are held to
61// MaxKnots and MaxComments. Whether each directory of comments is on a
62// knot the graph holds is the push's to check, since a knot deleted is the
63// clearer refusal.
64func Layout(entries []Entry) (*Index, error) {
65 idx, err := layout(entries)
66 if err != nil {
67 return nil, err
68 }
69 return idx, nil
70}
71
72func layout(entries []Entry) (*Index, *Error) {
73 idx := &Index{Knots: map[string]File{}, Comments: map[string]File{}, Files: map[string]string{}, knotAt: map[string]string{}}
74 seen := map[string]bool{}
75 children := map[string]int{}
76 isDir := map[string]bool{}
77 var dirs []string
78 for _, e := range entries {
79 if seen[e.Path] {
80 return nil, refuse(RuleLayout, e.Path, "is named twice in its tree")
81 }
82 seen[e.Path] = true
83 dir, base := path.Split(e.Path)
84 dir = strings.TrimSuffix(dir, "/")
85 children[dir]++
86 parts := strings.Split(e.Path, "/")
87 if e.Mode == "40000" {
88 dirs = append(dirs, e.Path)
89 isDir[e.Path] = true
90 if err := layoutDir(parts); err != nil {
91 return nil, err
92 }
93 continue
94 }
95 if e.Mode != "100644" {
96 return nil, refuse(RuleLayout, e.Path, fmt.Sprintf("has mode %s, and a graph holds only directories, mode 40000, and plain files, mode 100644: no symlink, executable or submodule", e.Mode))
97 }
98 f, err := layoutFile(parts, base)
99 if err != nil {
100 return nil, err
101 }
102 f.Path, f.OID = e.Path, e.OID
103 idx.Files[e.Path] = e.OID
104 if f.Stamp == "" {
105 if prior, ok := idx.Knots[f.ID]; ok {
106 return nil, refuse(RuleUniqueID, e.Path, fmt.Sprintf("has the id %s, which %s has already", f.ID, prior.Path))
107 }
108 idx.Knots[f.ID] = f
109 idx.knotAt[e.Path] = f.ID
110 } else {
111 idx.Comments[e.Path] = f
112 }
113 }
114 for _, d := range dirs {
115 if children[d] == 0 {
116 return nil, refuse(RuleLayout, d, "is an empty directory, which git does not write")
117 }
118 }
119 for _, e := range entries {
120 parts := strings.Split(e.Path, "/")
121 for i := 1; i < len(parts); i++ {
122 if d := strings.Join(parts[:i], "/"); !isDir[d] {
123 return nil, refuse(RuleLayout, e.Path, fmt.Sprintf("is listed without the directory %s it is in, and a tree git writes names each directory as an entry of its own", d))
124 }
125 }
126 }
127 switch {
128 case len(idx.Knots) > MaxKnots:
129 return nil, refuse(RuleLimit, "", fmt.Sprintf("the graph would hold %d knots, more than the %d it may", len(idx.Knots), MaxKnots))
130 case len(idx.Comments) > MaxComments:
131 return nil, refuse(RuleLimit, "", fmt.Sprintf("the graph would hold %d comments, more than the %d it may", len(idx.Comments), MaxComments))
132 }
133 return idx, nil
134}
135
136func layoutDir(parts []string) *Error {
137 p := strings.Join(parts, "/")
138 switch len(parts) {
139 case 1:
140 if _, ok := typeOfDirectory(parts[0]); ok || parts[0] == CommentsDirectory {
141 return nil
142 }
143 return refuse(RuleLayout, p, fmt.Sprintf("is no directory a graph holds; the root holds %s", strings.Join(rootNames(), ", ")))
144 case 2:
145 if parts[0] == CommentsDirectory && IsLocalID(parts[1]) {
146 return nil
147 }
148 if parts[0] == CommentsDirectory {
149 return refuse(RuleLayout, p, "is not named by a knot's id, as each directory of comments is")
150 }
151 }
152 return refuse(RuleLayout, p, "is a directory where a graph holds files")
153}
154
155func layoutFile(parts []string, base string) (File, *Error) {
156 p := strings.Join(parts, "/")
157 switch {
158 case len(parts) == 2 && parts[0] != CommentsDirectory:
159 t, ok := typeOfDirectory(parts[0])
160 if !ok {
161 break
162 }
163 m := knotFile.FindStringSubmatch(base)
164 if m == nil {
165 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is not named <id>-<slug>.md, as a knot is, with the id %s- and 7 hex digits and the slug lowercase letters, digits and hyphens", t.Prefix))
166 }
167 id, slug := m[1], m[3]
168 if !slugShape.MatchString(slug) || len(slug) > MaxSlug {
169 return File{}, refuse(RuleLayout, p, fmt.Sprintf("has the slug %q, and a slug is at most %d lowercase letters and digits, in words joined by single hyphens", slug, MaxSlug))
170 }
171 if pt, _ := typeOfPrefix(m[2]); pt.Name != t.Name {
172 return File{}, refuse(RuleDirectory, p, fmt.Sprintf("is a%s %s, and a%s %s belongs in %s/", article(pt.Name), pt.Name, article(pt.Name), pt.Name, pt.Directory))
173 }
174 return File{ID: id, Type: t.Name, Slug: slug}, nil
175 case len(parts) == 3 && parts[0] == CommentsDirectory:
176 m := commentFile.FindStringSubmatch(base)
177 if m == nil {
178 return File{}, refuse(RuleLayout, p, "is not named <stamp>-<op>.md, as a comment is, with the stamp YYYYMMDDTHHMMSSZ and the op 16 hex digits")
179 }
180 if _, err := time.Parse(CommentStamp, m[1]); err != nil {
181 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is stamped %s, which is no time: a comment's stamp is when it was written, YYYYMMDDTHHMMSSZ", m[1]))
182 }
183 return File{ID: parts[1], Stamp: m[1], Op: m[2]}, nil
184 }
185 return File{}, refuse(RuleLayout, p, fmt.Sprintf("is outside the graph's layout: a graph holds %s/<id>-<slug>.md and %s/<id>/<stamp>-<op>.md, and nothing else", strings.Join(typeDirectories(), "|"), CommentsDirectory))
186}
187
188func rootNames() []string { return append(typeDirectories(), CommentsDirectory) }
189
190func typeDirectories() []string {
191 var names []string
192 for _, t := range Types {
193 names = append(names, t.Directory)
194 }
195 return names
196}
197
198// Reader reads a file's content by its object, refusing one larger than
199// max bytes before reading it.
200type Reader func(oid string, max int) ([]byte, error)
201
202// Push is one write of a graph to judge: the graph before it, which is nil
203// for the push that creates the ref, and the graph it would leave.
204type Push struct {
205 Old, New *Index
206 Read Reader
207 // Pusher is the principal pushing. A new knot's created_by, a new
208 // comment's author and an edited comment's edited_by must name it.
209 Pusher string
210 // MayEdit decides whether the pusher may edit a comment another
211 // principal wrote: it returns nil when the pusher may edit a comment
212 // by author, and the reason it may not otherwise. Who may is the
213 // host's decision, so the hook supplies it from the host's grants.
214 // When it is nil, a pusher edits only its own comments.
215 MayEdit func(author string) error
216}
217
218// Check holds a push to every rule. The graph before it was valid, so only
219// what changed is read: each knot and comment the push adds or changes,
220// and, for cycles, the knots their edges reach. The rules about the whole
221// graph are checked on every push all the same: the counts from the
222// listing, and cycles by walking the edges from every changed knot.
223func (p Push) Check() error {
224 if err := p.check(true); err != nil {
225 return err
226 }
227 return nil
228}
229
230// Validate holds a whole graph to every rule but the push's: it reads
231// every knot and comment, and needs no pusher.
232func Validate(idx *Index, read Reader) error {
233 if err := (Push{New: idx, Read: read}).check(false); err != nil {
234 return err
235 }
236 return nil
237}
238
239func (p Push) check(push bool) *Error {
240 g := &graph{idx: p.New, read: p.Read, knots: map[string]*Knot{}}
241 var changed []string
242 for path, oid := range p.New.Files {
243 if p.Old == nil || p.Old.Files[path] != oid {
244 changed = append(changed, path)
245 }
246 }
247 sort.Strings(changed)
248 if p.Old != nil {
249 var gone []string
250 for path := range p.Old.Files {
251 if _, ok := p.New.Files[path]; !ok {
252 gone = append(gone, path)
253 }
254 }
255 sort.Strings(gone)
256 for _, path := range gone {
257 what := "a knot is never deleted"
258 if _, ok := p.Old.Comments[path]; ok {
259 what = "a comment is never deleted"
260 }
261 return refuse(RuleTransition, path, "is deleted, and "+what+"; a knot that is done is closed by its status, and the history is the record")
262 }
263 }
264 if push && len(changed) > MaxChangedPaths {
265 return refuse(RuleLimit, "", fmt.Sprintf("the push adds or changes %d files, more than the %d one commit may", len(changed), MaxChangedPaths))
266 }
267 var touched []string
268 for _, path := range changed {
269 if c, ok := p.New.Comments[path]; ok {
270 if err := p.checkComment(g, c, push); err != nil {
271 return err
272 }
273 continue
274 }
275 f := p.New.Knots[p.New.knotAt[path]]
276 k, err := g.knot(f.ID)
277 if err != nil {
278 return err
279 }
280 if err := g.checkEdges(k); err != nil {
281 return err
282 }
283 if err := p.checkTransition(f, k); err != nil {
284 return err
285 }
286 touched = append(touched, f.ID)
287 }
288 return g.checkCycles(touched)
289}
290
291// checkComment holds a comment the push adds or changes to its rules. A
292// whole graph's comments are held to their form alone, edited or not.
293//
294// A comment the push adds names the pusher as its author, and records no
295// edit. A comment the push changes is an edit: it keeps its author, names
296// the pusher in edited_by, and says when in edited. The pusher edits its
297// own comments, and another principal's only where MayEdit allows. A
298// comment's path, and so its ID, never changes, since no comment is
299// deleted.
300func (p Push) checkComment(g *graph, c File, push bool) *Error {
301 // A comment the push leaves unchanged is on a knot the graph holds,
302 // since no knot is deleted. One it adds must be too.
303 if _, ok := p.New.Knots[c.ID]; !ok {
304 return refuse(RuleEdgeResolves, path.Dir(c.Path), fmt.Sprintf("holds comments on %s, which is no knot in the graph", c.ID))
305 }
306 data, err := g.read(c.OID, MaxCommentSize)
307 if err != nil {
308 return refuse(RuleLimit, c.Path, err.Error())
309 }
310 comment, perr := parseComment(c.Path, data)
311 if perr != nil {
312 return perr
313 }
314 if !push {
315 return nil
316 }
317 var before string
318 if p.Old != nil {
319 before = p.Old.Files[c.Path]
320 }
321 if before == "" {
322 switch {
323 case comment.Edited != "":
324 return refuse(RuleProvenance, c.Path, "is a new comment that records an edit, and edited and edited_by are written only by an edit to a comment already in the graph")
325 case p.Pusher != "" && comment.Author != p.Pusher:
326 return refuse(RuleProvenance, c.Path, fmt.Sprintf("names %s as its author, and %s is pushing it: a comment's author is the principal that writes it", comment.Author, p.Pusher))
327 }
328 return nil
329 }
330 data, err = g.read(before, MaxCommentSize)
331 if err != nil {
332 return refuse(RuleLimit, c.Path, "as it was: "+err.Error())
333 }
334 old, perr := parseComment(c.Path, data)
335 if perr != nil {
336 return refuse(perr.Rule, c.Path, "as it was: "+perr.Msg)
337 }
338 switch {
339 case comment.Author != old.Author:
340 return refuse(RuleTransition, c.Path, fmt.Sprintf("changes its author from %q to %q, and a comment's author never changes", old.Author, comment.Author))
341 case comment.Edited == "":
342 return refuse(RuleProvenance, c.Path, "changes a comment without recording the edit: an edited comment says when it was edited and by whom, in edited and edited_by")
343 case p.Pusher == "":
344 return nil
345 case comment.EditedBy != p.Pusher:
346 return refuse(RuleProvenance, c.Path, fmt.Sprintf("names %s in edited_by, and %s is pushing it: an edit names the principal that makes it", comment.EditedBy, p.Pusher))
347 case p.Pusher == old.Author:
348 return nil
349 }
350 why := errors.New("a comment is edited only by its author")
351 if p.MayEdit != nil {
352 why = p.MayEdit(old.Author)
353 }
354 if why != nil {
355 return refuse(RuleTransition, c.Path, fmt.Sprintf("is a comment by %s, and %s is editing it: %v", old.Author, p.Pusher, why))
356 }
357 return nil
358}
359
360// checkTransition holds a knot the push adds or changes to what a push
361// may do to one: a new knot names the pusher as its creator, and a changed
362// one keeps its id, type, created date and creator.
363func (p Push) checkTransition(f File, k *Knot) *Error {
364 var before File
365 if p.Old != nil {
366 before = p.Old.Knots[f.ID]
367 }
368 if before.Path == "" {
369 if p.Pusher != "" && k.CreatedBy != p.Pusher {
370 return refuse(RuleProvenance, f.Path, fmt.Sprintf("names %s in created_by, and %s is pushing it: a new knot's creator is the principal that pushes it", k.CreatedBy, p.Pusher))
371 }
372 return nil
373 }
374 if before.Path != f.Path {
375 return refuse(RuleTransition, f.Path, fmt.Sprintf("moves %s from %s, and a knot's file never moves", f.ID, before.Path))
376 }
377 data, err := p.Read(before.OID, MaxKnotSize)
378 if err != nil {
379 return refuse(RuleLimit, before.Path, "as it was: "+err.Error())
380 }
381 old, perr := parseKnot(before.Path, before.Slug, data)
382 if perr != nil {
383 return refuse(perr.Rule, before.Path, "as it was: "+perr.Msg)
384 }
385 for _, field := range []string{"id", "type", "created", "created_by"} {
386 if old.Get(field) != k.Get(field) {
387 return refuse(RuleTransition, f.Path, fmt.Sprintf("changes %s from %q to %q, and a knot's id, type, created and created_by never change", field, old.Get(field), k.Get(field)))
388 }
389 }
390 return nil
391}
392
393// graph reads the knots of one index on demand, each once.
394type graph struct {
395 idx *Index
396 read Reader
397 knots map[string]*Knot
398}
399
400// knot is the knot with id, read and held to every rule about it alone,
401// and to its filename.
402func (g *graph) knot(id string) (*Knot, *Error) {
403 if k, ok := g.knots[id]; ok {
404 return k, nil
405 }
406 f := g.idx.Knots[id]
407 data, err := g.read(f.OID, MaxKnotSize)
408 if err != nil {
409 return nil, refuse(RuleLimit, f.Path, err.Error())
410 }
411 k, perr := parseKnot(f.Path, f.Slug, data)
412 if perr != nil {
413 return nil, perr
414 }
415 switch {
416 case k.ID != f.ID:
417 return nil, refuse(RuleFilename, f.Path, fmt.Sprintf("its filename says id %s, and its frontmatter says %s", f.ID, k.ID))
418 case k.Type != f.Type:
419 t, _ := TypeNamed(k.Type)
420 return nil, refuse(RuleDirectory, f.Path, fmt.Sprintf("is a%s %s, and a%s %s belongs in %s/", article(k.Type), k.Type, article(k.Type), k.Type, t.Directory))
421 }
422 if derived := DeriveID(k.TypeOf(), f.Slug); derived != k.ID {
423 return nil, refuse(RuleIDDerived, f.Path, fmt.Sprintf("its id %s is not derived from its slug %q, which gives %s", k.ID, f.Slug, derived))
424 }
425 g.knots[id] = k
426 return k, nil
427}
428
429// checkEdges holds every local edge of k to naming a knot in the graph,
430// of a type the edge takes. A reference to another project's knot is
431// held to its shape alone, which the knot's own check has done.
432func (g *graph) checkEdges(k *Knot) *Error {
433 resolve := func(field, id string, want ...string) *Error {
434 f, ok := g.idx.Knots[id]
435 switch {
436 case !ok:
437 return refuse(RuleEdgeResolves, k.Path(), fmt.Sprintf("%s names %s, which is no knot in the graph", field, id))
438 case len(want) > 0 && !slices.Contains(want, f.Type):
439 return refuse(RuleParentOutcome, k.Path(), fmt.Sprintf("%s names %s, a %s, and it names a%s %s", field, id, f.Type, article(want[0]), strings.Join(want, " or ")))
440 }
441 return nil
442 }
443 if k.Parent != "" {
444 if err := resolve("parent", k.Parent, "outcome"); err != nil {
445 return err
446 }
447 }
448 if k.GraduatedInto != "" {
449 if err := resolve("graduated_into", k.GraduatedInto, "outcome", "question"); err != nil {
450 return err
451 }
452 }
453 for _, ref := range k.BlockedBy {
454 if IsLocalID(ref) {
455 if err := resolve("blocked_by", ref); err != nil {
456 return err
457 }
458 }
459 }
460 return nil
461}
462
463// checkCycles refuses a cycle in parent edges, or in blocked_by edges,
464// through any knot in from. The graph before the push had none, so every
465// cycle the push could make runs through a knot it changed. Each knot
466// reached is read once.
467//
468// The two edges are checked apart. A milestone may wait on one of its own
469// work items, and that is no cycle: the work item can finish.
470func (g *graph) checkCycles(from []string) *Error {
471 for _, edge := range []string{"parent", "blocked_by"} {
472 const (
473 visiting = 1
474 done = 2
475 )
476 state := map[string]int{}
477 var trail []string
478 var visit func(id string) *Error
479 visit = func(id string) *Error {
480 switch state[id] {
481 case visiting:
482 at := 0
483 for trail[at] != id {
484 at++
485 }
486 loop := append(append([]string(nil), trail[at:]...), id)
487 k := g.knots[id]
488 return refuse(RuleCycle, k.Path(), fmt.Sprintf("its %s edges form a cycle, %s", edge, strings.Join(loop, " → ")))
489 case done:
490 return nil
491 }
492 k, err := g.knot(id)
493 if err != nil {
494 return err
495 }
496 state[id] = visiting
497 trail = append(trail, id)
498 var next []string
499 if edge == "parent" && k.Parent != "" {
500 next = []string{k.Parent}
501 } else if edge == "blocked_by" {
502 for _, ref := range k.BlockedBy {
503 if _, ok := g.idx.Knots[ref]; ok {
504 next = append(next, ref)
505 }
506 }
507 }
508 for _, n := range next {
509 if err := visit(n); err != nil {
510 return err
511 }
512 }
513 trail = trail[:len(trail)-1]
514 state[id] = done
515 return nil
516 }
517 for _, id := range from {
518 if err := visit(id); err != nil {
519 return err
520 }
521 }
522 }
523 return nil
524}