gunk-dev/the-valley

authorize.go

source42401ff8454fmain's published tip history
11.3 KiB
1package export
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "io/fs"
9 "os"
10 "path/filepath"
11 "sync"
12 "syscall"
13 "time"
14)
15
16// Holdings are the active export, by its sequence and its digest, or nil
17// for none, and the source tip of each of its projects whose repository
18// the active generation still holds.
19func (s *Store) Holdings() (*Active, map[string]string, error) {
20 held := map[string]string{}
21 g, release, err := s.Open()
22 defer release()
23 switch {
24 case errors.Is(err, ErrNoExport):
25 return nil, held, nil
26 case err != nil:
27 return nil, nil, err
28 }
29 e, err := g.Export()
30 if err != nil {
31 return nil, nil, err
32 }
33 digest, err := e.Digest()
34 if err != nil {
35 return nil, nil, err
36 }
37 for _, p := range e.Projects {
38 if repo, _ := g.Repo(p.Name); exists(repo) {
39 held[p.Name] = p.SourceTip
40 }
41 }
42 return &Active{Sequence: g.Sequence, Digest: digest}, held, nil
43}
44
45// named reports, by the stored authorization, whether a project and
46// identity are named, with any reader. With no stored authorization it
47// names nothing.
48func (s *Store) named() (func(name, identity string) bool, error) {
49 a, _, err := s.Authorization()
50 if errors.Is(err, ErrNoAuthorization) {
51 return func(string, string) bool { return false }, nil
52 }
53 if err != nil {
54 return nil, err
55 }
56 return a.Names, nil
57}
58
59// ReadAuthorization is the stored authorization, as the signed note the
60// receiver admitted, read whole and at most MaxAuthorization bytes. Its
61// error is ErrNoAuthorization before the first is stored.
62func (s *Store) ReadAuthorization() ([]byte, error) {
63 f, err := os.Open(s.path("authorization"))
64 if errors.Is(err, fs.ErrNotExist) {
65 return nil, ErrNoAuthorization
66 }
67 if err != nil {
68 return nil, err
69 }
70 defer f.Close()
71 data, err := io.ReadAll(io.LimitReader(f, MaxAuthorization+1))
72 if err != nil {
73 return nil, err
74 }
75 if len(data) > MaxAuthorization {
76 return nil, fmt.Errorf("%s is larger than %d bytes", s.path("authorization"), MaxAuthorization)
77 }
78 return data, nil
79}
80
81// Authorization is the stored authorization, read and parsed, with the
82// signed note it was read from.
83func (s *Store) Authorization() (*Authorization, []byte, error) {
84 signed, err := s.ReadAuthorization()
85 if err != nil {
86 return nil, nil, err
87 }
88 a, err := ReadStoredAuthorization(signed)
89 if err != nil {
90 return nil, nil, fmt.Errorf("%s: %w", s.path("authorization"), err)
91 }
92 return a, signed, nil
93}
94
95// AuthorizationHighWater is the stored authorization's sequence, 0 for
96// none. A stored authorization that cannot be read is an error, never 0,
97// so no replay is admitted over it.
98func (s *Store) AuthorizationHighWater() (int64, error) {
99 a, _, err := s.Authorization()
100 if errors.Is(err, ErrNoAuthorization) {
101 return 0, nil
102 }
103 if err != nil {
104 return 0, err
105 }
106 return a.Sequence, nil
107}
108
109// Authorize stores an authorization VerifyAuthorization admitted, whose
110// signed note is signed. It takes the authorization lock, waiting for it
111// until ctx is done, and never the activation lock, so a stalled upload,
112// commit or repository check does not hold it up. Under the lock it
113// refuses a sequence not greater than the stored one's as replayed, and a
114// basis other than the stored one's sequence as stale-basis, and then
115// replaces the stored authorization durably. Once Authorize returns
116// nil, every response a server starts writing is held to it: the rename
117// happens under the serving lock, exclusively.
118//
119// Authorize deletes nothing. Prune deletes the repositories it withdrew.
120func (s *Store) Authorize(ctx context.Context, a *Authorization, signed []byte) error {
121 if s.readOnly {
122 return errReadOnly
123 }
124 unlock, err := s.lockAuthorization(ctx)
125 if err != nil {
126 return err
127 }
128 defer unlock()
129 hw, err := s.AuthorizationHighWater()
130 if err != nil {
131 return err
132 }
133 if err := a.admissible(hw); err != nil {
134 return err
135 }
136 if err := ctx.Err(); err != nil {
137 return err
138 }
139 return writeDurablyHeld(s.path("authorization"), signed, func() (func(), error) {
140 return s.holdServing(ctx, syscall.LOCK_EX)
141 })
142}
143
144// servingLock is the file a server and Authorize coordinate through. A
145// server holds it shared from its last read of the authorization until it
146// has written a response's headers. Authorize holds it exclusively while
147// it renames the new authorization into place, and returns only after it
148// releases it. So a response whose headers are written after Authorize
149// returns was checked against the new authorization.
150const servingLock = "serving.lock"
151
152// HoldServing takes the serving lock shared, for a server's last read of
153// the authorization and the response it then starts. Authorize holds it
154// exclusively for a rename alone, so the wait is short, but a receiver
155// stopped while it holds it would hold it for as long as it stays
156// stopped: HoldServing waits only until ctx is done, and then fails with
157// ctx's error. It fails so too when ctx is done by the time it takes the
158// lock, and gives the lock back, so nothing is started past a deadline. A
159// store opened read-only takes it too: the lock file is opened read-only.
160func (s *Store) HoldServing(ctx context.Context) (release func(), err error) {
161 return s.holdServing(ctx, syscall.LOCK_SH)
162}
163
164// holdServing takes the serving lock as how says, waiting for it until
165// ctx is done. A ctx done once the lock is taken gives the lock back and
166// fails, so neither a rename nor a response's headers follow it.
167func (s *Store) holdServing(ctx context.Context, how int) (func(), error) {
168 flags := os.O_RDONLY
169 if how == syscall.LOCK_EX {
170 flags = os.O_RDWR
171 }
172 f, err := os.OpenFile(s.path(servingLock), flags, 0)
173 if err != nil {
174 return nil, err
175 }
176 for pause := time.Millisecond; ; pause = min(2*pause, 50*time.Millisecond) {
177 err := flock(f, how|syscall.LOCK_NB)
178 if err == nil {
179 break
180 }
181 if !errors.Is(err, syscall.EWOULDBLOCK) {
182 f.Close()
183 return nil, err
184 }
185 select {
186 case <-time.After(pause):
187 case <-ctx.Done():
188 f.Close()
189 return nil, fmt.Errorf("waiting for %s: %w", s.path(servingLock), ctx.Err())
190 }
191 }
192 if err := ctx.Err(); err != nil {
193 f.Close()
194 return nil, fmt.Errorf("holding %s: %w", s.path(servingLock), err)
195 }
196 var once sync.Once
197 return func() { once.Do(func() { f.Close() }) }, nil
198}
199
200// touch makes the file at path if it does not exist, and gives it mode
201// 0644 whatever the umask.
202func touch(path string) error {
203 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
204 if err != nil {
205 return err
206 }
207 defer f.Close()
208 return f.Chmod(0o644)
209}
210
211// Missing are the projects of the active export that the stored
212// authorization names and whose repositories the active generation no
213// longer holds, in the export's order.
214func (s *Store) Missing() ([]string, error) {
215 named, err := s.named()
216 if err != nil {
217 return nil, err
218 }
219 missing := []string{}
220 g, release, err := s.Open()
221 defer release()
222 if errors.Is(err, ErrNoExport) {
223 return missing, nil
224 }
225 if err != nil {
226 return nil, err
227 }
228 e, err := g.Export()
229 if err != nil {
230 return nil, err
231 }
232 for _, p := range e.Projects {
233 if repo, _ := g.Repo(p.Name); named(p.Name, p.Identity) && !exists(repo) {
234 missing = append(missing, p.Name)
235 }
236 }
237 return missing, nil
238}
239
240// Prune deletes from the active generation the repository of each project
241// the stored authorization does not name, once no reader holds the
242// generation. It takes the activation lock, waiting for it until ctx is
243// done. While a reader holds the generation it deletes nothing and returns
244// ErrHeld, and the caller tries again later. With no stored authorization
245// it deletes nothing: a server serves nothing without one, and a later
246// authorization may name what the generation holds. It decides what to
247// delete, and renames it away, under the authorization lock too, so a
248// repository an authorization names again is never deleted after
249// Authorize returns. export.json stays as it was signed, so it keeps the
250// withdrawn projects' plan text until a later activation replaces the
251// generation.
252func (s *Store) Prune(ctx context.Context) error {
253 if s.readOnly {
254 return errReadOnly
255 }
256 unlock, err := s.lock(ctx)
257 if err != nil {
258 return err
259 }
260 defer unlock()
261 return s.prune(ctx)
262}
263
264// prune is Prune, with the activation lock held. It selects the
265// repositories of the projects the stored authorization does not name.
266// Then, under the authorization lock, it reads the authorization again,
267// keeps only those it still does not name, and renames them into the
268// trash. An authorization stored meanwhile is either read again here, so
269// what it names again is kept, or is stored once the rename is done, when
270// Missing reports what it deleted. It deletes the trash once it lets the
271// authorization lock go.
272func (s *Store) prune(ctx context.Context) error {
273 g, withdrawn, err := s.withdrawn()
274 if err != nil || len(withdrawn) == 0 {
275 return err
276 }
277 if pruneSelected != nil {
278 pruneSelected()
279 }
280 unlock, err := s.lockAuthorization(ctx)
281 if err != nil {
282 return err
283 }
284 trash, err := s.renameWithdrawn(g, withdrawn)
285 unlock()
286 for _, t := range trash {
287 err = errors.Join(err, removeAll(ctx, t))
288 }
289 return err
290}
291
292// withdrawn are the active generation and the projects of it whose
293// repositories it holds and the stored authorization does not name. With
294// no stored authorization there are none.
295func (s *Store) withdrawn() (Generation, []string, error) {
296 a, _, err := s.Authorization()
297 if errors.Is(err, ErrNoAuthorization) {
298 return Generation{}, nil, nil
299 }
300 if err != nil {
301 return Generation{}, nil, err
302 }
303 seq, ok, err := s.active()
304 if err != nil || !ok {
305 return Generation{}, nil, err
306 }
307 g := Generation{Sequence: seq, Dir: s.generationDir(seq)}
308 e, err := g.Export()
309 if err != nil {
310 return Generation{}, nil, err
311 }
312 var withdrawn []string
313 for _, p := range e.Projects {
314 if repo, _ := g.Repo(p.Name); !a.Names(p.Name, p.Identity) && exists(repo) {
315 withdrawn = append(withdrawn, p.Name)
316 }
317 }
318 return g, withdrawn, nil
319}
320
321// renameWithdrawn renames into the trash the repositories of the projects
322// of g in names that the stored authorization, read again, still does not
323// name, while no reader holds g. The caller holds the authorization lock.
324// It returns what it put in the trash.
325func (s *Store) renameWithdrawn(g Generation, names []string) ([]string, error) {
326 a, _, err := s.Authorization()
327 if err != nil {
328 return nil, err
329 }
330 e, err := g.Export()
331 if err != nil {
332 return nil, err
333 }
334 still := map[string]bool{}
335 for _, p := range e.Projects {
336 still[p.Name] = !a.Names(p.Name, p.Identity)
337 }
338 var repos []string
339 for _, name := range names {
340 if repo, _ := g.Repo(name); still[name] && exists(repo) {
341 repos = append(repos, repo)
342 }
343 }
344 if len(repos) == 0 {
345 return nil, nil
346 }
347 f, err := os.Open(g.Dir)
348 if err != nil {
349 return nil, err
350 }
351 defer f.Close()
352 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
353 return nil, ErrHeld
354 } else if err != nil {
355 return nil, err
356 }
357 // Holding the generation exclusively, no reader is in it, and one
358 // that opens it next finds the repositories gone.
359 var trash []string
360 for _, repo := range repos {
361 to := s.path("trash", "withdrawn-"+filepath.Base(repo)+"-"+random())
362 if err := rename(repo, to); err != nil {
363 return trash, err
364 }
365 trash = append(trash, to)
366 }
367 return trash, syncPath(filepath.Join(g.Dir, "repos"))
368}
369
370// pruneSelected, when it is set, is called by prune once it has selected
371// the repositories to delete and before it takes the authorization lock. A
372// test pauses there.
373var pruneSelected func()