gunk-dev/the-valley

journal.go

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