gunk-dev/the-valley

journal.go

sourcee2855ca05a68main's published tip history
22.0 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io/fs"
10 "os"
11 "path/filepath"
12 "regexp"
13 "sort"
14 "strings"
15
16 "the-valley/change"
17 "the-valley/rebase"
18)
19
20// The journal is every write the restacker intends and has not yet seen
21// through, kept in the state directory before the first of them is
22// pushed, so a pass that ends part way can tell afterwards what it did. It
23// is the restacker's own, local file, journal.json, in the format
24// valley-restack-journal/v1:
25//
26// {
27// "schema": "valley-restack-journal/v1",
28// "repository": "<--repo>", "target": "main", "principal": "<--principal>",
29// "families": [
30// {"operation": "20261020T120400Z-1a2b3c4d",
31// "tip": "<main's tip as captured>",
32// "evidence": "<the evidence fingerprint as captured>",
33// "observed": { the whole observation: Observation },
34// "branches": { the branch push, as rebase.PendingBranches keeps it } or null,
35// "versions": [ each version, as rebase.PendingVersion keeps it, lower layers first ],
36// "reports": [ {"pending": { as rebase.PendingReport keeps it },
37// "omitted": [ what the report leaves out of the observation ]} ],
38// "replacements": [ each report of what did happen, in the form of a report ]}
39// ]
40// }
41//
42// Each family carries the operation that built it, and main's tip and the
43// evidence fingerprint that operation captured, since a journal can hold
44// families of several operations: a family stays in the journal while it
45// is open (publish.go), and a later pass adds the families it builds. No
46// two families share a change or a branch, since the planner has a family
47// that would wait (waits). A
48// family has a branch push and versions only when its operation would
49// restack it. A replacement is a report of what did happen to a family
50// whose branches moved, built when origin's report says otherwise
51// (publish.go).
52// Each version is leased on the record commit the capture read, and each
53// report and replacement on the report origin held. Every write names the
54// object it would push by its full ID, and every one of those objects is
55// kept reachable in the scratch repository, under
56// refs/valley-restack/<operation>/<object>, for as long as the journal
57// names it (keep).
58//
59// The journal is read as strictly as it is written: a field missing,
60// unknown or named twice, a form that does not agree with itself, or a
61// journal another repository, target or principal wrote is refused, and
62// nothing it names is decided (loadJournal). A family agrees with itself
63// only when every write it holds is about one of its layers. A family
64// that would restack adds exactly one version of each of its changes.
65// Each report gives the family's result, and says published exactly what
66// the family's versions add: nothing, for a family that adds none. Each
67// replacement says complete or partial, says each change was published at
68// its prepared head, and names a version only as the family adds it. A
69// journal that would not read back as written is never kept (keep). A
70// journal that is missing is never inferred: what origin shows of a write
71// no journal names is left for the planner, which holds a change whose
72// branch is not at its recorded head.
73
74// journalSchema names the journal's format.
75const journalSchema = "valley-restack-journal/v1"
76
77// journalFile is the journal's name in the state directory.
78const journalFile = "journal.json"
79
80// retainPrefix is where the scratch repository keeps every object a
81// journaled operation would push.
82const retainPrefix = "refs/valley-restack/"
83
84// Journal is the writes of every family still to be seen through.
85type Journal struct {
86 Schema string `json:"schema"`
87 Repository string `json:"repository"`
88 Target string `json:"target"`
89 Principal string `json:"principal"`
90 Families []JournalFamily `json:"families"`
91}
92
93// JournalFamily is one family's observation and the writes it would make.
94type JournalFamily struct {
95 Operation string `json:"operation"` // the operation that built it
96 Tip string `json:"tip"` // main's tip as that operation captured it
97 Evidence string `json:"evidence"` // change.EvidenceFingerprint as captured
98 Observed Observation `json:"observed"`
99 Branches *rebase.PendingBranches `json:"branches"`
100 Versions []*rebase.PendingVersion `json:"versions"`
101 Reports []JournalReport `json:"reports"`
102 Replacements []JournalReport `json:"replacements"` // reports of what did happen, at most one a change
103}
104
105// JournalReport is one change's report, and what it leaves out of the
106// observation it was cut from: nothing for a report that holds it whole.
107type JournalReport struct {
108 Pending *rebase.PendingReport `json:"pending"`
109 Omitted []string `json:"omitted"`
110}
111
112// operationName is the shape of an operation's name, as a report's
113// operation field takes it.
114var operationName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]*$`)
115
116// check refuses a journal that does not agree with itself, or that
117// another repository, target or principal wrote.
118func (j *Journal) check(b binding) error {
119 switch {
120 case j.Schema != journalSchema:
121 return fmt.Errorf("its schema is %q, where %q is expected", j.Schema, journalSchema)
122 case j.Repository != b.Repository || j.Target != b.Target || j.Principal != b.Principal:
123 return fmt.Errorf("it belongs to %s on %s as %s, and this pass is for %s on %s as %s",
124 j.Target, j.Repository, j.Principal, b.Target, b.Repository, b.Principal)
125 }
126 whose := map[string]int{} // the family each change and branch is in
127 for i, f := range j.Families {
128 if err := f.check(j.Target); err != nil {
129 return fmt.Errorf("its family %d: %w", i, err)
130 }
131 for _, l := range f.Observed.Layers {
132 for _, key := range layerKeys(l.ID, l.Branch) {
133 if k, found := whose[key]; found && k != i {
134 return fmt.Errorf("its families %d and %d share the %s", k, i, key)
135 }
136 whose[key] = i
137 }
138 }
139 }
140 return nil
141}
142
143// layerKeys names what a layer is, for telling whether two families
144// share it: "change <ID>" for a change, and "branch <name>" for the
145// branch it is on.
146func layerKeys(id, branch string) []string {
147 var keys []string
148 if id != "" {
149 keys = append(keys, "change "+id)
150 }
151 if branch != "" {
152 keys = append(keys, "branch "+branch)
153 }
154 return keys
155}
156
157func (f *JournalFamily) check(target string) error {
158 o := f.Observed
159 switch {
160 case !operationName.MatchString(f.Operation) || len(f.Operation) > change.MaxOperation:
161 return fmt.Errorf("its operation %q is not a report's operation name", f.Operation)
162 case !rebase.IsObjectID(f.Tip):
163 return fmt.Errorf("its tip %q is not a full object ID", f.Tip)
164 case !hexOf(f.Evidence, 16):
165 return fmt.Errorf("its evidence %q is not an evidence fingerprint", f.Evidence)
166 case o.Action != restack && o.Action != hold:
167 return fmt.Errorf("its action is %q, where %q or %q is expected", o.Action, restack, hold)
168 case o.Result != change.RestackComplete && o.Result != change.RestackConflict && o.Result != change.RestackBlocked:
169 return fmt.Errorf("its result is %q", o.Result)
170 case len(o.Layers) == 0:
171 return errors.New("it observed no layer")
172 }
173 layers := map[string]ObservedLayer{} // change layers by ID
174 order := map[string]int{}
175 branches := map[string]ObservedLayer{}
176 for i, l := range o.Layers {
177 switch {
178 case l.Name == "":
179 return fmt.Errorf("its layer %d has no name", i)
180 case l.ID != "" && !change.ValidID(l.ID):
181 return fmt.Errorf("its layer %s names the change ID %q", l.Name, l.ID)
182 case l.ID != "" && (!rebase.IsObjectID(l.Record) || l.Version < 1):
183 return fmt.Errorf("its layer %s names no record commit and version", l.Name)
184 case l.ID == "" && (l.Record != "" || l.Version != 0):
185 return fmt.Errorf("its plain branch %s names a record", l.Name)
186 case !rebase.IsObjectID(l.Head):
187 return fmt.Errorf("its layer %s names the head %q", l.Name, l.Head)
188 case l.Branch != "" && !change.ValidBranch(l.Branch):
189 return fmt.Errorf("its layer %s names the branch %q", l.Name, l.Branch)
190 case l.BranchTip != "" && !rebase.IsObjectID(l.BranchTip):
191 return fmt.Errorf("its layer %s names the branch tip %q", l.Name, l.BranchTip)
192 case l.ID != "" && layers[l.ID].ID != "":
193 return fmt.Errorf("it observed %s twice", l.ID)
194 }
195 if l.ID != "" {
196 layers[l.ID], order[l.ID] = l, i
197 }
198 if l.Branch != "" {
199 branches[l.Branch] = l
200 }
201 }
202 if o.Failing != "" && layers[o.Failing].ID == "" {
203 return fmt.Errorf("its failing layer %s is none of its changes", o.Failing)
204 }
205
206 if (f.Branches != nil) != (o.Result == change.RestackComplete) || (f.Branches == nil) != (len(f.Versions) == 0) {
207 return errors.New("it has a branch push and versions exactly when it would restack")
208 }
209 news := map[string]string{}
210 if b := f.Branches; b != nil {
211 if b.Tip != f.Tip {
212 return fmt.Errorf("its branch push was prepared on %s, not the captured tip %s", b.Tip, f.Tip)
213 }
214 for _, u := range b.Updates {
215 l, ok := branches[u.Branch]
216 if !ok || l.BranchTip != u.Old {
217 return fmt.Errorf("its branch push moves %s from %s, which it did not observe", u.Branch, u.Old)
218 }
219 news[u.Branch] = u.New
220 }
221 if len(b.Updates) != len(o.Layers) {
222 return errors.New("its branch push does not move every layer")
223 }
224 }
225 last := -1
226 written := map[string]*rebase.PendingVersion{} // each version by change ID
227 for _, v := range f.Versions {
228 if v == nil {
229 return errors.New("it holds an empty version")
230 }
231 l, ok := layers[v.ID]
232 switch {
233 case !ok:
234 return fmt.Errorf("it adds a version to %s, which is none of its changes", v.ID)
235 case !v.Restack():
236 return fmt.Errorf("its version of %s is not a restack's", v.ID)
237 case v.Old != l.Record || v.Branch != l.Branch || v.Head != news[l.Branch]:
238 return fmt.Errorf("its version of %s is not leased on the record it observed, or does not record the head prepared for %s", v.ID, l.Branch)
239 case order[v.ID] <= last:
240 return fmt.Errorf("its versions are not lower layers first")
241 }
242 last = order[v.ID]
243 written[v.ID] = v
244 }
245 if f.Branches != nil && len(written) != len(layers) {
246 return fmt.Errorf("it would restack %d changes and adds a version to %d of them, where each change gets exactly one", len(layers), len(written))
247 }
248 reported := map[string]bool{}
249 for _, r := range f.Reports {
250 p := r.Pending
251 switch {
252 case p == nil:
253 return errors.New("it holds an empty report")
254 case layers[p.ID].ID == "":
255 return fmt.Errorf("it reports on %s, which is none of its changes", p.ID)
256 case reported[p.ID]:
257 return fmt.Errorf("it reports on %s twice", p.ID)
258 case !f.ours(p.Report, target):
259 return fmt.Errorf("its report on %s is not this operation's, on %s at %s", p.ID, target, f.Tip)
260 case p.Report.Result != o.Result:
261 return fmt.Errorf("its report on %s says %s, and the family's result is %s", p.ID, p.Report.Result, o.Result)
262 }
263 if err := checkClaims(p.Report, layers, written); err != nil {
264 return fmt.Errorf("its report on %s %w", p.ID, err)
265 }
266 reported[p.ID] = true
267 }
268 replaced := map[string]bool{}
269 for _, r := range f.Replacements {
270 p := r.Pending
271 switch {
272 case p == nil:
273 return errors.New("it holds an empty replacement")
274 case f.Branches == nil:
275 return fmt.Errorf("it replaces the report on %s, and moved no branch", p.ID)
276 case layers[p.ID].ID == "":
277 return fmt.Errorf("it replaces a report on %s, which is none of its changes", p.ID)
278 case replaced[p.ID]:
279 return fmt.Errorf("it replaces the report on %s twice", p.ID)
280 case !f.ours(p.Report, target):
281 return fmt.Errorf("its replacement on %s is not this operation's, on %s at %s", p.ID, target, f.Tip)
282 }
283 if err := checkHappened(p.Report, layers, written, news); err != nil {
284 return fmt.Errorf("its replacement on %s %w", p.ID, err)
285 }
286 replaced[p.ID] = true
287 }
288 return nil
289}
290
291// ours reports whether a report is the family's operation's, on the
292// target at the tip the operation captured.
293func (f *JournalFamily) ours(r *change.RestackReport, target string) bool {
294 return r.Operation == f.Operation && r.Target == target && r.TargetTip == change.HeadPrefix+f.Tip
295}
296
297// checkHappened refuses a replacement that says other than what could
298// have happened to a family whose branches moved: each of its layers is
299// one of the family's changes, published at the head prepared for its
300// branch, with a version only as the family adds it. It says complete
301// when it names every change's version, and partial otherwise.
302func checkHappened(r *change.RestackReport, layers map[string]ObservedLayer, written map[string]*rebase.PendingVersion, news map[string]string) error {
303 all := true
304 for _, l := range r.Layers {
305 v, p := written[l.ChangeID], l.Published
306 switch {
307 case layers[l.ChangeID].ID == "":
308 return fmt.Errorf("has a layer for %s, which is none of the family's changes", l.ChangeID)
309 case p == nil || p.Head != change.HeadPrefix+news[layers[l.ChangeID].Branch]:
310 return fmt.Errorf("does not say %s was published at the head prepared for it", l.ChangeID)
311 case p.Version == nil && p.Record == nil:
312 all = false
313 case v == nil || p.Version == nil || *p.Version != v.Version || p.Record == nil || *p.Record != change.HeadPrefix+v.Commit:
314 return fmt.Errorf("says %s was published as a version the family does not add", l.ChangeID)
315 }
316 }
317 switch {
318 case r.Result == change.RestackComplete && !all:
319 return errors.New("says complete, and names a change with no version")
320 case r.Result == change.RestackPartial && all:
321 return errors.New("says partial, and names every change's version")
322 case r.Result != change.RestackComplete && r.Result != change.RestackPartial:
323 return fmt.Errorf("says %s, where complete or partial is expected", r.Result)
324 }
325 return nil
326}
327
328// checkClaims refuses a report that says something was published other
329// than what the family's versions add. Each of the report's layers is one
330// of the family's changes. A layer says it was published exactly when the
331// family adds a version of that change, and then names that version's
332// head, number and record commit.
333func checkClaims(r *change.RestackReport, layers map[string]ObservedLayer, written map[string]*rebase.PendingVersion) error {
334 for _, l := range r.Layers {
335 v, p := written[l.ChangeID], l.Published
336 switch {
337 case layers[l.ChangeID].ID == "":
338 return fmt.Errorf("has a layer for %s, which is none of the family's changes", l.ChangeID)
339 case v == nil && p != nil:
340 return fmt.Errorf("says %s was published, and the family adds no version of it", l.ChangeID)
341 case v != nil && p == nil:
342 return fmt.Errorf("says nothing was published for %s, and the family adds v%d of it", l.ChangeID, v.Version)
343 case v != nil && (p.Head != change.HeadPrefix+v.Head || p.Version == nil || *p.Version != v.Version ||
344 p.Record == nil || *p.Record != change.HeadPrefix+v.Commit):
345 return fmt.Errorf("says %s was published as other than v%d at %s, record %s, which the family adds", l.ChangeID, v.Version, short(v.Head), short(v.Commit))
346 }
347 }
348 return nil
349}
350
351func hexOf(s string, n int) bool {
352 return len(s) == n && strings.Trim(s, "0123456789abcdef") == ""
353}
354
355// loadJournal reads the journal in the state directory: nil when there is
356// none. A journal that does not read, or that is another's, is an error,
357// and nothing it names is decided.
358func loadJournal(dir string, b binding) (*Journal, error) {
359 path := filepath.Join(dir, journalFile)
360 data, err := os.ReadFile(path)
361 switch {
362 case errors.Is(err, fs.ErrNotExist):
363 return nil, nil
364 case err != nil:
365 return nil, fmt.Errorf("reading the journal %s: %w", path, err)
366 }
367 var j Journal
368 if err := strictly(data, &j); err != nil {
369 return nil, fmt.Errorf("the journal %s does not read, so nothing it names is decided: %w", path, err)
370 }
371 if err := j.check(b); err != nil {
372 return nil, fmt.Errorf("the journal %s is refused, so nothing it names is decided: %w", path, err)
373 }
374 return &j, nil
375}
376
377// strictly reads data into v, and takes only what json.Marshal writes of
378// v, as rebase's kept forms are read: space between tokens is all that may
379// differ.
380func strictly(data []byte, v any) error {
381 dec := json.NewDecoder(bytes.NewReader(data))
382 dec.DisallowUnknownFields()
383 if err := dec.Decode(v); err != nil {
384 return err
385 }
386 var compact bytes.Buffer
387 if err := json.Compact(&compact, data); err != nil {
388 return err
389 }
390 again, err := json.Marshal(v)
391 if err != nil {
392 return err
393 }
394 if !bytes.Equal(compact.Bytes(), again) {
395 return errors.New("it is not in the form it is kept in: a field is missing or named twice, or a value is written another way")
396 }
397 return nil
398}
399
400// retained is every object the journal's writes would push, each by the
401// ref the scratch repository keeps it under: each prepared head, each
402// record commit, each report commit and each replacement's.
403func (j *Journal) retained() map[string]string {
404 refs := map[string]string{}
405 for _, f := range j.Families {
406 var oids []string
407 if f.Branches != nil {
408 for _, u := range f.Branches.Updates {
409 oids = append(oids, u.New)
410 }
411 }
412 for _, v := range f.Versions {
413 oids = append(oids, v.Commit)
414 }
415 for _, r := range append(append([]JournalReport{}, f.Reports...), f.Replacements...) {
416 oids = append(oids, r.Pending.Commit)
417 }
418 for _, oid := range oids {
419 refs[retainPrefix+f.Operation+"/"+oid] = oid
420 }
421 }
422 return refs
423}
424
425// keep makes the journal durable before any of its writes is pushed. It
426// archives the observation of each family whose reports leave something
427// out of it, and keeps every object the writes would push reachable in
428// the scratch repository, under refs/valley-restack/<operation>/<object>.
429// It then writes the journal to the state directory, synced, in place of
430// any before it. Only then does it let go of each object the journal no
431// longer names. A journal that would not read back as written is refused
432// before anything is kept, since a later pass would refuse it in turn.
433func keep(ctx context.Context, g rebase.Git, dir string, j *Journal) error {
434 if err := j.check(binding{Repository: j.Repository, Target: j.Target, Principal: j.Principal}); err != nil {
435 return fmt.Errorf("the journal cannot be kept: %w", err)
436 }
437 data, err := json.MarshalIndent(j, "", " ")
438 if err != nil {
439 return err
440 }
441 if err := strictly(data, &Journal{}); err != nil {
442 return fmt.Errorf("the journal cannot be kept, since it would not read back as written: %w", err)
443 }
444 for _, f := range j.Families {
445 for _, r := range f.Reports {
446 if len(r.Omitted) > 0 {
447 if err := archive(dir, f.Observed); err != nil {
448 return fmt.Errorf("the journal cannot be kept, since the observation its reports are cut from cannot be archived: %w", err)
449 }
450 break
451 }
452 }
453 }
454 refs := j.retained()
455 var names []string
456 for ref := range refs {
457 names = append(names, ref)
458 }
459 sort.Strings(names)
460 var stdin strings.Builder
461 for _, ref := range names {
462 fmt.Fprintf(&stdin, "update %s %s\n", ref, refs[ref])
463 }
464 if err := updateRefs(ctx, g, stdin.String()); err != nil {
465 return fmt.Errorf("could not keep the objects of the journal: %w", err)
466 }
467 if err := writeDurably(dir, journalFile, append(data, '\n')); err != nil {
468 return err
469 }
470 return letGo(ctx, g, refs)
471}
472
473// observationsDir is where the state directory keeps the whole
474// observation a report was cut from, when the report leaves something out
475// of it.
476const observationsDir = "observations"
477
478// archive keeps the whole observation in the state directory as
479// observations/<digest>.json, where <digest> is the observation's digest.
480// The file holds the observation as the digest is taken of it, so its
481// SHA-256 begins with that digest. A report that leaves something out
482// names the file. The file outlives the journal: nothing the restacker
483// does removes it.
484func archive(dir string, o Observation) error {
485 data, err := json.Marshal(o)
486 if err != nil {
487 return err
488 }
489 at := filepath.Join(dir, observationsDir)
490 if err := os.MkdirAll(at, 0o700); err != nil {
491 return err
492 }
493 return writeDurably(at, o.Digest()+".json", data)
494}
495
496// letGo lets go of every object the scratch repository keeps for the
497// journal, but those kept names: nil lets go of them all.
498func letGo(ctx context.Context, g rebase.Git, kept map[string]string) error {
499 out, err := gitOut(ctx, g, "for-each-ref", "--format=%(refname)", retainPrefix)
500 if err != nil {
501 return err
502 }
503 var stdin strings.Builder
504 for _, ref := range strings.Fields(out) {
505 if _, ok := kept[ref]; !ok {
506 fmt.Fprintf(&stdin, "delete %s\n", ref)
507 }
508 }
509 if err := updateRefs(ctx, g, stdin.String()); err != nil {
510 return fmt.Errorf("could not let go of the objects the journal no longer names: %w", err)
511 }
512 return nil
513}
514
515// updateRefs runs git update-ref --stdin with the instructions given, all
516// in one transaction.
517func updateRefs(ctx context.Context, g rebase.Git, instructions string) error {
518 if instructions == "" {
519 return nil
520 }
521 cmd := g.Command(ctx, "update-ref", "--stdin")
522 cmd.Stdin = strings.NewReader(instructions)
523 if out, err := cmd.CombinedOutput(); err != nil {
524 return fmt.Errorf("%v: %s", err, strings.TrimSpace(string(out)))
525 }
526 return nil
527}
528
529// forget removes the journal from the state directory, durably, and then
530// lets go of every object kept for it.
531func forget(ctx context.Context, g rebase.Git, dir string) error {
532 if err := os.Remove(filepath.Join(dir, journalFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
533 return err
534 }
535 d, err := os.Open(dir)
536 if err != nil {
537 return err
538 }
539 err = d.Sync()
540 d.Close()
541 if err != nil {
542 return err
543 }
544 return letGo(ctx, g, nil)
545}
546
547// writeDurably writes a file in dir through a synced temporary file, and
548// renames it into place, so a crash leaves the old file or the new one,
549// whole. The directory is synced after, so the rename is durable too.
550func writeDurably(dir, name string, data []byte) error {
551 tmp, err := os.CreateTemp(dir, name+".*")
552 if err != nil {
553 return err
554 }
555 defer os.Remove(tmp.Name())
556 _, err = tmp.Write(data)
557 if serr := tmp.Sync(); err == nil {
558 err = serr
559 }
560 if cerr := tmp.Close(); err == nil {
561 err = cerr
562 }
563 if err != nil {
564 return fmt.Errorf("writing %s in %s: %w", name, dir, err)
565 }
566 if err := os.Rename(tmp.Name(), filepath.Join(dir, name)); err != nil {
567 return err
568 }
569 d, err := os.Open(dir)
570 if err != nil {
571 return err
572 }
573 defer d.Close()
574 return d.Sync()
575}