gunk-dev/the-valley

store.go

source81c223d4cefdmain's published tip history
21.8 KiB
1package export
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
11 "sort"
12 "strconv"
13 "strings"
14 "sync"
15 "syscall"
16)
17
18// ErrNoExport is Open's error when the receiver has activated no export.
19var ErrNoExport = errors.New("no export has been activated")
20
21// Store is a receiver's state directory. Its layout is:
22//
23// <state>/lock serialises activations
24// <state>/high-water the greatest sequence accepted
25// <state>/active symlink to exports/<sequence>
26// <state>/exports/<sequence>/ one generation, immutable once active
27// export.json
28// repos/<project>.git
29// <state>/staging/<sequence>/ one upload, until it is committed
30// bodies/<sha256>
31// export.json
32// tmp/<project>.git a repository being built
33// repos/<project>.git a repository once it is accepted
34// <state>/trash/ generations being deleted
35//
36// A generation is activated by renaming its staging directory into
37// exports/, writing high-water durably, and then swapping active
38// atomically. A reader resolves active once per request with Open and
39// keeps that generation, locked against deletion, until it releases it.
40// An old generation is deleted only once no reader holds it.
41//
42// The locks are flock(2) locks, so readers and activations in different
43// processes on one host are held to the same rule as goroutines are.
44type Store struct {
45 dir string
46 report func(error)
47}
48
49// Generation is one activated export: its sequence and its directory.
50type Generation struct {
51 Sequence int64
52 Dir string
53}
54
55// ExportPath is the generation's export.json.
56func (g Generation) ExportPath() string { return filepath.Join(g.Dir, ExportFile) }
57
58// Repo is the bare repository of the generation's project called name. ok
59// is false for a name that is not a project name.
60func (g Generation) Repo(name string) (path string, ok bool) {
61 if !ValidName(name) {
62 return "", false
63 }
64 return filepath.Join(g.Dir, "repos", name+".git"), true
65}
66
67// Export reads and validates the generation's export.json.
68func (g Generation) Export() (*Export, error) {
69 data, err := os.ReadFile(g.ExportPath())
70 if err != nil {
71 return nil, err
72 }
73 return Decode(data)
74}
75
76// Staging is one upload being received: its manifest and its directory.
77type Staging struct {
78 Manifest *Manifest
79 Dir string
80}
81
82// Bodies is the directory StageBody writes the upload's bodies to.
83func (st Staging) Bodies() string { return filepath.Join(st.Dir, "bodies") }
84
85// Body is where the body b is staged once it verified.
86func (st Staging) Body(b Body) string { return filepath.Join(st.Bodies(), b.SHA256) }
87
88// Repo is where the staged repository of the project called name goes.
89func (st Staging) Repo(name string) string {
90 return filepath.Join(st.Dir, "repos", name+".git")
91}
92
93// tmp is the directory a staged repository is built in.
94func (st Staging) tmp() string { return filepath.Join(st.Dir, "tmp") }
95
96// OpenStore opens the state directory at dir, creating its layout. It
97// finishes an activation a crash interrupted after high-water was written,
98// and deletes what no activation can use.
99//
100// report is told of each failure the store works past rather than
101// returns: deleting what no activation can use, which the next sweep
102// tries again, and syncing a swap of active to disk, which the next
103// OpenStore repeats after a crash. Neither undoes an activation. A
104// receiver logs them. A nil report drops them.
105func OpenStore(dir string, report func(error)) (*Store, error) {
106 abs, err := filepath.Abs(dir)
107 if err != nil {
108 return nil, err
109 }
110 if report == nil {
111 report = func(error) {}
112 }
113 s := &Store{dir: abs, report: report}
114 for _, d := range []string{abs, s.path("exports"), s.path("staging"), s.path("trash")} {
115 if err := os.MkdirAll(d, 0o755); err != nil {
116 return nil, err
117 }
118 }
119 unlock, err := s.lock()
120 if err != nil {
121 return nil, err
122 }
123 defer unlock()
124 if err := s.recover(); err != nil {
125 return nil, err
126 }
127 if err := s.sweep(); err != nil {
128 s.report(err)
129 }
130 return s, nil
131}
132
133// Dir is the state directory.
134func (s *Store) Dir() string { return s.dir }
135
136func (s *Store) path(parts ...string) string {
137 return filepath.Join(append([]string{s.dir}, parts...)...)
138}
139
140func (s *Store) exportDir(sequence int64) string {
141 return s.path("exports", strconv.FormatInt(sequence, 10))
142}
143
144// HighWater is the greatest sequence the store has accepted, 0 for none.
145func (s *Store) HighWater() (int64, error) {
146 data, err := os.ReadFile(s.path("high-water"))
147 if errors.Is(err, os.ErrNotExist) {
148 return 0, nil
149 }
150 if err != nil {
151 return 0, err
152 }
153 n, ok := decimal(strings.TrimSuffix(string(data), "\n"))
154 if !ok {
155 return 0, fmt.Errorf("%s holds %q, which is not a sequence", s.path("high-water"), data)
156 }
157 return n, nil
158}
159
160// active is the sequence active points at, and false when there is none.
161func (s *Store) active() (int64, bool, error) {
162 target, err := os.Readlink(s.path("active"))
163 if errors.Is(err, os.ErrNotExist) {
164 return 0, false, nil
165 }
166 if err != nil {
167 return 0, false, err
168 }
169 name, ok := strings.CutPrefix(target, "exports/")
170 n, valid := decimal(name)
171 if !ok || !valid {
172 return 0, false, fmt.Errorf("%s points at %q, which is no generation", s.path("active"), target)
173 }
174 return n, true, nil
175}
176
177// Open resolves active once and returns that generation, held against
178// deletion until release is called. A request serves everything from the
179// one generation it opened, so an activation during the request never
180// mixes two exports in one response. release may be called more than
181// once. Open's error is ErrNoExport before the first activation.
182func (s *Store) Open() (Generation, func(), error) {
183 for range 16 {
184 seq, ok, err := s.active()
185 if err != nil {
186 return Generation{}, func() {}, err
187 }
188 if !ok {
189 return Generation{}, func() {}, ErrNoExport
190 }
191 dir := s.exportDir(seq)
192 f, err := os.Open(dir)
193 if errors.Is(err, os.ErrNotExist) {
194 continue // active moved on and the generation was deleted
195 }
196 if err != nil {
197 return Generation{}, func() {}, err
198 }
199 if err := flock(f, syscall.LOCK_SH); err != nil {
200 f.Close()
201 return Generation{}, func() {}, err
202 }
203 // A deletion renames the generation away while it holds the lock
204 // exclusively, so a generation still at its path once this holds
205 // the lock is one no deletion will touch.
206 held, errHeld := f.Stat()
207 there, errThere := os.Stat(dir)
208 if errHeld != nil || errThere != nil || !os.SameFile(held, there) {
209 f.Close()
210 continue
211 }
212 var once sync.Once
213 release := func() { once.Do(func() { f.Close() }) }
214 return Generation{Sequence: seq, Dir: dir}, release, nil
215 }
216 return Generation{}, func() {}, errors.New("active moved on every time it was resolved")
217}
218
219// Stage is the staging directory for an upload whose manifest
220// VerifyManifest admitted. A manifest posted again finds its directory and
221// the bodies already staged in it. Staging a manifest discards the staging
222// directories of older ones. A manifest not newer than the high-water mark
223// is refused as replayed, and one older than another staged upload as
224// superseded.
225func (s *Store) Stage(m *Manifest) (Staging, error) {
226 unlock, err := s.lock()
227 if err != nil {
228 return Staging{}, err
229 }
230 defer unlock()
231 if err := s.checkNewer(m); err != nil {
232 return Staging{}, err
233 }
234 staged, err := s.staged()
235 if err != nil {
236 return Staging{}, err
237 }
238 for _, seq := range staged {
239 if seq > m.Sequence {
240 return Staging{}, refuse(CodeSuperseded, "the upload with sequence %d supersedes this one, %d", seq, m.Sequence)
241 }
242 if seq < m.Sequence {
243 if err := removeAll(s.path("staging", strconv.FormatInt(seq, 10))); err != nil {
244 return Staging{}, err
245 }
246 }
247 }
248 st := Staging{Manifest: m, Dir: s.path("staging", strconv.FormatInt(m.Sequence, 10))}
249 for _, d := range []string{st.Bodies(), filepath.Join(st.Dir, "repos")} {
250 if err := os.MkdirAll(d, 0o755); err != nil {
251 return Staging{}, err
252 }
253 }
254 return st, nil
255}
256
257// Inventory is the reply to the staged upload's manifest: the export the
258// store serves, the projects it holds, and the bodies still to be sent.
259// export.json is needed until it is staged. A bundle is needed until it is
260// staged or its repository is, unless the active generation holds its
261// project at the declared source tip, from which Activate carries it.
262func (s *Store) Inventory(st Staging) (Inventory, error) {
263 inv := Inventory{Schema: InventorySchema, Sequence: st.Manifest.Sequence, Holds: []Held{}, Needs: []Need{}}
264 held := map[string]string{}
265 g, release, err := s.Open()
266 defer release()
267 switch {
268 case errors.Is(err, ErrNoExport):
269 case err != nil:
270 return Inventory{}, err
271 default:
272 e, err := g.Export()
273 if err != nil {
274 return Inventory{}, err
275 }
276 digest, err := e.Digest()
277 if err != nil {
278 return Inventory{}, err
279 }
280 inv.Active = &Active{Sequence: g.Sequence, Digest: digest}
281 for _, p := range e.Projects {
282 inv.Holds = append(inv.Holds, Held{Project: p.Name, SourceTip: p.SourceTip})
283 held[p.Name] = p.SourceTip
284 }
285 }
286 needed := map[string]bool{}
287 need := func(b Body) {
288 if !needed[b.SHA256] && !exists(st.Body(b)) {
289 needed[b.SHA256] = true
290 inv.Needs = append(inv.Needs, Need{Name: b.Name, SHA256: b.SHA256, Size: b.Size})
291 }
292 }
293 if !exists(filepath.Join(st.Dir, ExportFile)) {
294 need(st.Manifest.File)
295 }
296 for _, p := range st.Manifest.Projects {
297 if !exists(st.Repo(p.Name)) && held[p.Name] != p.SourceTip {
298 need(p.Bundle)
299 }
300 }
301 return inv, nil
302}
303
304// Activate commits a staged upload: it makes it the active generation, or
305// refuses it and leaves the active one as it was. It holds the store's
306// lock throughout, so activations are serialised. In order, it:
307//
308// 1. refuses the upload unless its sequence is still greater than the
309// high-water mark and nothing newer is staged, and as incomplete,
310// with the bodies still needed, unless Inventory needs none;
311// 2. moves the staged export.json into place and holds it to the
312// manifest with CheckExport;
313// 3. gives every project its repository: one already staged, the staged
314// bundle through AcceptBundle, or the active generation's repository
315// at the same source tip through CarryRepo. A repository is built
316// under tmp/ and renamed into repos/ only once it is accepted;
317// 4. removes the bodies and tmp/, and checks that the staging directory
318// holds export.json and exactly those repositories, each at its
319// source tip;
320// 5. renames the staging directory into exports/;
321// 6. writes high-water durably;
322// 7. swaps active to the new generation;
323// 8. syncs the swap to disk, and deletes the generations no reader holds
324// and the stale staging directories.
325//
326// The activation has succeeded once step 7 is done: the new generation
327// serves, and high-water names it, so the next OpenStore restores it
328// after a crash. What fails in step 8 goes to the store's report, and
329// Activate still returns the new generation.
330//
331// A failure before step 7 is returned, and leaves the old generation
332// active. A crash before step 6 leaves the old generation active, and the
333// next OpenStore deletes the new one. After step 6 the sequence is
334// accepted: a commit retried after a failure between 6 and 7 is refused
335// as replayed. A crash between 6 and 7 is finished by the next OpenStore,
336// which swaps active to the generation high-water names.
337func (s *Store) Activate(ctx context.Context, st Staging) (Generation, error) {
338 unlock, err := s.lock()
339 if err != nil {
340 return Generation{}, err
341 }
342 defer unlock()
343 m := st.Manifest
344 if want := s.path("staging", strconv.FormatInt(m.Sequence, 10)); st.Dir != want {
345 return Generation{}, fmt.Errorf("the staging directory of sequence %d is %s, not %s", m.Sequence, want, st.Dir)
346 }
347 if err := s.checkNewer(m); err != nil {
348 return Generation{}, err
349 }
350 staged, err := s.staged()
351 if err != nil {
352 return Generation{}, err
353 }
354 if len(staged) == 0 || staged[len(staged)-1] != m.Sequence {
355 return Generation{}, refuse(CodeSuperseded, "the upload with sequence %d is not the newest staged", m.Sequence)
356 }
357
358 inv, err := s.Inventory(st)
359 if err != nil {
360 return Generation{}, err
361 }
362 if len(inv.Needs) > 0 {
363 e := refuse(CodeIncomplete, "the upload with sequence %d still needs %d bodies", m.Sequence, len(inv.Needs))
364 e.Needs = inv.Needs
365 return Generation{}, e
366 }
367
368 // A staged body that fails here is removed, so the inventory names it
369 // as needed again rather than keep a body that cannot be activated.
370 exportPath := filepath.Join(st.Dir, ExportFile)
371 if !exists(exportPath) {
372 if err := rename(st.Body(m.File), exportPath); err != nil {
373 return Generation{}, err
374 }
375 }
376 data, err := os.ReadFile(exportPath)
377 if err != nil {
378 return Generation{}, err
379 }
380 if _, err := m.CheckExport(data); err != nil {
381 os.Remove(exportPath)
382 return Generation{}, err
383 }
384
385 for _, p := range m.Projects {
386 if exists(st.Repo(p.Name)) {
387 continue
388 }
389 if err := s.build(ctx, st, p); err != nil {
390 return Generation{}, err
391 }
392 }
393
394 for _, d := range []string{st.Bodies(), st.tmp()} {
395 if err := removeAll(d); err != nil {
396 return Generation{}, err
397 }
398 }
399 if err := checkStaged(ctx, st); err != nil {
400 return Generation{}, err
401 }
402 for _, d := range []string{filepath.Join(st.Dir, "repos"), st.Dir} {
403 if err := syncPath(d); err != nil {
404 return Generation{}, err
405 }
406 }
407 dir := s.exportDir(m.Sequence)
408 if err := rename(st.Dir, dir); err != nil {
409 return Generation{}, err
410 }
411 for _, d := range []string{s.path("exports"), s.path("staging")} {
412 if err := syncPath(d); err != nil {
413 return Generation{}, err
414 }
415 }
416 if err := writeDurably(s.path("high-water"), []byte(strconv.FormatInt(m.Sequence, 10)+"\n")); err != nil {
417 return Generation{}, err
418 }
419 if err := s.swap(m.Sequence); err != nil {
420 return Generation{}, err
421 }
422 if err := syncPath(s.dir); err != nil {
423 s.report(fmt.Errorf("the swap of active to generation %d is not on disk: %w", m.Sequence, err))
424 }
425 if err := s.sweep(); err != nil {
426 s.report(err)
427 }
428 return Generation{Sequence: m.Sequence, Dir: dir}, nil
429}
430
431// build gives the project its repository in staging, from the staged
432// bundle through AcceptBundle or from the active generation through
433// carry. It builds the repository under tmp/ and renames it into repos/
434// only once it is accepted, so a repository in repos/ is always an
435// accepted one. A build a crash interrupted is left under tmp/, where the
436// next build of the project starts again.
437func (s *Store) build(ctx context.Context, st Staging, p ManifestProject) error {
438 tmp := filepath.Join(st.tmp(), p.Name+".git")
439 if err := removeAll(tmp); err != nil {
440 return err
441 }
442 if err := os.MkdirAll(st.tmp(), 0o755); err != nil {
443 return err
444 }
445 if bundle := st.Body(p.Bundle); exists(bundle) {
446 if err := AcceptBundle(ctx, bundle, tmp, p.SourceTip); err != nil {
447 os.Remove(bundle)
448 return err
449 }
450 } else if err := s.carry(ctx, p, tmp); err != nil {
451 return err
452 }
453 return rename(tmp, st.Repo(p.Name))
454}
455
456// carry gives a project the active generation's repository, when that
457// generation holds the project at the manifest's source tip.
458func (s *Store) carry(ctx context.Context, p ManifestProject, repo string) error {
459 g, release, err := s.Open()
460 defer release()
461 if err != nil && !errors.Is(err, ErrNoExport) {
462 return err
463 }
464 if err == nil {
465 e, err := g.Export()
466 if err != nil {
467 return err
468 }
469 for _, held := range e.Projects {
470 if held.Name == p.Name && held.SourceTip == p.SourceTip {
471 from, _ := g.Repo(p.Name)
472 return CarryRepo(ctx, from, repo, p.SourceTip)
473 }
474 }
475 }
476 return refuse(CodeIncomplete, "project %s has no staged bundle, and the receiver holds no repository of it at %s", p.Name, p.SourceTip)
477}
478
479// checkStaged holds the staging directory to step 4 of Activate.
480func checkStaged(ctx context.Context, st Staging) error {
481 entries, err := os.ReadDir(st.Dir)
482 if err != nil {
483 return err
484 }
485 var names []string
486 for _, e := range entries {
487 names = append(names, e.Name())
488 }
489 if strings.Join(names, " ") != ExportFile+" repos" {
490 return fmt.Errorf("the staging directory %s holds %q, not export.json and repos", st.Dir, names)
491 }
492 repos, err := os.ReadDir(filepath.Join(st.Dir, "repos"))
493 if err != nil {
494 return err
495 }
496 if len(repos) != len(st.Manifest.Projects) {
497 return fmt.Errorf("the staging directory holds %d repositories for %d projects", len(repos), len(st.Manifest.Projects))
498 }
499 for _, p := range st.Manifest.Projects {
500 refs, err := git(ctx, st.Repo(p.Name), "for-each-ref", "--format=%(objectname) %(refname)")
501 if err != nil {
502 return err
503 }
504 if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want {
505 return refuse(CodeBadBundle, "the staged repository of %s holds %q, not %q", p.Name, got, want)
506 }
507 }
508 return nil
509}
510
511// checkNewer refuses a manifest whose sequence is not greater than the
512// high-water mark.
513func (s *Store) checkNewer(m *Manifest) error {
514 hw, err := s.HighWater()
515 if err != nil {
516 return err
517 }
518 return checkSequence(m, hw)
519}
520
521// staged are the sequences with a staging directory, in ascending order.
522func (s *Store) staged() ([]int64, error) {
523 entries, err := os.ReadDir(s.path("staging"))
524 if err != nil {
525 return nil, err
526 }
527 var seqs []int64
528 for _, e := range entries {
529 if n, ok := decimal(e.Name()); ok {
530 seqs = append(seqs, n)
531 }
532 }
533 sort.Slice(seqs, func(i, j int) bool { return seqs[i] < seqs[j] })
534 return seqs, nil
535}
536
537// swap points active at the generation with sequence, atomically. The
538// caller syncs the state directory.
539func (s *Store) swap(sequence int64) error {
540 tmp := s.path("active." + random())
541 if err := os.Symlink("exports/"+strconv.FormatInt(sequence, 10), tmp); err != nil {
542 return err
543 }
544 if err := rename(tmp, s.path("active")); err != nil {
545 os.Remove(tmp)
546 return err
547 }
548 return nil
549}
550
551// recover finishes an activation interrupted between writing high-water
552// and swapping active: the generation high-water names is complete, since
553// it was renamed into exports/ before high-water was written.
554func (s *Store) recover() error {
555 hw, err := s.HighWater()
556 if err != nil || hw == 0 {
557 return err
558 }
559 seq, ok, err := s.active()
560 if err != nil {
561 return err
562 }
563 if ok && seq == hw {
564 return nil
565 }
566 if !exists(s.exportDir(hw)) {
567 return nil
568 }
569 if err := s.swap(hw); err != nil {
570 return err
571 }
572 return syncPath(s.dir)
573}
574
575// sweep deletes every generation but the active one that no reader holds,
576// every staging directory not newer than the high-water mark, and the
577// trash. A generation a reader holds is left for a later sweep. A
578// deletion that fails does not stop the others, and the next sweep tries
579// it again.
580func (s *Store) sweep() error {
581 active, ok, err := s.active()
582 if err != nil {
583 return fmt.Errorf("sweeping %s: %w", s.dir, err)
584 }
585 hw, err := s.HighWater()
586 if err != nil {
587 return fmt.Errorf("sweeping %s: %w", s.dir, err)
588 }
589 var errs []error
590 exports, err := os.ReadDir(s.path("exports"))
591 errs = append(errs, err)
592 for _, e := range exports {
593 if n, valid := decimal(e.Name()); valid && ok && n == active {
594 continue
595 }
596 errs = append(errs, s.delete(s.path("exports", e.Name())))
597 }
598 staging, err := os.ReadDir(s.path("staging"))
599 errs = append(errs, err)
600 for _, e := range staging {
601 if n, valid := decimal(e.Name()); !valid || n <= hw {
602 errs = append(errs, removeAll(s.path("staging", e.Name())))
603 }
604 }
605 trash, err := os.ReadDir(s.path("trash"))
606 errs = append(errs, err)
607 for _, e := range trash {
608 errs = append(errs, removeAll(s.path("trash", e.Name())))
609 }
610 if err := errors.Join(errs...); err != nil {
611 return fmt.Errorf("sweeping %s: %w", s.dir, err)
612 }
613 return nil
614}
615
616// delete removes the generation at dir unless a reader holds it. Holding
617// the generation's lock exclusively, it renames the generation into the
618// trash, so a reader that locks it afterwards finds it gone from its path.
619func (s *Store) delete(dir string) error {
620 f, err := os.Open(dir)
621 if errors.Is(err, os.ErrNotExist) {
622 return nil
623 }
624 if err != nil {
625 return err
626 }
627 defer f.Close()
628 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
629 return nil
630 } else if err != nil {
631 return err
632 }
633 trash := s.path("trash", filepath.Base(dir)+"-"+random())
634 if err := rename(dir, trash); err != nil {
635 return err
636 }
637 f.Close()
638 return removeAll(trash)
639}
640
641// lock takes the store's activation lock, waiting for it.
642func (s *Store) lock() (unlock func(), err error) {
643 f, err := os.OpenFile(s.path("lock"), os.O_RDWR|os.O_CREATE, 0o644)
644 if err != nil {
645 return nil, err
646 }
647 if err := flock(f, syscall.LOCK_EX); err != nil {
648 f.Close()
649 return nil, err
650 }
651 return func() { f.Close() }, nil
652}
653
654// flock takes a lock on f's open file description, which closing f
655// releases.
656func flock(f *os.File, how int) error {
657 for {
658 err := syscall.Flock(int(f.Fd()), how)
659 if !errors.Is(err, syscall.EINTR) {
660 return err
661 }
662 }
663}
664
665// writeDurably replaces the file at path with data: a temporary file
666// beside it, synced, renamed over it, and the directory synced.
667func writeDurably(path string, data []byte) error {
668 tmp := path + "." + random()
669 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
670 if err != nil {
671 return err
672 }
673 _, err = f.Write(data)
674 if err == nil {
675 err = syncFile(f)
676 }
677 if cerr := f.Close(); err == nil {
678 err = cerr
679 }
680 if err == nil {
681 err = rename(tmp, path)
682 }
683 if err != nil {
684 os.Remove(tmp)
685 return err
686 }
687 return syncPath(filepath.Dir(path))
688}
689
690// syncPath syncs the file or directory at path. Syncing a directory makes
691// its entries durable.
692func syncPath(path string) error {
693 f, err := os.Open(path)
694 if err != nil {
695 return err
696 }
697 defer f.Close()
698 return syncFile(f)
699}
700
701// The calls the store syncs, renames and deletes with. A test replaces
702// them to record their order or to make one fail.
703var (
704 syncFile = (*os.File).Sync
705 rename = os.Rename
706 removeAll = os.RemoveAll
707)
708
709func exists(path string) bool {
710 _, err := os.Lstat(path)
711 return err == nil
712}
713
714func random() string {
715 b := make([]byte, 8)
716 rand.Read(b)
717 return hex.EncodeToString(b)
718}