gunk-dev/the-valley

store.go

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