gunk-dev/the-valley

pending.go

source7db83f346570main's published tip history
12.1 KiB
1// Keeping a write between building it and pushing it.
2//
3// A record commit or a report commit is written before it is pushed, so a
4// caller can keep the write somewhere durable first. After a crash, the
5// caller restores it and compares origin's ref with it: at Commit, origin
6// took the push; at Old, it did not, and the write may be pushed again.
7// A prepared family's branch push is kept the same way, as each branch's
8// old tip and prepared head, keyed by the branch's name.
9//
10// A kept write restores to the same write, or not at all. Its form names
11// everything its push checks, and a version's mode is part of that: a
12// restack append restored as a manual one would push without reading the
13// branch again. MarshalJSON writes the form. UnmarshalJSON restores only
14// a form MarshalJSON could have written, and refuses any other: one with
15// a field missing, unknown or named twice, and one that does not agree
16// with itself, such as a version whose record names another head.
17
18package rebase
19
20import (
21 "bytes"
22 "context"
23 "encoding/json"
24 "errors"
25 "fmt"
26 "strings"
27
28 "the-valley/change"
29)
30
31// The schemas of the forms a write is kept in.
32const (
33 pendingVersionSchema = "valley-pending-version/v1"
34 pendingReportSchema = "valley-pending-report/v1"
35 pendingBranchesSchema = "valley-pending-branches/v1"
36)
37
38// The modes a version is built in. The mode decides what its push checks.
39const (
40 manualMode = "manual" // BuildVersion's: the push is leased on the record ref
41 restackMode = "restack" // BuildRestack's: the push also needs origin's branch still at Head
42)
43
44// versionForm is the form a PendingVersion is kept in.
45type versionForm struct {
46 Schema string `json:"schema"`
47 Mode string `json:"mode"`
48 ID string `json:"change_id"`
49 Handle string `json:"handle"`
50 Ref string `json:"ref"`
51 Old string `json:"old"`
52 Commit string `json:"commit"`
53 Version int `json:"version"`
54 Head string `json:"head"`
55 Branch string `json:"branch"`
56 Record *change.Record `json:"record"`
57}
58
59// MarshalJSON writes p in the form it is kept in. It refuses a p that
60// UnmarshalJSON would refuse, so what it writes always restores.
61func (p PendingVersion) MarshalJSON() ([]byte, error) {
62 if err := p.check(); err != nil {
63 return nil, fmt.Errorf("the pending version cannot be kept: %w", err)
64 }
65 mode := manualMode
66 if p.restack {
67 mode = restackMode
68 }
69 return json.Marshal(versionForm{
70 Schema: pendingVersionSchema, Mode: mode, ID: p.ID, Handle: p.Handle, Ref: p.Ref, Old: p.Old,
71 Commit: p.Commit, Version: p.Version, Head: p.Head, Branch: p.Branch, Record: p.Record,
72 })
73}
74
75// UnmarshalJSON restores a PendingVersion that MarshalJSON wrote, in the
76// mode it was built in.
77func (p *PendingVersion) UnmarshalJSON(data []byte) error {
78 var f versionForm
79 if err := restore(data, &f); err != nil {
80 return fmt.Errorf("the pending version does not restore: %w", err)
81 }
82 q := PendingVersion{
83 ID: f.ID, Handle: f.Handle, Ref: f.Ref, Old: f.Old, Commit: f.Commit,
84 Record: f.Record, Version: f.Version, Head: f.Head, Branch: f.Branch, restack: f.Mode == restackMode,
85 }
86 switch {
87 case f.Schema != pendingVersionSchema:
88 return fmt.Errorf("the pending version does not restore: its schema is %q, where %q is expected", f.Schema, pendingVersionSchema)
89 case f.Mode != manualMode && f.Mode != restackMode:
90 return fmt.Errorf("the pending version does not restore: its mode is %q, where %q or %q is expected", f.Mode, manualMode, restackMode)
91 }
92 if err := q.check(); err != nil {
93 return fmt.Errorf("the pending version does not restore: %w", err)
94 }
95 *p = q
96 return nil
97}
98
99// check refuses a pending version that does not agree with itself. Its
100// record must be the change's, ready at the version it names as both its
101// active and its last, at its head and on its branch. A version is only
102// ever added to a record that exists, so Old names a commit.
103func (p *PendingVersion) check() error {
104 switch {
105 case !change.ValidID(p.ID):
106 return fmt.Errorf("%q is not a change ID", p.ID)
107 case len(p.Handle) < change.MinHandle || !strings.HasPrefix(p.ID, p.Handle):
108 return fmt.Errorf("%q is not a handle of %s", p.Handle, p.ID)
109 case p.Ref != change.Ref(Target, p.ID):
110 return fmt.Errorf("its ref %q is not the record ref of %s", p.Ref, p.ID)
111 case !IsObjectID(p.Old) || !IsObjectID(p.Commit) || !IsObjectID(p.Head):
112 return errors.New("the record it read, the record commit and the head are not each a full object ID")
113 case !change.ValidBranch(p.Branch):
114 return fmt.Errorf("%q is not a branch name", p.Branch)
115 case p.Record == nil:
116 return errors.New("it holds no record")
117 }
118 if err := p.Record.Check(); err != nil {
119 return fmt.Errorf("its record does not read: %w", err)
120 }
121 r, v := p.Record, p.Record.ActiveVersion()
122 if r.ChangeID != p.ID || r.Target != Target || r.State != change.Ready || r.Active != len(r.Versions) ||
123 v.N != p.Version || HeadOf(v) != p.Head || v.Branch != p.Branch {
124 return fmt.Errorf("its record does not hold %s ready at v%d, its last version, at %s on %s", p.ID, p.Version, short(p.Head), p.Branch)
125 }
126 return nil
127}
128
129// reportForm is the form a PendingReport is kept in.
130type reportForm struct {
131 Schema string `json:"schema"`
132 ID string `json:"change_id"`
133 Ref string `json:"ref"`
134 Old string `json:"old"`
135 Commit string `json:"commit"`
136 Report *change.RestackReport `json:"report"`
137}
138
139// MarshalJSON writes p in the form it is kept in. It refuses a p that
140// UnmarshalJSON would refuse, so what it writes always restores.
141func (p PendingReport) MarshalJSON() ([]byte, error) {
142 if err := p.check(); err != nil {
143 return nil, fmt.Errorf("the pending report cannot be kept: %w", err)
144 }
145 return json.Marshal(reportForm{Schema: pendingReportSchema, ID: p.ID, Ref: p.Ref, Old: p.Old, Commit: p.Commit, Report: p.Report})
146}
147
148// UnmarshalJSON restores a PendingReport that MarshalJSON wrote.
149func (p *PendingReport) UnmarshalJSON(data []byte) error {
150 var f reportForm
151 if err := restore(data, &f); err != nil {
152 return fmt.Errorf("the pending report does not restore: %w", err)
153 }
154 if f.Schema != pendingReportSchema {
155 return fmt.Errorf("the pending report does not restore: its schema is %q, where %q is expected", f.Schema, pendingReportSchema)
156 }
157 q := PendingReport{ID: f.ID, Ref: f.Ref, Old: f.Old, Commit: f.Commit, Report: f.Report}
158 if err := q.check(); err != nil {
159 return fmt.Errorf("the pending report does not restore: %w", err)
160 }
161 *p = q
162 return nil
163}
164
165// check refuses a pending report that does not agree with itself: its
166// report must read, and be about the change whose report ref it names.
167// Old is "" for a change that had no report.
168func (p *PendingReport) check() error {
169 switch {
170 case !change.ValidID(p.ID):
171 return fmt.Errorf("%q is not a change ID", p.ID)
172 case p.Ref != RestackPrefix+p.ID:
173 return fmt.Errorf("its ref %q is not the report ref of %s", p.Ref, p.ID)
174 case p.Old != "" && !IsObjectID(p.Old) || !IsObjectID(p.Commit):
175 return errors.New("the report it replaces and the report commit are not each a full object ID")
176 case p.Report == nil:
177 return errors.New("it holds no report")
178 }
179 if err := p.Report.Check(); err != nil {
180 return fmt.Errorf("its report does not read: %w", err)
181 }
182 if p.Report.ChangeID != p.ID {
183 return fmt.Errorf("its report is about %s, not %s", p.Report.ChangeID, p.ID)
184 }
185 return nil
186}
187
188// PendingBranches is a prepared family's branch push, kept: the target tip
189// the family was rebased onto, and each branch the one atomic push moves,
190// from the tip the capture read, which the push is leased on, to its
191// prepared head. It names branches, never a layer in memory, so it
192// restores whole after a crash. Origin holding every New then means the
193// push was taken, and holding every Old that it was not.
194type PendingBranches struct {
195 Tip string // the target tip the family was rebased onto
196 Updates []BranchUpdate // bottom first, one for each layer
197}
198
199// BranchUpdate is one branch a family's push moves.
200type BranchUpdate struct {
201 Branch string // the branch
202 Old string // its tip as captured, which the push is leased on
203 New string // the prepared head the push moves it to
204}
205
206// Branches is the prepared family's branch push, kept.
207func (p *Prepared) Branches() *PendingBranches {
208 b := &PendingBranches{Tip: p.Family.Tip}
209 for _, l := range p.Family.Layers {
210 b.Updates = append(b.Updates, BranchUpdate{Branch: l.Branch, Old: l.Tip, New: p.Heads[l]})
211 }
212 return b
213}
214
215// Push moves every branch at once, each leased on its Old: either every
216// branch moves or none does. It does not read origin first; Publish does.
217func (b *PendingBranches) Push(ctx context.Context, g Git) (Push, []RefusedRef) {
218 args := []string{"--atomic"}
219 for _, u := range b.Updates {
220 args = append(args, "--force-with-lease=refs/heads/"+u.Branch+":"+u.Old)
221 }
222 args = append(args, "origin")
223 for _, u := range b.Updates {
224 args = append(args, u.New+":refs/heads/"+u.Branch)
225 }
226 return push(ctx, g, args...)
227}
228
229// branchesForm is the form a PendingBranches is kept in.
230type branchesForm struct {
231 Schema string `json:"schema"`
232 Tip string `json:"tip"`
233 Updates []updateForm `json:"updates"`
234}
235
236type updateForm struct {
237 Branch string `json:"branch"`
238 Old string `json:"old"`
239 New string `json:"new"`
240}
241
242// MarshalJSON writes b in the form it is kept in. It refuses a b that
243// UnmarshalJSON would refuse, so what it writes always restores.
244func (b PendingBranches) MarshalJSON() ([]byte, error) {
245 if err := b.check(); err != nil {
246 return nil, fmt.Errorf("the pending branch push cannot be kept: %w", err)
247 }
248 f := branchesForm{Schema: pendingBranchesSchema, Tip: b.Tip, Updates: []updateForm{}}
249 for _, u := range b.Updates {
250 f.Updates = append(f.Updates, updateForm(u))
251 }
252 return json.Marshal(f)
253}
254
255// UnmarshalJSON restores a PendingBranches that MarshalJSON wrote.
256func (b *PendingBranches) UnmarshalJSON(data []byte) error {
257 var f branchesForm
258 if err := restore(data, &f); err != nil {
259 return fmt.Errorf("the pending branch push does not restore: %w", err)
260 }
261 if f.Schema != pendingBranchesSchema {
262 return fmt.Errorf("the pending branch push does not restore: its schema is %q, where %q is expected", f.Schema, pendingBranchesSchema)
263 }
264 q := PendingBranches{Tip: f.Tip}
265 for _, u := range f.Updates {
266 q.Updates = append(q.Updates, BranchUpdate(u))
267 }
268 if err := q.check(); err != nil {
269 return fmt.Errorf("the pending branch push does not restore: %w", err)
270 }
271 *b = q
272 return nil
273}
274
275// check refuses a branch push that does not agree with itself: it moves at
276// least one branch, no branch twice, and each from one full object ID to
277// another.
278func (b *PendingBranches) check() error {
279 if !IsObjectID(b.Tip) {
280 return fmt.Errorf("its tip %q is not a full object ID", b.Tip)
281 }
282 if len(b.Updates) == 0 {
283 return errors.New("it moves no branch")
284 }
285 seen := map[string]bool{}
286 for _, u := range b.Updates {
287 switch {
288 case !change.ValidBranch(u.Branch):
289 return fmt.Errorf("%q is not a branch name", u.Branch)
290 case seen[u.Branch]:
291 return fmt.Errorf("it moves %s twice", u.Branch)
292 case !IsObjectID(u.Old) || !IsObjectID(u.New):
293 return fmt.Errorf("the old tip and the new head of %s are not each a full object ID", u.Branch)
294 case u.Old == u.New:
295 return fmt.Errorf("it moves %s to the tip it is at", u.Branch)
296 }
297 seen[u.Branch] = true
298 }
299 return nil
300}
301
302// restore reads data into form, and takes only what json.Marshal writes
303// of form. Space between tokens is all that may differ, so a form kept
304// inside an indented file still restores. Anything else is refused: a
305// field missing, unknown or named twice, a value written another way, or
306// anything after the form.
307func restore(data []byte, form any) error {
308 dec := json.NewDecoder(bytes.NewReader(data))
309 dec.DisallowUnknownFields()
310 if err := dec.Decode(form); err != nil {
311 return err
312 }
313 var compact bytes.Buffer
314 if err := json.Compact(&compact, data); err != nil {
315 return err
316 }
317 again, err := json.Marshal(form)
318 if err != nil {
319 return err
320 }
321 if !bytes.Equal(compact.Bytes(), again) {
322 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")
323 }
324 return nil
325}