gunk-dev/the-valley

store.go

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