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