gunk-dev/the-valley

journal.go

sourcef703cb5df113main's published tip history
12.7 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 "strings"
14
15 "the-valley/change"
16 "the-valley/rebase"
17)
18
19// The journal is every write one operation intends, kept in the state
20// directory before the first of them is pushed, so a pass that ends part
21// way can tell afterwards what it did. It is the restacker's own, local
22// file, journal.json, in the format valley-restack-journal/v1:
23//
24// {
25// "schema": "valley-restack-journal/v1",
26// "repository": "<--repo>", "target": "main", "principal": "<--principal>",
27// "operation": "20261020T120400Z-1a2b3c4d",
28// "tip": "<main's tip as captured>",
29// "evidence": "<the evidence fingerprint as captured>",
30// "families": [
31// {"observed": { the whole observation: Observation },
32// "branches": { the branch push, as rebase.PendingBranches keeps it } or null,
33// "versions": [ each version, as rebase.PendingVersion keeps it, lower layers first ],
34// "reports": [ {"pending": { as rebase.PendingReport keeps it },
35// "omitted": [ what the report leaves out of the observation ]} ]}
36// ]
37// }
38//
39// A family has a branch push and versions only when the operation would
40// restack it. Each version is leased on the record commit the capture
41// read, and each report on the report origin held. Every write names the
42// object it would push by its full ID, and every one of those objects is
43// kept reachable in the scratch repository, under
44// refs/valley-restack/<operation>/, for as long as the journal names it
45// (keep).
46//
47// The journal is read as strictly as it is written: a field missing,
48// unknown or named twice, a form that does not agree with itself, or a
49// journal another repository, target or principal wrote is refused, and
50// nothing it names is decided (loadJournal). A journal that is missing is
51// never inferred: what origin shows of a write no journal names is left
52// for the planner, which holds a change whose branch is not at its
53// recorded head.
54
55// journalSchema names the journal's format.
56const journalSchema = "valley-restack-journal/v1"
57
58// journalFile is the journal's name in the state directory.
59const journalFile = "journal.json"
60
61// retainPrefix is where the scratch repository keeps every object a
62// journaled operation would push.
63const retainPrefix = "refs/valley-restack/"
64
65// Journal is one operation's intended writes.
66type Journal struct {
67 Schema string `json:"schema"`
68 Repository string `json:"repository"`
69 Target string `json:"target"`
70 Principal string `json:"principal"`
71 Operation string `json:"operation"`
72 Tip string `json:"tip"` // main's tip as captured
73 Evidence string `json:"evidence"` // change.EvidenceFingerprint as captured
74 Families []JournalFamily `json:"families"`
75}
76
77// JournalFamily is one family's observation and the writes it would make.
78type JournalFamily struct {
79 Observed Observation `json:"observed"`
80 Branches *rebase.PendingBranches `json:"branches"`
81 Versions []*rebase.PendingVersion `json:"versions"`
82 Reports []JournalReport `json:"reports"`
83}
84
85// JournalReport is one change's report, and what it leaves out of the
86// family's observation: nothing for a report that holds it whole.
87type JournalReport struct {
88 Pending *rebase.PendingReport `json:"pending"`
89 Omitted []string `json:"omitted"`
90}
91
92// operationName is the shape of an operation's name, as a report's
93// operation field takes it.
94var operationName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]*$`)
95
96// check refuses a journal that does not agree with itself, or that
97// another repository, target or principal wrote.
98func (j *Journal) check(b binding) error {
99 switch {
100 case j.Schema != journalSchema:
101 return fmt.Errorf("its schema is %q, where %q is expected", j.Schema, journalSchema)
102 case j.Repository != b.Repository || j.Target != b.Target || j.Principal != b.Principal:
103 return fmt.Errorf("it belongs to %s on %s as %s, and this pass is for %s on %s as %s",
104 j.Target, j.Repository, j.Principal, b.Target, b.Repository, b.Principal)
105 case !operationName.MatchString(j.Operation) || len(j.Operation) > change.MaxOperation:
106 return fmt.Errorf("its operation %q is not a report's operation name", j.Operation)
107 case !rebase.IsObjectID(j.Tip):
108 return fmt.Errorf("its tip %q is not a full object ID", j.Tip)
109 case !hexOf(j.Evidence, 16):
110 return fmt.Errorf("its evidence %q is not an evidence fingerprint", j.Evidence)
111 }
112 for i, f := range j.Families {
113 if err := f.check(j); err != nil {
114 return fmt.Errorf("its family %d: %w", i, err)
115 }
116 }
117 return nil
118}
119
120func (f *JournalFamily) check(j *Journal) error {
121 o := f.Observed
122 switch {
123 case o.Action != restack && o.Action != hold:
124 return fmt.Errorf("its action is %q, where %q or %q is expected", o.Action, restack, hold)
125 case o.Result != change.RestackComplete && o.Result != change.RestackConflict && o.Result != change.RestackBlocked:
126 return fmt.Errorf("its result is %q", o.Result)
127 case len(o.Layers) == 0:
128 return errors.New("it observed no layer")
129 }
130 layers := map[string]ObservedLayer{} // change layers by ID
131 order := map[string]int{}
132 branches := map[string]ObservedLayer{}
133 for i, l := range o.Layers {
134 switch {
135 case l.Name == "":
136 return fmt.Errorf("its layer %d has no name", i)
137 case l.ID != "" && !change.ValidID(l.ID):
138 return fmt.Errorf("its layer %s names the change ID %q", l.Name, l.ID)
139 case l.ID != "" && (!rebase.IsObjectID(l.Record) || l.Version < 1):
140 return fmt.Errorf("its layer %s names no record commit and version", l.Name)
141 case l.ID == "" && (l.Record != "" || l.Version != 0):
142 return fmt.Errorf("its plain branch %s names a record", l.Name)
143 case !rebase.IsObjectID(l.Head):
144 return fmt.Errorf("its layer %s names the head %q", l.Name, l.Head)
145 case l.Branch != "" && !change.ValidBranch(l.Branch):
146 return fmt.Errorf("its layer %s names the branch %q", l.Name, l.Branch)
147 case l.BranchTip != "" && !rebase.IsObjectID(l.BranchTip):
148 return fmt.Errorf("its layer %s names the branch tip %q", l.Name, l.BranchTip)
149 case l.ID != "" && layers[l.ID].ID != "":
150 return fmt.Errorf("it observed %s twice", l.ID)
151 }
152 if l.ID != "" {
153 layers[l.ID], order[l.ID] = l, i
154 }
155 if l.Branch != "" {
156 branches[l.Branch] = l
157 }
158 }
159 if o.Failing != "" && layers[o.Failing].ID == "" {
160 return fmt.Errorf("its failing layer %s is none of its changes", o.Failing)
161 }
162
163 if (f.Branches != nil) != (o.Result == change.RestackComplete) || (f.Branches == nil) != (len(f.Versions) == 0) {
164 return errors.New("it has a branch push and versions exactly when it would restack")
165 }
166 news := map[string]string{}
167 if b := f.Branches; b != nil {
168 if b.Tip != j.Tip {
169 return fmt.Errorf("its branch push was prepared on %s, not the captured tip %s", b.Tip, j.Tip)
170 }
171 for _, u := range b.Updates {
172 l, ok := branches[u.Branch]
173 if !ok || l.BranchTip != u.Old {
174 return fmt.Errorf("its branch push moves %s from %s, which it did not observe", u.Branch, u.Old)
175 }
176 news[u.Branch] = u.New
177 }
178 if len(b.Updates) != len(o.Layers) {
179 return errors.New("its branch push does not move every layer")
180 }
181 }
182 last := -1
183 for _, v := range f.Versions {
184 l, ok := layers[v.ID]
185 switch {
186 case !ok:
187 return fmt.Errorf("it adds a version to %s, which is none of its changes", v.ID)
188 case !v.Restack():
189 return fmt.Errorf("its version of %s is not a restack's", v.ID)
190 case v.Old != l.Record || v.Branch != l.Branch || v.Head != news[l.Branch]:
191 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)
192 case order[v.ID] <= last:
193 return fmt.Errorf("its versions are not lower layers first")
194 }
195 last = order[v.ID]
196 }
197 reported := map[string]bool{}
198 for _, r := range f.Reports {
199 p := r.Pending
200 switch {
201 case p == nil:
202 return errors.New("it holds an empty report")
203 case layers[p.ID].ID == "":
204 return fmt.Errorf("it reports on %s, which is none of its changes", p.ID)
205 case reported[p.ID]:
206 return fmt.Errorf("it reports on %s twice", p.ID)
207 case p.Report.Operation != j.Operation || p.Report.Target != j.Target || p.Report.TargetTip != change.HeadPrefix+j.Tip:
208 return fmt.Errorf("its report on %s is not this operation's, on %s at %s", p.ID, j.Target, j.Tip)
209 }
210 reported[p.ID] = true
211 }
212 return nil
213}
214
215func hexOf(s string, n int) bool {
216 return len(s) == n && strings.Trim(s, "0123456789abcdef") == ""
217}
218
219// loadJournal reads the journal in the state directory: nil when there is
220// none. A journal that does not read, or that is another's, is an error,
221// and nothing it names is decided.
222func loadJournal(dir string, b binding) (*Journal, error) {
223 path := filepath.Join(dir, journalFile)
224 data, err := os.ReadFile(path)
225 switch {
226 case errors.Is(err, fs.ErrNotExist):
227 return nil, nil
228 case err != nil:
229 return nil, fmt.Errorf("reading the journal %s: %w", path, err)
230 }
231 var j Journal
232 if err := strictly(data, &j); err != nil {
233 return nil, fmt.Errorf("the journal %s does not read, so nothing it names is decided: %w", path, err)
234 }
235 if err := j.check(b); err != nil {
236 return nil, fmt.Errorf("the journal %s is refused, so nothing it names is decided: %w", path, err)
237 }
238 return &j, nil
239}
240
241// strictly reads data into v, and takes only what json.Marshal writes of
242// v, as rebase's kept forms are read: space between tokens is all that may
243// differ.
244func strictly(data []byte, v any) error {
245 dec := json.NewDecoder(bytes.NewReader(data))
246 dec.DisallowUnknownFields()
247 if err := dec.Decode(v); err != nil {
248 return err
249 }
250 var compact bytes.Buffer
251 if err := json.Compact(&compact, data); err != nil {
252 return err
253 }
254 again, err := json.Marshal(v)
255 if err != nil {
256 return err
257 }
258 if !bytes.Equal(compact.Bytes(), again) {
259 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")
260 }
261 return nil
262}
263
264// objects is every object the journal's writes would push: each prepared
265// head, each record commit and each report commit.
266func (j *Journal) objects() []string {
267 var all []string
268 for _, f := range j.Families {
269 if f.Branches != nil {
270 for _, u := range f.Branches.Updates {
271 all = append(all, u.New)
272 }
273 }
274 for _, v := range f.Versions {
275 all = append(all, v.Commit)
276 }
277 for _, r := range f.Reports {
278 all = append(all, r.Pending.Commit)
279 }
280 }
281 return all
282}
283
284// keep makes the journal durable before any of its writes is pushed: it
285// keeps every object the writes would push reachable in the scratch
286// repository, under refs/valley-restack/<operation>/, and then writes the
287// journal to the state directory, synced, in place of any before it.
288func keep(ctx context.Context, g rebase.Git, dir string, j *Journal) error {
289 if err := j.check(binding{Repository: j.Repository, Target: j.Target, Principal: j.Principal}); err != nil {
290 return fmt.Errorf("the journal cannot be kept: %w", err)
291 }
292 var stdin strings.Builder
293 for i, oid := range j.objects() {
294 fmt.Fprintf(&stdin, "update %s%s/%d %s\n", retainPrefix, j.Operation, i, oid)
295 }
296 cmd := g.Command(ctx, "update-ref", "--stdin")
297 cmd.Stdin = strings.NewReader(stdin.String())
298 if out, err := cmd.CombinedOutput(); err != nil {
299 return fmt.Errorf("could not keep the objects of operation %s: %v: %s", j.Operation, err, strings.TrimSpace(string(out)))
300 }
301 data, err := json.MarshalIndent(j, "", " ")
302 if err != nil {
303 return err
304 }
305 return writeDurably(dir, journalFile, append(data, '\n'))
306}
307
308// release lets go of what an operation kept in the scratch repository.
309func release(ctx context.Context, g rebase.Git, op string) error {
310 out, err := gitOut(ctx, g, "for-each-ref", "--format=delete %(refname)", retainPrefix+op+"/")
311 if err != nil {
312 return err
313 }
314 cmd := g.Command(ctx, "update-ref", "--stdin")
315 cmd.Stdin = strings.NewReader(out)
316 if out, err := cmd.CombinedOutput(); err != nil {
317 return fmt.Errorf("could not let go of the objects of operation %s: %v: %s", op, err, strings.TrimSpace(string(out)))
318 }
319 return nil
320}
321
322// writeDurably writes a file in dir through a synced temporary file, and
323// renames it into place, so a crash leaves the old file or the new one,
324// whole. The directory is synced after, so the rename is durable too.
325func writeDurably(dir, name string, data []byte) error {
326 tmp, err := os.CreateTemp(dir, name+".*")
327 if err != nil {
328 return err
329 }
330 defer os.Remove(tmp.Name())
331 _, err = tmp.Write(data)
332 if serr := tmp.Sync(); err == nil {
333 err = serr
334 }
335 if cerr := tmp.Close(); err == nil {
336 err = cerr
337 }
338 if err != nil {
339 return fmt.Errorf("writing %s in %s: %w", name, dir, err)
340 }
341 if err := os.Rename(tmp.Name(), filepath.Join(dir, name)); err != nil {
342 return err
343 }
344 d, err := os.Open(dir)
345 if err != nil {
346 return err
347 }
348 defer d.Close()
349 return d.Sync()
350}