gunk-dev/the-valley

store.go

source53bd156eeb1bmain's published tip history
57.9 KiB
1package export
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "slices"
15 "sort"
16 "strconv"
17 "strings"
18 "sync"
19 "syscall"
20 "time"
21)
22
23// ErrNoExport is Open's error when the receiver has activated no export.
24var ErrNoExport = errors.New("no export has been activated")
25
26// ErrNoAuthorization is the error of reading the stored authorization
27// when the receiver has admitted none.
28var ErrNoAuthorization = errors.New("no authorization has been received")
29
30// ErrHeld is Prune's error when a reader holds the generation it would
31// delete repositories from. It deletes them once no reader does.
32var ErrHeld = errors.New("a reader holds the active generation")
33
34// StoreDescriptor is the one line of a store's descriptor file. The
35// descriptor is the store's entry point: the receiver and the server are
36// given its path, and the store's payloads are in the directory v2 beside
37// it. Binaries that read the first layout take a directory as the state
38// and refuse a file, so none of them can open this store, and none can
39// read its payloads as the first layout's public exports.
40const StoreDescriptor = "the-valley/web-store/v2"
41
42// Store is a receiver's store: a descriptor file and its payload
43// directory. Its layout is:
44//
45// <descriptor> one line, StoreDescriptor
46// <parent>/v2/ the payload directory, Dir:
47// lock serialises activations
48// authorization.lock serialises authorization writes
49// authorization the newest authorization admitted
50// high-water the greatest sequence accepted
51// current symlink to generations/<sequence>
52// generations/<sequence>/ one generation
53// export.json
54// repos/<project>.git
55// staging/<sequence>/ one upload, until it is committed
56// bodies/<sha256>
57// export.json
58// tmp/<project>.git a repository being built
59// repos/<project>.git a repository once it is accepted
60// trash/ what is being deleted: old
61// generations, discarded uploads,
62// withdrawn repositories, and
63// repositories past the cap
64//
65// <parent> is the directory the descriptor is in. The payload directory
66// holds no active symlink and no exports/, which the first layout served
67// from, so a binary of the first layout given it serves nothing either.
68//
69// staging/ and each upload in it are the receiver's alone, mode 0700, so
70// no other user reads a body before it is verified. generations/, every
71// generation in it, and authorization are readable by every user who can
72// reach them: directories 0755 and files 0644, or 0444 for git's
73// read-only objects, whatever the receiver's umask. Who can reach them is
74// the parent directory's own mode, which is the deployment's to set.
75//
76// A generation is activated by renaming its staging directory into
77// generations/, writing high-water durably, and then swapping current
78// atomically. A reader resolves current once per request with Open and
79// keeps that generation, locked against deletion, until it releases it.
80// An old generation is deleted only once no reader holds it.
81//
82// The authorization is a second stream beside the generations: its own
83// file, its own sequence and its own lock. Authorize replaces it durably
84// without the activation lock, so no upload, commit or check of a
85// repository holds it up. A generation holds a repository only for each
86// project the authorization names: Activate builds none for another, and
87// Prune deletes one the authorization withdrew, once no reader holds the
88// generation. export.json stays as it was signed.
89//
90// The locks are flock(2) locks, so readers and activations in different
91// processes on one host are held to the same rule as goroutines are. A
92// reader needs only to reach the payload directory and read it: the
93// receiver opens it with OpenStore, and a server with OpenReadOnly, which
94// writes nothing.
95type Store struct {
96 // MaxStorage is the most bytes the state directory may take on disk,
97 // as usage counts them, or 0 for no cap. Stage refuses a manifest
98 // whose upload, by checkStorage's estimate, would take the directory
99 // past it. Activate measures the directory after it builds each
100 // repository, and refuses an upload that took it past. Set it before
101 // the store is used.
102 //
103 // The cap is best effort. One repository's build can pass it by what
104 // the estimate missed, and a file a process still holds open after it
105 // is deleted takes space that no measure counts. The hard bound is the
106 // filesystem the state directory is on.
107 MaxStorage int64
108
109 dir string
110 report func(error)
111 // readOnly is set by OpenReadOnly. Such a store refuses Stage and
112 // Activate.
113 readOnly bool
114 // turn holds a token while one of the store's goroutines holds the
115 // lock, so the others wait their turn on it. authTurn is the same for
116 // authorization.lock.
117 turn chan struct{}
118 authTurn chan struct{}
119 // writing is the writers Writer admitted.
120 writing writing
121}
122
123// writing is the writers of staged bodies that Writer admitted. Stage and
124// Activate stop them before they delete the bodies they write.
125type writing struct {
126 mu sync.Mutex
127 // open is the sequence of the upload whose bodies take writers: the
128 // one Stage staged last, until Activate removes its bodies. 0 is none.
129 open int64
130 writers map[*writer]bool
131}
132
133type writer struct {
134 sequence int64
135 stop context.CancelCauseFunc
136 done chan struct{}
137}
138
139// RepoOverhead is what Stage counts for each repository an upload builds,
140// beyond the bundle it is fetched from or the repository it is carried
141// from: git's own files, the index of each pack, the commit-graph, and
142// the blocks small objects take when git keeps them loose. It is an
143// estimate. A repository of many objects takes more, and Activate's
144// measure after each build catches that.
145const RepoOverhead = 1 << 20
146
147// errReadOnly is the error of Stage and Activate on a store OpenReadOnly
148// opened.
149var errReadOnly = errors.New("the state directory is open read-only")
150
151// Generation is one activated export: its sequence and its directory.
152type Generation struct {
153 Sequence int64
154 Dir string
155}
156
157// ExportPath is the generation's export.json.
158func (g Generation) ExportPath() string { return filepath.Join(g.Dir, ExportFile) }
159
160// Repo is the bare repository of the generation's project called name. ok
161// is false for a name that is not a project name.
162func (g Generation) Repo(name string) (path string, ok bool) {
163 if !ValidName(name) {
164 return "", false
165 }
166 return filepath.Join(g.Dir, "repos", name+".git"), true
167}
168
169// Export reads and validates the generation's export.json.
170func (g Generation) Export() (*Export, error) {
171 data, err := os.ReadFile(g.ExportPath())
172 if err != nil {
173 return nil, err
174 }
175 return Decode(data)
176}
177
178// Staging is one upload being received: its manifest and its directory.
179type Staging struct {
180 Manifest *Manifest
181 Dir string
182}
183
184// Bodies is the directory StageBody writes the upload's bodies to.
185func (st Staging) Bodies() string { return filepath.Join(st.Dir, "bodies") }
186
187// Body is where the body b is staged once it verified.
188func (st Staging) Body(b Body) string { return filepath.Join(st.Bodies(), b.SHA256) }
189
190// Repo is where the staged repository of the project called name goes.
191func (st Staging) Repo(name string) string {
192 return filepath.Join(st.Dir, "repos", name+".git")
193}
194
195// tmp is the directory a staged repository is built in.
196func (st Staging) tmp() string { return filepath.Join(st.Dir, "tmp") }
197
198// OpenStore opens the store whose descriptor is at path, creating the
199// descriptor and the payload directory when path does not exist. path
200// that is a directory, as the first layout's state was, is refused. A new
201// store made over the first layout's state retires it (see
202// retireFirstLayout), so a binary of the first layout started there again
203// serves nothing, and a later start finishes a retirement a crash
204// stopped. Nothing else in the descriptor's directory is touched.
205// OpenStore finishes an activation a crash interrupted after high-water
206// was written, deletes what no activation can use, and deletes the
207// repositories the stored authorization withdrew. If it cannot finish
208// checking the generation that activation would make current, as when git
209// is killed, it deletes nothing and returns the error, and the receiver
210// tries again.
211//
212// report is told of each failure the store works past rather than
213// returns: deleting what no activation can use, which the next sweep
214// tries again; syncing a swap of current to disk, which the next
215// OpenStore repeats after a crash; a generation high-water names that
216// recovery found damaged and did not activate; and repositories a
217// withdrawal left, which the next authorization or activation deletes.
218// None undoes an activation that succeeded. A receiver logs them. A nil
219// report drops them.
220func OpenStore(path string, report func(error)) (*Store, error) {
221 abs, err := filepath.Abs(path)
222 if err != nil {
223 return nil, err
224 }
225 if report == nil {
226 report = func(error) {}
227 }
228 info, err := os.Lstat(abs)
229 missing := errors.Is(err, fs.ErrNotExist)
230 switch {
231 case missing:
232 case err != nil:
233 return nil, err
234 default:
235 if err := checkDescriptor(abs, info); err != nil {
236 return nil, err
237 }
238 }
239 if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
240 return nil, err
241 }
242 if err := retireFirstLayout(abs, missing, report); err != nil {
243 return nil, err
244 }
245 dir := payloadDir(abs)
246 s := &Store{dir: dir, report: report, turn: make(chan struct{}, 1), authTurn: make(chan struct{}, 1)}
247 for _, d := range []string{dir, s.path("generations"), s.path("staging"), s.path("trash")} {
248 if err := os.MkdirAll(d, 0o755); err != nil {
249 return nil, err
250 }
251 }
252 // The payload directory and generations/ are readable by every user
253 // who can reach them, whatever the umask; the descriptor's directory
254 // decides who can. So is serving.lock, which a server opens read-only.
255 for _, d := range []string{dir, s.path("generations")} {
256 if err := os.Chmod(d, 0o755); err != nil {
257 return nil, err
258 }
259 }
260 if err := touch(s.path(servingLock)); err != nil {
261 return nil, err
262 }
263 if err := os.Chmod(s.path("staging"), 0o700); err != nil {
264 return nil, err
265 }
266 unlock, err := s.lock(context.Background())
267 if err != nil {
268 return nil, err
269 }
270 defer unlock()
271 if err := s.recover(); err != nil {
272 return nil, err
273 }
274 if err := s.sweep(context.Background()); err != nil {
275 s.report(err)
276 }
277 if err := s.prune(context.Background()); err != nil {
278 s.report(fmt.Errorf("deleting withdrawn repositories: %w", err))
279 }
280 return s, nil
281}
282
283// payloadDir is the payload directory of the store whose descriptor is at
284// the absolute path descriptor.
285func payloadDir(descriptor string) string { return filepath.Join(filepath.Dir(descriptor), "v2") }
286
287// checkDescriptor holds the file at path, whose Lstat is info, to a
288// store's descriptor.
289func checkDescriptor(path string, info fs.FileInfo) error {
290 if info.IsDir() {
291 return fmt.Errorf("%s is a directory, as a state directory of the first store layout is; give the path of the store's descriptor file instead, such as %s, and the receiver makes a new store there", path, filepath.Join(path, "store"))
292 }
293 if !info.Mode().IsRegular() {
294 return fmt.Errorf("%s is not a regular file, so it is no store's descriptor", path)
295 }
296 data, err := os.ReadFile(path)
297 if err != nil {
298 return err
299 }
300 if string(data) != StoreDescriptor+"\n" {
301 return fmt.Errorf("%s does not hold %q, so it is no store's descriptor", path, StoreDescriptor)
302 }
303 return nil
304}
305
306// createDescriptor makes a new store at path: it makes the payload
307// directory, and writes the descriptor last, so a descriptor always has
308// its payload directory.
309func createDescriptor(path string) error {
310 if err := os.MkdirAll(payloadDir(path), 0o755); err != nil {
311 return err
312 }
313 return writeDurably(path, []byte(StoreDescriptor+"\n"))
314}
315
316// firstLayout are the names the first layout keeps in its state
317// directory, in the order retireFirstLayout deletes them: active first,
318// so a binary of that layout serves nothing once it is gone, and lock
319// last.
320var firstLayout = []string{"active", "high-water", "exports", "staging", "trash", "lock"}
321
322// retiringFile is the record, in the payload directory, of a retirement
323// of the first layout that has not finished: the names of firstLayout it
324// deletes, one per line.
325const retiringFile = "retiring"
326
327// retireStep, when it is set, is called before retireFirstLayout deletes
328// each name, and an error it returns stops the retirement there, as a
329// crash would. A test sets it.
330var retireStep func(name string) error
331
332// retireFirstLayout opens the descriptor at path, the first layout's
333// state beside it retired. It deletes only what it has proven is the
334// first layout's, and records that proof durably before it deletes
335// anything:
336//
337// - When the descriptor is missing, and the directory holds an active
338// symlink into exports/ or a high-water file of the first layout's
339// format, the names of firstLayout the directory then holds are the
340// first layout's. It records them in the payload directory, then
341// writes the descriptor, then deletes them.
342// - On a later start, it finishes a retirement only when that record is
343// there, deleting what is left of the names it lists, and removes the
344// record once all are gone.
345//
346// Otherwise it deletes nothing, so a new store made beside unrelated files
347// that share a name with the first layout's leaves them be. Before it
348// records or deletes anything, it takes the first layout's lock, which
349// that layout's receiver held for every activation, and fails while
350// another process holds it. Each step deletes whatever is left of its
351// name, so a retirement a crash stopped at any step is finished by the
352// next start.
353func retireFirstLayout(path string, missing bool, report func(error)) error {
354 dir, record := filepath.Dir(path), filepath.Join(payloadDir(path), retiringFile)
355 names, pending, err := readRetiring(record)
356 if err != nil {
357 return err
358 }
359 if !pending && missing {
360 if names, err = provenFirstLayout(dir); err != nil {
361 return err
362 }
363 }
364 if len(names) == 0 {
365 if missing {
366 return createDescriptor(path)
367 }
368 return nil
369 }
370 unlock, err := lockFirstLayout(dir, names)
371 if err != nil {
372 return err
373 }
374 defer unlock()
375 if !pending {
376 if err := os.MkdirAll(payloadDir(path), 0o755); err != nil {
377 return err
378 }
379 if err := writeDurably(record, []byte(strings.Join(names, "\n")+"\n")); err != nil {
380 return err
381 }
382 }
383 if missing {
384 if err := createDescriptor(path); err != nil {
385 return err
386 }
387 }
388 for _, name := range names {
389 if retireStep != nil {
390 if err := retireStep(name); err != nil {
391 return fmt.Errorf("retiring the first layout's %s: %w", filepath.Join(dir, name), err)
392 }
393 }
394 if err := os.RemoveAll(filepath.Join(dir, name)); err != nil {
395 return fmt.Errorf("retiring the first layout's %s: %w", filepath.Join(dir, name), err)
396 }
397 if name == "active" {
398 if err := syncPath(dir); err != nil {
399 return err
400 }
401 }
402 }
403 if err := syncPath(dir); err != nil {
404 return err
405 }
406 if err := os.Remove(record); err != nil {
407 return err
408 }
409 if err := syncPath(payloadDir(path)); err != nil {
410 return err
411 }
412 report(fmt.Errorf("%s held state of the first store layout, which is retired; the publisher's next pass sends everything again", dir))
413 return nil
414}
415
416// readRetiring reads the record of a retirement still to finish. pending
417// is false when there is none. A record that names anything but the
418// first layout's names is an error, and nothing is deleted.
419func readRetiring(record string) (names []string, pending bool, err error) {
420 data, err := os.ReadFile(record)
421 if errors.Is(err, fs.ErrNotExist) {
422 return nil, false, nil
423 }
424 if err != nil {
425 return nil, false, err
426 }
427 for _, name := range strings.Split(strings.TrimSuffix(string(data), "\n"), "\n") {
428 if !slices.Contains(firstLayout, name) {
429 return nil, false, fmt.Errorf("%s names %q, which is not of the first store layout; nothing is retired", record, name)
430 }
431 names = append(names, name)
432 }
433 return names, true, nil
434}
435
436// provenFirstLayout are the names of firstLayout that dir holds, in
437// firstLayout's order, when dir holds the first layout: an active symlink
438// to exports/<sequence>, or a high-water file holding a sequence and a
439// newline, as that layout wrote them. Without either, there are none.
440func provenFirstLayout(dir string) ([]string, error) {
441 proven := false
442 if target, err := os.Readlink(filepath.Join(dir, "active")); err == nil {
443 seq, ok := strings.CutPrefix(target, "exports/")
444 _, valid := decimal(seq)
445 proven = ok && valid
446 }
447 if info, err := os.Lstat(filepath.Join(dir, "high-water")); !proven && err == nil && info.Mode().IsRegular() && info.Size() <= 21 {
448 data, err := os.ReadFile(filepath.Join(dir, "high-water"))
449 if err != nil {
450 return nil, err
451 }
452 seq, ok := strings.CutSuffix(string(data), "\n")
453 n, valid := decimal(seq)
454 proven = ok && valid && n > 0
455 }
456 if !proven {
457 return nil, nil
458 }
459 var names []string
460 for _, name := range firstLayout {
461 if _, err := os.Lstat(filepath.Join(dir, name)); err == nil {
462 names = append(names, name)
463 } else if !errors.Is(err, fs.ErrNotExist) {
464 return nil, err
465 }
466 }
467 return names, nil
468}
469
470// lockFirstLayout takes the first layout's lock, when names hold it and it
471// is there still, and fails while another process holds it.
472func lockFirstLayout(dir string, names []string) (func(), error) {
473 if !slices.Contains(names, "lock") {
474 return func() {}, nil
475 }
476 path := filepath.Join(dir, "lock")
477 f, err := os.OpenFile(path, os.O_RDWR, 0)
478 if errors.Is(err, fs.ErrNotExist) {
479 return func() {}, nil
480 }
481 if err != nil {
482 return nil, err
483 }
484 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
485 f.Close()
486 return nil, fmt.Errorf("%s holds state of the first store layout, and another process holds its lock, %s; stop the receiver of the first layout, then start this one again", dir, path)
487 } else if err != nil {
488 f.Close()
489 return nil, err
490 }
491 return func() { f.Close() }, nil
492}
493
494// OpenReadOnly opens the store whose descriptor is at path for reading
495// alone, as a server does. It writes nothing: it creates no directory,
496// takes no lock but a reader's shared one on the generation it opens, and
497// neither recovers an interrupted activation nor sweeps, which the
498// receiver's OpenStore does. So a server may run as a user that can only
499// read the receiver's store. Until the receiver finishes an interrupted
500// activation, a reader is served the generation current points at. The
501// descriptor and the payload directory must exist already, and path that
502// is a directory is refused.
503func OpenReadOnly(path string) (*Store, error) {
504 abs, err := filepath.Abs(path)
505 if err != nil {
506 return nil, err
507 }
508 info, err := os.Lstat(abs)
509 if err != nil {
510 return nil, err
511 }
512 if err := checkDescriptor(abs, info); err != nil {
513 return nil, err
514 }
515 dir := payloadDir(abs)
516 info, err = os.Stat(dir)
517 if err != nil {
518 return nil, err
519 }
520 if !info.IsDir() {
521 return nil, fmt.Errorf("%s is not a directory", dir)
522 }
523 return &Store{dir: dir, report: func(error) {}, readOnly: true, turn: make(chan struct{}, 1), authTurn: make(chan struct{}, 1)}, nil
524}
525
526// Dir is the store's payload directory.
527func (s *Store) Dir() string { return s.dir }
528
529func (s *Store) path(parts ...string) string {
530 return filepath.Join(append([]string{s.dir}, parts...)...)
531}
532
533func (s *Store) generationDir(sequence int64) string {
534 return s.path("generations", strconv.FormatInt(sequence, 10))
535}
536
537// HighWater is the greatest sequence the store has accepted, 0 for none.
538func (s *Store) HighWater() (int64, error) {
539 data, err := os.ReadFile(s.path("high-water"))
540 if errors.Is(err, os.ErrNotExist) {
541 return 0, nil
542 }
543 if err != nil {
544 return 0, err
545 }
546 n, ok := decimal(strings.TrimSuffix(string(data), "\n"))
547 if !ok {
548 return 0, fmt.Errorf("%s holds %q, which is not a sequence", s.path("high-water"), data)
549 }
550 return n, nil
551}
552
553// active is the sequence current points at, and false when there is none.
554func (s *Store) active() (int64, bool, error) {
555 target, err := os.Readlink(s.path("current"))
556 if errors.Is(err, os.ErrNotExist) {
557 return 0, false, nil
558 }
559 if err != nil {
560 return 0, false, err
561 }
562 name, ok := strings.CutPrefix(target, "generations/")
563 n, valid := decimal(name)
564 if !ok || !valid {
565 return 0, false, fmt.Errorf("%s points at %q, which is no generation", s.path("current"), target)
566 }
567 return n, true, nil
568}
569
570// Active is the sequence of the generation active points at. It reads
571// active without opening the generation, so it holds nothing, and the
572// generation it names may be deleted once active moves on. Its error is
573// ErrNoExport before the first activation.
574func (s *Store) Active() (int64, error) {
575 seq, ok, err := s.active()
576 if err == nil && !ok {
577 err = ErrNoExport
578 }
579 return seq, err
580}
581
582// Open resolves active once and returns that generation, held against
583// deletion until release is called. A request serves everything from the
584// one generation it opened, so an activation during the request never
585// mixes two exports in one response. release may be called more than
586// once. Open's error is ErrNoExport before the first activation.
587func (s *Store) Open() (Generation, func(), error) {
588 for range 16 {
589 seq, ok, err := s.active()
590 if err != nil {
591 return Generation{}, func() {}, err
592 }
593 if !ok {
594 return Generation{}, func() {}, ErrNoExport
595 }
596 dir := s.generationDir(seq)
597 f, err := os.Open(dir)
598 if errors.Is(err, os.ErrNotExist) {
599 continue // active moved on and the generation was deleted
600 }
601 if err != nil {
602 return Generation{}, func() {}, err
603 }
604 if err := flock(f, syscall.LOCK_SH); err != nil {
605 f.Close()
606 return Generation{}, func() {}, err
607 }
608 // A deletion renames the generation away while it holds the lock
609 // exclusively, so a generation still at its path once this holds
610 // the lock is one no deletion will touch.
611 held, errHeld := f.Stat()
612 there, errThere := os.Stat(dir)
613 if errHeld != nil || errThere != nil || !os.SameFile(held, there) {
614 f.Close()
615 continue
616 }
617 var once sync.Once
618 release := func() { once.Do(func() { f.Close() }) }
619 return Generation{Sequence: seq, Dir: dir}, release, nil
620 }
621 return Generation{}, func() {}, errors.New("active moved on every time it was resolved")
622}
623
624// Stage is the staging directory for an upload whose manifest
625// VerifyManifest admitted. A manifest posted again finds its directory and
626// the bodies already staged in it. Staging a manifest discards the staging
627// directories of older ones: it stops their writers (see Writer), waits
628// until each has closed its files, and only then deletes the directories.
629// A manifest not newer than the high-water mark is refused as replayed,
630// and one older than another staged upload as superseded. One whose
631// upload would take the state directory past MaxStorage is refused as
632// too-large (see checkStorage), but first Stage sweeps the generations no
633// reader holds any more, and measures again.
634//
635// Stage waits for the store's lock, measures the state directory, sweeps,
636// and waits for the writers it stops, each only until ctx is done. It
637// checks ctx before each directory it deletes or creates, and the sweep
638// and each deletion stop part way once ctx is done. So once ctx is done,
639// Stage releases the lock and deletes and creates nothing more. A deletion
640// it stops part way is left in the trash, for the next sweep.
641func (s *Store) Stage(ctx context.Context, m *Manifest) (Staging, error) {
642 if s.readOnly {
643 return Staging{}, errReadOnly
644 }
645 unlock, err := s.lock(ctx)
646 if err != nil {
647 return Staging{}, err
648 }
649 defer unlock()
650 if err := s.checkNewer(m); err != nil {
651 return Staging{}, err
652 }
653 staged, err := s.staged()
654 if err != nil {
655 return Staging{}, err
656 }
657 var older []string
658 for _, seq := range staged {
659 if seq > m.Sequence {
660 return Staging{}, refuse(CodeSuperseded, "the upload with sequence %d supersedes this one, %d", seq, m.Sequence)
661 }
662 if seq < m.Sequence {
663 older = append(older, s.path("staging", strconv.FormatInt(seq, 10)))
664 }
665 }
666 st := Staging{Manifest: m, Dir: s.path("staging", strconv.FormatInt(m.Sequence, 10))}
667 discard := append(older, st.Dir)
668 err = s.checkStorage(ctx, m, discard)
669 if e := (*Error)(nil); errors.As(err, &e) && e.Code == CodeTooLarge && ctx.Err() == nil {
670 // A generation a reader held at the last sweep may be free now.
671 if err := s.sweep(ctx); err != nil {
672 s.report(err)
673 }
674 err = s.checkStorage(ctx, m, discard)
675 }
676 if err != nil {
677 return Staging{}, err
678 }
679 // Past here Stage deletes and stages, which a client gone away or out
680 // of time no longer wants.
681 if err := ctx.Err(); err != nil {
682 return Staging{}, err
683 }
684 if err := s.discard(ctx, m.Sequence); err != nil {
685 return Staging{}, err
686 }
687 for _, dir := range older {
688 if err := ctx.Err(); err != nil {
689 return Staging{}, err
690 }
691 if err := s.remove(ctx, dir); err != nil {
692 return Staging{}, err
693 }
694 }
695 for _, d := range []string{st.Dir, st.Bodies(), filepath.Join(st.Dir, "repos")} {
696 if err := ctx.Err(); err != nil {
697 return Staging{}, err
698 }
699 if err := os.MkdirAll(d, 0o700); err != nil {
700 return Staging{}, err
701 }
702 if err := os.Chmod(d, 0o700); err != nil {
703 return Staging{}, err
704 }
705 }
706 return st, nil
707}
708
709// Writer admits a writer of the staged upload st's bodies, such as a
710// request running StageBody, and returns the writer's context and done.
711// The context is done once ctx is, and once the store discards st's
712// bodies: when a newer manifest's Stage discards the upload, its cause is
713// a superseded refusal, and when Activate removes the bodies of the upload
714// it commits, a no-manifest refusal. Stage and Activate wait for done
715// before they delete anything, so a writer stops once its context is done,
716// closes and removes every file it opened, and only then calls done.
717// Writer refuses a writer of bodies already discarded with one of those
718// refusals.
719func (s *Store) Writer(ctx context.Context, st Staging) (context.Context, func(), error) {
720 seq := st.Manifest.Sequence
721 s.writing.mu.Lock()
722 defer s.writing.mu.Unlock()
723 if s.writing.open != seq {
724 return nil, nil, discarded(seq, s.writing.open)
725 }
726 wctx, stop := context.WithCancelCause(ctx)
727 w := &writer{sequence: seq, stop: stop, done: make(chan struct{})}
728 if s.writing.writers == nil {
729 s.writing.writers = map[*writer]bool{}
730 }
731 s.writing.writers[w] = true
732 done := sync.OnceFunc(func() {
733 stop(nil)
734 s.writing.mu.Lock()
735 delete(s.writing.writers, w)
736 s.writing.mu.Unlock()
737 close(w.done)
738 })
739 return wctx, done, nil
740}
741
742// discard opens the bodies of the upload with sequence open to writers, or
743// no upload's when open is 0. It stops the writers of every other upload's
744// bodies, and waits until each has called done, or until ctx is done.
745func (s *Store) discard(ctx context.Context, open int64) error {
746 s.writing.mu.Lock()
747 s.writing.open = open
748 var stopped []*writer
749 for w := range s.writing.writers {
750 if w.sequence != open {
751 w.stop(discarded(w.sequence, open))
752 stopped = append(stopped, w)
753 }
754 }
755 s.writing.mu.Unlock()
756 for _, w := range stopped {
757 select {
758 case <-w.done:
759 case <-ctx.Done():
760 return fmt.Errorf("waiting for the writers of the upload with sequence %d to stop: %w", w.sequence, ctx.Err())
761 }
762 }
763 return ctx.Err()
764}
765
766// discarded is the refusal of a writer of the upload with sequence once
767// the bodies of the upload with sequence open take writers instead.
768func discarded(sequence, open int64) error {
769 if sequence < open {
770 return refuse(CodeSuperseded, "the upload with sequence %d supersedes this one, %d", open, sequence)
771 }
772 return refuse(CodeNoManifest, "the upload with sequence %d takes no more bodies", sequence)
773}
774
775// Inventory is the reply to the staged upload's manifest: the export the
776// store serves, the projects it holds, and the bodies still to be sent.
777// export.json is needed until it is staged. A bundle is needed until it is
778// staged or its repository is, unless the active generation holds its
779// project at the declared source tip, from which Activate carries it.
780//
781// A bundle is needed only for a project the stored authorization names.
782// The receiver builds no repository of any other, so with no stored
783// authorization no bundle is needed. A project whose repository a
784// withdrawal deleted is not held.
785func (s *Store) Inventory(st Staging) (Inventory, error) {
786 inv := Inventory{Schema: InventorySchema, Sequence: st.Manifest.Sequence, Holds: []Held{}, Needs: []Need{}}
787 named, err := s.named()
788 if err != nil {
789 return Inventory{}, err
790 }
791 active, held, err := s.Holdings()
792 if err != nil {
793 return Inventory{}, err
794 }
795 inv.Active = active
796 var names []string
797 for name := range held {
798 names = append(names, name)
799 }
800 sort.Strings(names)
801 for _, name := range names {
802 inv.Holds = append(inv.Holds, Held{Project: name, SourceTip: held[name]})
803 }
804 needed := map[string]bool{}
805 need := func(b Body) {
806 if !needed[b.SHA256] && !exists(st.Body(b)) {
807 needed[b.SHA256] = true
808 inv.Needs = append(inv.Needs, Need{Name: b.Name, SHA256: b.SHA256, Size: b.Size})
809 }
810 }
811 if !exists(filepath.Join(st.Dir, ExportFile)) {
812 need(st.Manifest.File)
813 }
814 for _, p := range st.Manifest.Projects {
815 if named(p.Name, p.Identity) && !exists(st.Repo(p.Name)) && held[p.Name] != p.SourceTip {
816 need(p.Bundle)
817 }
818 }
819 return inv, nil
820}
821
822// Activate commits a staged upload: it makes it the active generation, or
823// refuses it and leaves the current one as it was. It holds the store's
824// lock throughout, so activations are serialised. It waits for the lock
825// until ctx is done, and the git it runs is stopped once ctx is done. In
826// order, it:
827//
828// 1. refuses the upload unless its sequence is still greater than the
829// high-water mark and nothing newer is staged, and as incomplete,
830// with the bodies still needed, unless Inventory needs none;
831// 2. moves the staged export.json into place, readable by every user,
832// and holds it to the manifest with CheckExport;
833// 3. gives every project the stored authorization names its repository,
834// and removes a staged one of any other: one already staged, the staged
835// bundle through AcceptBundle, or the active generation's repository
836// at the same source tip through CarryRepo. A repository is built
837// under tmp/, made readable by every user, every file and directory
838// of it is synced to disk, and only then is it renamed into repos/.
839// Once each is in repos/, the state directory is held to MaxStorage:
840// a repository that took it past the cap is moved to the trash, and
841// the upload is refused as too-large;
842// 4. stops the writers of the upload's bodies, and waits until each has
843// closed its files (see Writer); removes the bodies and tmp/; and
844// checks that the staging directory holds export.json and exactly
845// those repositories, each at its source tip;
846// 5. stops if ctx is done; makes repos/ and the staging directory
847// readable by every user, syncs export.json, repos/ and the staging
848// directory, renames the staging directory into exports/, and syncs
849// both parents;
850// 6. writes high-water durably, once every file and directory of the
851// generation is on disk;
852// 7. swaps current to the new generation;
853// 8. syncs the swap to disk, deletes the generations no reader holds and
854// the stale staging directories, and prunes the repositories of
855// projects the authorization withdrew meanwhile, until ctx is done.
856//
857// The activation has succeeded once step 7 is done: the new generation
858// serves, and high-water names it, so the next OpenStore restores it
859// after a crash. What fails in step 8 goes to the store's report, and
860// Activate still returns the new generation.
861//
862// A failure before step 7 is returned, and leaves the old generation
863// active. A crash before step 6 leaves the old generation active, and the
864// next OpenStore deletes the new one. After step 6 the sequence is
865// accepted: a commit retried after a failure between 6 and 7 is refused
866// as replayed. A crash between 6 and 7 is finished by the next OpenStore,
867// which swaps current to the generation high-water names.
868func (s *Store) Activate(ctx context.Context, st Staging) (Generation, error) {
869 if s.readOnly {
870 return Generation{}, errReadOnly
871 }
872 unlock, err := s.lock(ctx)
873 if err != nil {
874 return Generation{}, err
875 }
876 defer unlock()
877 m := st.Manifest
878 if want := s.path("staging", strconv.FormatInt(m.Sequence, 10)); st.Dir != want {
879 return Generation{}, fmt.Errorf("the staging directory of sequence %d is %s, not %s", m.Sequence, want, st.Dir)
880 }
881 if err := s.checkNewer(m); err != nil {
882 return Generation{}, err
883 }
884 staged, err := s.staged()
885 if err != nil {
886 return Generation{}, err
887 }
888 if len(staged) == 0 || staged[len(staged)-1] != m.Sequence {
889 return Generation{}, refuse(CodeSuperseded, "the upload with sequence %d is not the newest staged", m.Sequence)
890 }
891
892 inv, err := s.Inventory(st)
893 if err != nil {
894 return Generation{}, err
895 }
896 if len(inv.Needs) > 0 {
897 e := refuse(CodeIncomplete, "the upload with sequence %d still needs %d bodies", m.Sequence, len(inv.Needs))
898 e.Needs = inv.Needs
899 return Generation{}, e
900 }
901
902 // A staged body that fails here is removed, so the inventory names it
903 // as needed again rather than keep a body that cannot be activated.
904 exportPath := filepath.Join(st.Dir, ExportFile)
905 if !exists(exportPath) {
906 if err := rename(st.Body(m.File), exportPath); err != nil {
907 return Generation{}, err
908 }
909 }
910 if err := os.Chmod(exportPath, 0o644); err != nil {
911 return Generation{}, err
912 }
913 data, err := os.ReadFile(exportPath)
914 if err != nil {
915 return Generation{}, err
916 }
917 if _, err := m.CheckExport(data); err != nil {
918 os.Remove(exportPath)
919 return Generation{}, err
920 }
921
922 // A repository is built for each project the stored authorization
923 // names, and for no other: one staged for a project it withdrew since
924 // is removed.
925 named, err := s.named()
926 if err != nil {
927 return Generation{}, err
928 }
929 var want []ManifestProject
930 for _, p := range m.Projects {
931 if !named(p.Name, p.Identity) {
932 if err := s.remove(ctx, st.Repo(p.Name)); err != nil {
933 return Generation{}, err
934 }
935 continue
936 }
937 want = append(want, p)
938 if exists(st.Repo(p.Name)) {
939 continue
940 }
941 if err := s.build(ctx, st, p); err != nil {
942 return Generation{}, err
943 }
944 if err := s.checkUsage(ctx); err != nil {
945 // Out of repos/ at once, so no part of it is taken for an
946 // accepted repository, even when ctx stops its deletion.
947 if rerr := s.remove(ctx, st.Repo(p.Name)); rerr != nil {
948 return Generation{}, errors.Join(err, rerr)
949 }
950 return Generation{}, err
951 }
952 }
953
954 if err := s.discard(ctx, 0); err != nil {
955 return Generation{}, err
956 }
957 for _, d := range []string{st.Bodies(), st.tmp()} {
958 if err := removeAll(ctx, d); err != nil {
959 return Generation{}, err
960 }
961 }
962 if err := checkStaged(ctx, st, want); err != nil {
963 return Generation{}, err
964 }
965 // Past here the upload is made the active generation, which a client
966 // gone away or out of time no longer wants.
967 if err := ctx.Err(); err != nil {
968 return Generation{}, err
969 }
970 for _, d := range []string{filepath.Join(st.Dir, "repos"), st.Dir} {
971 if err := os.Chmod(d, 0o755); err != nil {
972 return Generation{}, err
973 }
974 }
975 for _, p := range []string{exportPath, filepath.Join(st.Dir, "repos"), st.Dir} {
976 if err := syncPath(p); err != nil {
977 return Generation{}, err
978 }
979 }
980 dir := s.generationDir(m.Sequence)
981 if err := rename(st.Dir, dir); err != nil {
982 return Generation{}, err
983 }
984 for _, d := range []string{s.path("generations"), s.path("staging")} {
985 if err := syncPath(d); err != nil {
986 return Generation{}, err
987 }
988 }
989 if err := writeDurably(s.path("high-water"), []byte(strconv.FormatInt(m.Sequence, 10)+"\n")); err != nil {
990 return Generation{}, err
991 }
992 if err := s.swap(m.Sequence); err != nil {
993 return Generation{}, err
994 }
995 if err := syncPath(s.dir); err != nil {
996 s.report(fmt.Errorf("the swap of current to generation %d is not on disk: %w", m.Sequence, err))
997 }
998 if err := s.sweep(ctx); err != nil {
999 s.report(err)
1000 }
1001 // The authorization may have withdrawn a project while this built it.
1002 if err := s.prune(ctx); err != nil && !errors.Is(err, ErrHeld) {
1003 s.report(fmt.Errorf("deleting withdrawn repositories: %w", err))
1004 }
1005 return Generation{Sequence: m.Sequence, Dir: dir}, nil
1006}
1007
1008// build gives the project its repository in staging, from the staged
1009// bundle through AcceptBundle or from the active generation through
1010// carry. It builds the repository under tmp/, makes it readable by every
1011// user, syncs it to disk, and only then renames it into repos/, so a
1012// repository in repos/ is always an accepted one, whole on disk. A build
1013// a crash interrupted, or one ctx stopped, is left under tmp/, where the
1014// next build of the project starts again. A bundle AcceptBundle refuses
1015// is removed, so the inventory names it as needed again; a bundle whose
1016// fetch ctx stopped is kept.
1017func (s *Store) build(ctx context.Context, st Staging, p ManifestProject) error {
1018 tmp := filepath.Join(st.tmp(), p.Name+".git")
1019 if err := removeAll(ctx, tmp); err != nil {
1020 return err
1021 }
1022 if err := os.MkdirAll(st.tmp(), 0o755); err != nil {
1023 return err
1024 }
1025 if bundle := st.Body(p.Bundle); exists(bundle) {
1026 if err := AcceptBundle(ctx, bundle, tmp, p.SourceTip); err != nil {
1027 if e := (*Error)(nil); errors.As(err, &e) && ctx.Err() == nil {
1028 os.Remove(bundle)
1029 }
1030 return err
1031 }
1032 } else if err := s.carry(ctx, p, tmp); err != nil {
1033 return err
1034 }
1035 if err := readable(tmp); err != nil {
1036 return err
1037 }
1038 // git syncs what it fetches, but not what git init wrote before, nor
1039 // the modes readable set.
1040 if err := syncTree(tmp); err != nil {
1041 return err
1042 }
1043 return rename(tmp, st.Repo(p.Name))
1044}
1045
1046// carry gives a project the active generation's repository, when that
1047// generation holds the project at the manifest's source tip.
1048func (s *Store) carry(ctx context.Context, p ManifestProject, repo string) error {
1049 g, release, err := s.Open()
1050 defer release()
1051 if err != nil && !errors.Is(err, ErrNoExport) {
1052 return err
1053 }
1054 if err == nil {
1055 e, err := g.Export()
1056 if err != nil {
1057 return err
1058 }
1059 for _, held := range e.Projects {
1060 if from, _ := g.Repo(p.Name); held.Name == p.Name && held.SourceTip == p.SourceTip && exists(from) {
1061 return CarryRepo(ctx, from, repo, p.SourceTip)
1062 }
1063 }
1064 }
1065 return refuse(CodeIncomplete, "project %s has no staged bundle, and the receiver holds no repository of it at %s", p.Name, p.SourceTip)
1066}
1067
1068// checkStaged holds the staging directory to step 4 of Activate: it holds
1069// a repository for each project of want, and no other.
1070func checkStaged(ctx context.Context, st Staging, want []ManifestProject) error {
1071 entries, err := os.ReadDir(st.Dir)
1072 if err != nil {
1073 return err
1074 }
1075 var names []string
1076 for _, e := range entries {
1077 names = append(names, e.Name())
1078 }
1079 if strings.Join(names, " ") != ExportFile+" repos" {
1080 return fmt.Errorf("the staging directory %s holds %q, not export.json and repos", st.Dir, names)
1081 }
1082 repos, err := os.ReadDir(filepath.Join(st.Dir, "repos"))
1083 if err != nil {
1084 return err
1085 }
1086 if len(repos) != len(want) {
1087 return fmt.Errorf("the staging directory holds %d repositories for %d projects", len(repos), len(want))
1088 }
1089 for _, p := range want {
1090 refs, err := git(ctx, st.Repo(p.Name), "for-each-ref", "--format=%(objectname) %(refname)")
1091 if err != nil {
1092 return err
1093 }
1094 if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want {
1095 return refuse(CodeBadBundle, "the staged repository of %s holds %q, not %q", p.Name, got, want)
1096 }
1097 }
1098 return nil
1099}
1100
1101// errNotWhole is checkGeneration's finding that a generation is damaged.
1102var errNotWhole = errors.New("the generation is not whole")
1103
1104// checkGeneration holds the activated generation at dir to what Activate
1105// checked before high-water named it, and to git fsck. export.json is a
1106// valid export, and each repository the generation holds is of one of its
1107// projects, git fsck finds it whole, and it holds refs/heads/main at the
1108// project's source tip and no other ref. A project named lacks no
1109// repository: named reports, by the stored authorization, which projects
1110// Activate built one for. A generation that fails gives an error that wraps
1111// errNotWhole. Any other error says nothing about the generation: the
1112// check did not finish, as when git is killed or fails to start.
1113func checkGeneration(ctx context.Context, dir string, named func(name, identity string) bool) error {
1114 g := Generation{Dir: dir}
1115 data, err := os.ReadFile(g.ExportPath())
1116 if errors.Is(err, fs.ErrNotExist) {
1117 return fmt.Errorf("%w: it holds no export.json", errNotWhole)
1118 }
1119 if err != nil {
1120 return err
1121 }
1122 e, err := Decode(data)
1123 if err != nil {
1124 return fmt.Errorf("%w: %v", errNotWhole, err)
1125 }
1126 for _, p := range e.Projects {
1127 repo, _ := g.Repo(p.Name)
1128 if _, err := os.Lstat(repo); errors.Is(err, fs.ErrNotExist) {
1129 if named(p.Name, p.Identity) {
1130 return fmt.Errorf("%w: the repository of %s is gone", errNotWhole, p.Name)
1131 }
1132 continue
1133 } else if err != nil {
1134 return err
1135 }
1136 finding, err := fsck(ctx, repo)
1137 if err != nil {
1138 return fmt.Errorf("the check of the repository of %s did not finish: %w", p.Name, err)
1139 }
1140 if finding != "" {
1141 return fmt.Errorf("%w: git fsck finds the repository of %s damaged: %s", errNotWhole, p.Name, finding)
1142 }
1143 refs, err := git(ctx, repo, "for-each-ref", "--format=%(objectname) %(refname)")
1144 if err != nil {
1145 return err
1146 }
1147 if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want {
1148 return fmt.Errorf("%w: the repository of %s holds %q, not %q", errNotWhole, p.Name, got, want)
1149 }
1150 }
1151 return nil
1152}
1153
1154// fsck runs git fsck on the repository at repo. finding is the first
1155// problem fsck names when it finds the repository damaged, and "" when it
1156// finds it whole. fsck finds damage only when git exits on its own with a
1157// non-zero status and names a problem. Anything else is an error, which
1158// says nothing about the repository: git killed by a signal, failing to
1159// start, outliving ctx, or exiting without naming a problem, as it does
1160// when it runs out of memory.
1161func fsck(ctx context.Context, repo string) (finding string, err error) {
1162 // --git-dir, unlike -C, never lets git check a repository it finds
1163 // above repo. LC_ALL=C keeps git's messages in the words fsckFinding
1164 // reads.
1165 cmd := command(ctx, "", "--git-dir="+repo, "fsck", "--no-progress", "--no-dangling")
1166 cmd.Env = append(cmd.Env, "LC_ALL=C")
1167 var out bytes.Buffer
1168 cmd.Stdout, cmd.Stderr = &out, &out
1169 err = cmd.Run()
1170 if err == nil {
1171 return "", nil
1172 }
1173 var exit *exec.ExitError
1174 if errors.As(err, &exit) && exit.Exited() && ctx.Err() == nil {
1175 if finding := fsckFinding(out.String()); finding != "" {
1176 return finding, nil
1177 }
1178 }
1179 last := strings.TrimSpace(out.String())
1180 if i := strings.LastIndexByte(last, '\n'); i >= 0 {
1181 last = last[i+1:]
1182 }
1183 if last == "" {
1184 return "", fmt.Errorf("git fsck: %w", err)
1185 }
1186 return "", fmt.Errorf("git fsck: %w: %s", err, last)
1187}
1188
1189// fsckFinding is the first line of git fsck's output that names a problem
1190// with the repository, and "" when none does. fsck reports each problem it
1191// finds on a line of its own: an error, a missing object, or a broken
1192// link. git refuses a directory that holds no repository, and dies on an
1193// object it finds corrupt. A failure of git's own, such as malloc failing,
1194// names no problem.
1195func fsckFinding(out string) string {
1196 for _, line := range strings.Split(out, "\n") {
1197 switch {
1198 case strings.HasPrefix(line, "error: "),
1199 strings.HasPrefix(line, "missing "),
1200 strings.HasPrefix(line, "broken link from "),
1201 strings.HasPrefix(line, "fatal: not a git repository"),
1202 strings.HasPrefix(line, "fatal: ") && strings.HasSuffix(line, " is corrupt"):
1203 return line
1204 }
1205 }
1206 return ""
1207}
1208
1209// checkNewer refuses a manifest whose sequence is not greater than the
1210// high-water mark.
1211func (s *Store) checkNewer(m *Manifest) error {
1212 hw, err := s.HighWater()
1213 if err != nil {
1214 return err
1215 }
1216 return checkSequence(m, hw)
1217}
1218
1219// staged are the sequences with a staging directory, in ascending order.
1220func (s *Store) staged() ([]int64, error) {
1221 entries, err := os.ReadDir(s.path("staging"))
1222 if err != nil {
1223 return nil, err
1224 }
1225 var seqs []int64
1226 for _, e := range entries {
1227 if n, ok := decimal(e.Name()); ok {
1228 seqs = append(seqs, n)
1229 }
1230 }
1231 sort.Slice(seqs, func(i, j int) bool { return seqs[i] < seqs[j] })
1232 return seqs, nil
1233}
1234
1235// swap points current at the generation with sequence, atomically. The
1236// caller syncs the payload directory.
1237func (s *Store) swap(sequence int64) error {
1238 tmp := s.path("current." + random())
1239 if err := os.Symlink("generations/"+strconv.FormatInt(sequence, 10), tmp); err != nil {
1240 return err
1241 }
1242 if err := rename(tmp, s.path("current")); err != nil {
1243 os.Remove(tmp)
1244 return err
1245 }
1246 return nil
1247}
1248
1249// recover finishes an activation interrupted between writing high-water
1250// and swapping current. The generation high-water names was on disk before
1251// high-water was written, so it is whole unless the disk lost what it was
1252// told to keep. recover holds it to checkGeneration before it swaps
1253// active to it. A generation that fails is reported and not activated:
1254// the old generation keeps serving, the sweep after recovery deletes the
1255// damaged one, and the publisher's next manifest replaces it. A check
1256// that did not finish says nothing about the generation, so recover
1257// returns its error, and OpenStore deletes nothing and fails, to be tried
1258// again.
1259func (s *Store) recover() error {
1260 hw, err := s.HighWater()
1261 if err != nil || hw == 0 {
1262 return err
1263 }
1264 seq, ok, err := s.active()
1265 if err != nil {
1266 return err
1267 }
1268 if ok && seq == hw {
1269 return nil
1270 }
1271 dir := s.generationDir(hw)
1272 if !exists(dir) {
1273 return nil
1274 }
1275 named, err := s.named()
1276 if err != nil {
1277 return err
1278 }
1279 if err := checkGeneration(context.Background(), dir, named); errors.Is(err, errNotWhole) {
1280 s.report(fmt.Errorf("generation %d, which high-water names, is not activated: %w", hw, err))
1281 return nil
1282 } else if err != nil {
1283 return fmt.Errorf("generation %d, which high-water names, is kept unchecked: %w", hw, err)
1284 }
1285 if err := s.swap(hw); err != nil {
1286 return err
1287 }
1288 return syncPath(s.dir)
1289}
1290
1291// sweep deletes every generation but the active one that no reader holds,
1292// every staging directory not newer than the high-water mark, and the
1293// trash. A generation a reader holds is left for a later sweep. A
1294// deletion that fails does not stop the others, and the next sweep tries
1295// it again. Once ctx is done, sweep stops, even part way through a
1296// deletion, and fails with ctx's error; the next sweep finishes the work.
1297func (s *Store) sweep(ctx context.Context) error {
1298 active, ok, err := s.active()
1299 if err != nil {
1300 return fmt.Errorf("sweeping %s: %w", s.dir, err)
1301 }
1302 hw, err := s.HighWater()
1303 if err != nil {
1304 return fmt.Errorf("sweeping %s: %w", s.dir, err)
1305 }
1306 var errs []error
1307 generations, err := os.ReadDir(s.path("generations"))
1308 errs = append(errs, err)
1309 for _, e := range generations {
1310 if ctx.Err() != nil {
1311 break
1312 }
1313 if n, valid := decimal(e.Name()); valid && ok && n == active {
1314 continue
1315 }
1316 errs = append(errs, s.delete(ctx, s.path("generations", e.Name())))
1317 }
1318 staging, err := os.ReadDir(s.path("staging"))
1319 errs = append(errs, err)
1320 for _, e := range staging {
1321 if ctx.Err() != nil {
1322 break
1323 }
1324 if n, valid := decimal(e.Name()); !valid || n <= hw {
1325 errs = append(errs, removeAll(ctx, s.path("staging", e.Name())))
1326 }
1327 }
1328 trash, err := os.ReadDir(s.path("trash"))
1329 errs = append(errs, err)
1330 for _, e := range trash {
1331 if ctx.Err() != nil {
1332 break
1333 }
1334 errs = append(errs, removeAll(ctx, s.path("trash", e.Name())))
1335 }
1336 // A deletion ctx stopped has said so already.
1337 if err := ctx.Err(); err != nil && !errors.Is(errors.Join(errs...), err) {
1338 errs = append(errs, fmt.Errorf("stopped: %w", err))
1339 }
1340 if err := errors.Join(errs...); err != nil {
1341 return fmt.Errorf("sweeping %s: %w", s.dir, err)
1342 }
1343 return nil
1344}
1345
1346// delete removes the generation at dir unless a reader holds it. Holding
1347// the generation's lock exclusively, it renames the generation into the
1348// trash, so a reader that locks it afterwards finds it gone from its path.
1349// It then deletes it there until ctx is done.
1350func (s *Store) delete(ctx context.Context, dir string) error {
1351 f, err := os.Open(dir)
1352 if errors.Is(err, os.ErrNotExist) {
1353 return nil
1354 }
1355 if err != nil {
1356 return err
1357 }
1358 defer f.Close()
1359 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
1360 return nil
1361 } else if err != nil {
1362 return err
1363 }
1364 trash := s.path("trash", filepath.Base(dir)+"-"+random())
1365 if err := rename(dir, trash); err != nil {
1366 return err
1367 }
1368 f.Close()
1369 return removeAll(ctx, trash)
1370}
1371
1372// remove deletes the tree at path. It renames the tree into the trash, so
1373// the tree is gone from path at once and whole until then, and deletes it
1374// there until ctx is done. What ctx stops is left in the trash for the
1375// next sweep. A path that does not exist is no error.
1376func (s *Store) remove(ctx context.Context, path string) error {
1377 trash := s.path("trash", filepath.Base(path)+"-"+random())
1378 if err := rename(path, trash); errors.Is(err, fs.ErrNotExist) {
1379 return nil
1380 } else if err != nil {
1381 return err
1382 }
1383 return removeAll(ctx, trash)
1384}
1385
1386// removeTree deletes the tree at path, as os.RemoveAll does, but checks
1387// ctx before it deletes each entry, and stops with ctx's error once ctx is
1388// done. A symlink is deleted, not followed. A path that does not exist is
1389// no error.
1390func removeTree(ctx context.Context, path string) error {
1391 if err := ctx.Err(); err != nil {
1392 return fmt.Errorf("deleting %s: %w", path, err)
1393 }
1394 info, err := os.Lstat(path)
1395 if errors.Is(err, fs.ErrNotExist) {
1396 return nil
1397 }
1398 if err != nil {
1399 return err
1400 }
1401 if info.IsDir() {
1402 entries, err := os.ReadDir(path)
1403 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1404 return err
1405 }
1406 for _, e := range entries {
1407 if err := removeTree(ctx, filepath.Join(path, e.Name())); err != nil {
1408 return err
1409 }
1410 }
1411 }
1412 if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
1413 return err
1414 }
1415 return nil
1416}
1417
1418// lock takes the store's activation lock, waiting for it until ctx is
1419// done, and fails once ctx is done, even when the lock is free. The
1420// store's own goroutines wait their turn on s.turn. The flock(2) lock then
1421// holds off other processes, and lock polls for it, since a process
1422// cannot stop waiting in flock(2) when ctx is done.
1423func (s *Store) lock(ctx context.Context) (unlock func(), err error) {
1424 return s.lockFile(ctx, "lock", s.turn)
1425}
1426
1427// lockAuthorization takes the authorization lock, as lock takes the
1428// activation lock. The two are independent: neither waits for the other.
1429func (s *Store) lockAuthorization(ctx context.Context) (unlock func(), err error) {
1430 return s.lockFile(ctx, "authorization.lock", s.authTurn)
1431}
1432
1433func (s *Store) lockFile(ctx context.Context, name string, turn chan struct{}) (unlock func(), err error) {
1434 waiting := func() error { return fmt.Errorf("waiting for the lock %s: %w", s.path(name), ctx.Err()) }
1435 if ctx.Err() != nil {
1436 return nil, waiting()
1437 }
1438 select {
1439 case turn <- struct{}{}:
1440 case <-ctx.Done():
1441 return nil, waiting()
1442 }
1443 f, err := os.OpenFile(s.path(name), os.O_RDWR|os.O_CREATE, 0o644)
1444 if err != nil {
1445 <-turn
1446 return nil, err
1447 }
1448 for pause := time.Millisecond; ; pause = min(2*pause, 100*time.Millisecond) {
1449 err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB)
1450 if err == nil {
1451 break
1452 }
1453 if !errors.Is(err, syscall.EWOULDBLOCK) {
1454 f.Close()
1455 <-turn
1456 return nil, err
1457 }
1458 select {
1459 case <-time.After(pause):
1460 case <-ctx.Done():
1461 f.Close()
1462 <-turn
1463 return nil, waiting()
1464 }
1465 }
1466 unlock = func() {
1467 f.Close()
1468 <-turn
1469 }
1470 // ctx may have been done while flock(2) succeeded, and the caller
1471 // does no work once it is.
1472 if ctx.Err() != nil {
1473 unlock()
1474 return nil, waiting()
1475 }
1476 return unlock, nil
1477}
1478
1479// checkStorage refuses m as too-large when its upload would take the
1480// state directory past MaxStorage, and stops measuring once ctx is done.
1481// It counts what the directory holds now,
1482// less the staging directories in discard, which are older uploads Stage
1483// discards and m's own. To that it adds everything the upload may write:
1484// every body m declares, once for each SHA-256, since the publisher may
1485// send any of them; and a repository for every project, each counted
1486// apart, even when two projects name one bundle. A project's repository
1487// counts as large as its bundle, or as the active generation's repository
1488// of it at the same source tip, which Activate carries, when that is
1489// larger; and RepoOverhead more.
1490func (s *Store) checkStorage(ctx context.Context, m *Manifest, discard []string) error {
1491 if s.MaxStorage <= 0 {
1492 return nil
1493 }
1494 skip := map[string]bool{}
1495 for _, dir := range discard {
1496 skip[dir] = true
1497 }
1498 held, err := usage(ctx, s.dir, skip)
1499 if err != nil {
1500 return err
1501 }
1502 carried := map[string]string{}
1503 g, release, err := s.Open()
1504 defer release()
1505 switch {
1506 case errors.Is(err, ErrNoExport):
1507 case err != nil:
1508 return err
1509 default:
1510 e, err := g.Export()
1511 if err != nil {
1512 return err
1513 }
1514 for _, p := range e.Projects {
1515 carried[p.Name+" "+p.SourceTip], _ = g.Repo(p.Name)
1516 }
1517 }
1518 total, fits := held, true
1519 add := func(n int64) {
1520 // Compared before it is added, so the sum never overflows.
1521 if !fits || n > s.MaxStorage-total {
1522 fits = false
1523 return
1524 }
1525 total += n
1526 }
1527 counted := map[string]bool{}
1528 for _, b := range m.Bodies() {
1529 if !counted[b.SHA256] {
1530 counted[b.SHA256] = true
1531 add(b.Size)
1532 }
1533 }
1534 for _, p := range m.Projects {
1535 repo := p.Bundle.Size
1536 if from, ok := carried[p.Name+" "+p.SourceTip]; ok {
1537 n, err := usage(ctx, from, nil)
1538 if err != nil {
1539 return err
1540 }
1541 repo = max(repo, n)
1542 }
1543 add(repo)
1544 add(RepoOverhead)
1545 }
1546 if !fits {
1547 return refuse(CodeTooLarge, "the state directory takes %d bytes on disk, and the upload with sequence %d would take it past this receiver's cap of %d", held, m.Sequence, s.MaxStorage)
1548 }
1549 return nil
1550}
1551
1552// checkUsage refuses as too-large once the state directory takes more
1553// than MaxStorage on disk. It stops measuring once ctx is done.
1554func (s *Store) checkUsage(ctx context.Context) error {
1555 if s.MaxStorage <= 0 {
1556 return nil
1557 }
1558 n, err := usage(ctx, s.dir, nil)
1559 if err != nil {
1560 return err
1561 }
1562 if n > s.MaxStorage {
1563 return refuse(CodeTooLarge, "the state directory takes %d bytes on disk, past this receiver's cap of %d", n, s.MaxStorage)
1564 }
1565 return nil
1566}
1567
1568// usage is what the tree at root takes on disk. Each file and directory
1569// in it counts its size or the blocks it holds, whichever is more, and a
1570// symlink is not followed. An entry deleted while usage walks is not
1571// counted, and neither is a path in skip, nor anything under it. usage
1572// stops with ctx's error once ctx is done.
1573func usage(ctx context.Context, root string, skip map[string]bool) (int64, error) {
1574 var total int64
1575 err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
1576 if err := ctx.Err(); err != nil {
1577 return fmt.Errorf("measuring %s: %w", root, err)
1578 }
1579 if errors.Is(err, fs.ErrNotExist) {
1580 return nil
1581 }
1582 if err != nil {
1583 return err
1584 }
1585 if skip[path] {
1586 if d.IsDir() {
1587 return filepath.SkipDir
1588 }
1589 return nil
1590 }
1591 info, err := d.Info()
1592 if errors.Is(err, fs.ErrNotExist) {
1593 return nil
1594 }
1595 if err != nil {
1596 return err
1597 }
1598 n := info.Size()
1599 if st, ok := info.Sys().(*syscall.Stat_t); ok {
1600 n = max(n, st.Blocks*512)
1601 }
1602 total += n
1603 return nil
1604 })
1605 return total, err
1606}
1607
1608// flock takes a lock on f's open file description, which closing f
1609// releases.
1610func flock(f *os.File, how int) error {
1611 for {
1612 err := syscall.Flock(int(f.Fd()), how)
1613 if !errors.Is(err, syscall.EINTR) {
1614 return err
1615 }
1616 }
1617}
1618
1619// writeDurably replaces the file at path with data: a temporary file
1620// beside it, mode 0644 whatever the umask, synced, renamed over it, and
1621// the directory synced.
1622func writeDurably(path string, data []byte) error {
1623 return writeDurablyHeld(path, data, nil)
1624}
1625
1626// writeDurablyHeld is writeDurably, holding what hold takes, when it is
1627// not nil, around the rename alone: hold is taken once the temporary file
1628// is synced, and released before the directory is synced.
1629func writeDurablyHeld(path string, data []byte, hold func() (func(), error)) error {
1630 tmp := path + "." + random()
1631 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
1632 if err != nil {
1633 return err
1634 }
1635 err = f.Chmod(0o644)
1636 if err == nil {
1637 _, err = f.Write(data)
1638 }
1639 if err == nil {
1640 err = syncFile(f)
1641 }
1642 if cerr := f.Close(); err == nil {
1643 err = cerr
1644 }
1645 release := func() {}
1646 if err == nil && hold != nil {
1647 release, err = hold()
1648 }
1649 if err == nil {
1650 err = rename(tmp, path)
1651 }
1652 release()
1653 if err != nil {
1654 os.Remove(tmp)
1655 return err
1656 }
1657 return syncPath(filepath.Dir(path))
1658}
1659
1660// readable makes the tree at root readable by every user who can reach
1661// it, whatever the umask it was written under: each directory 0755, and
1662// each file 0644, or 0444 when its owner may not write it, as git's
1663// objects are. A symlink is left as it is.
1664func readable(root string) error {
1665 return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
1666 switch {
1667 case err != nil:
1668 return err
1669 case d.IsDir():
1670 return os.Chmod(path, 0o755)
1671 case d.Type().IsRegular():
1672 info, err := d.Info()
1673 if err != nil {
1674 return err
1675 }
1676 return os.Chmod(path, info.Mode().Perm()&0o200|0o444)
1677 }
1678 return nil
1679 })
1680}
1681
1682// syncTree syncs every file and directory in the tree at root. A symlink
1683// is not followed: syncing its directory makes it durable.
1684func syncTree(root string) error {
1685 return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
1686 if err != nil {
1687 return err
1688 }
1689 if !d.IsDir() && !d.Type().IsRegular() {
1690 return nil
1691 }
1692 return syncPath(path)
1693 })
1694}
1695
1696// syncPath syncs the file or directory at path. Syncing a directory makes
1697// its entries durable.
1698func syncPath(path string) error {
1699 f, err := os.Open(path)
1700 if err != nil {
1701 return err
1702 }
1703 defer f.Close()
1704 return syncFile(f)
1705}
1706
1707// The calls the store syncs, renames and deletes with. A test replaces
1708// them to record their order or to make one fail.
1709var (
1710 syncFile = (*os.File).Sync
1711 rename = os.Rename
1712 removeAll = removeTree
1713)
1714
1715func exists(path string) bool {
1716 _, err := os.Lstat(path)
1717 return err == nil
1718}
1719
1720func random() string {
1721 b := make([]byte, 8)
1722 rand.Read(b)
1723 return hex.EncodeToString(b)
1724}