gunk-dev/the-valley

authorize.go

source4a0035221288main's published tip history
10.9 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. A store opened read-only takes it too: the lock file is
158// opened read-only.
159func (s *Store) HoldServing(ctx context.Context) (release func(), err error) {
160 return s.holdServing(ctx, syscall.LOCK_SH)
161}
162
163// holdServing takes the serving lock as how says, waiting for it until
164// ctx is done.
165func (s *Store) holdServing(ctx context.Context, how int) (func(), error) {
166 flags := os.O_RDONLY
167 if how == syscall.LOCK_EX {
168 flags = os.O_RDWR
169 }
170 f, err := os.OpenFile(s.path(servingLock), flags, 0)
171 if err != nil {
172 return nil, err
173 }
174 for pause := time.Millisecond; ; pause = min(2*pause, 50*time.Millisecond) {
175 err := flock(f, how|syscall.LOCK_NB)
176 if err == nil {
177 break
178 }
179 if !errors.Is(err, syscall.EWOULDBLOCK) {
180 f.Close()
181 return nil, err
182 }
183 select {
184 case <-time.After(pause):
185 case <-ctx.Done():
186 f.Close()
187 return nil, fmt.Errorf("waiting for %s: %w", s.path(servingLock), ctx.Err())
188 }
189 }
190 var once sync.Once
191 return func() { once.Do(func() { f.Close() }) }, nil
192}
193
194// touch makes the file at path if it does not exist, and gives it mode
195// 0644 whatever the umask.
196func touch(path string) error {
197 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
198 if err != nil {
199 return err
200 }
201 defer f.Close()
202 return f.Chmod(0o644)
203}
204
205// Missing are the projects of the active export that the stored
206// authorization names and whose repositories the active generation no
207// longer holds, in the export's order.
208func (s *Store) Missing() ([]string, error) {
209 named, err := s.named()
210 if err != nil {
211 return nil, err
212 }
213 missing := []string{}
214 g, release, err := s.Open()
215 defer release()
216 if errors.Is(err, ErrNoExport) {
217 return missing, nil
218 }
219 if err != nil {
220 return nil, err
221 }
222 e, err := g.Export()
223 if err != nil {
224 return nil, err
225 }
226 for _, p := range e.Projects {
227 if repo, _ := g.Repo(p.Name); named(p.Name, p.Identity) && !exists(repo) {
228 missing = append(missing, p.Name)
229 }
230 }
231 return missing, nil
232}
233
234// Prune deletes from the active generation the repository of each project
235// the stored authorization does not name, once no reader holds the
236// generation. It takes the activation lock, waiting for it until ctx is
237// done. While a reader holds the generation it deletes nothing and returns
238// ErrHeld, and the caller tries again later. With no stored authorization
239// it deletes nothing: a server serves nothing without one, and a later
240// authorization may name what the generation holds. It decides what to
241// delete, and renames it away, under the authorization lock too, so a
242// repository an authorization names again is never deleted after
243// Authorize returns. export.json stays as it was signed, so it keeps the
244// withdrawn projects' plan text until a later activation replaces the
245// generation.
246func (s *Store) Prune(ctx context.Context) error {
247 if s.readOnly {
248 return errReadOnly
249 }
250 unlock, err := s.lock(ctx)
251 if err != nil {
252 return err
253 }
254 defer unlock()
255 return s.prune(ctx)
256}
257
258// prune is Prune, with the activation lock held. It selects the
259// repositories of the projects the stored authorization does not name.
260// Then, under the authorization lock, it reads the authorization again,
261// keeps only those it still does not name, and renames them into the
262// trash. An authorization stored meanwhile is either read again here, so
263// what it names again is kept, or is stored once the rename is done, when
264// Missing reports what it deleted. It deletes the trash once it lets the
265// authorization lock go.
266func (s *Store) prune(ctx context.Context) error {
267 g, withdrawn, err := s.withdrawn()
268 if err != nil || len(withdrawn) == 0 {
269 return err
270 }
271 if pruneSelected != nil {
272 pruneSelected()
273 }
274 unlock, err := s.lockAuthorization(ctx)
275 if err != nil {
276 return err
277 }
278 trash, err := s.renameWithdrawn(g, withdrawn)
279 unlock()
280 for _, t := range trash {
281 err = errors.Join(err, removeAll(ctx, t))
282 }
283 return err
284}
285
286// withdrawn are the active generation and the projects of it whose
287// repositories it holds and the stored authorization does not name. With
288// no stored authorization there are none.
289func (s *Store) withdrawn() (Generation, []string, error) {
290 a, _, err := s.Authorization()
291 if errors.Is(err, ErrNoAuthorization) {
292 return Generation{}, nil, nil
293 }
294 if err != nil {
295 return Generation{}, nil, err
296 }
297 seq, ok, err := s.active()
298 if err != nil || !ok {
299 return Generation{}, nil, err
300 }
301 g := Generation{Sequence: seq, Dir: s.generationDir(seq)}
302 e, err := g.Export()
303 if err != nil {
304 return Generation{}, nil, err
305 }
306 var withdrawn []string
307 for _, p := range e.Projects {
308 if repo, _ := g.Repo(p.Name); !a.Names(p.Name, p.Identity) && exists(repo) {
309 withdrawn = append(withdrawn, p.Name)
310 }
311 }
312 return g, withdrawn, nil
313}
314
315// renameWithdrawn renames into the trash the repositories of the projects
316// of g in names that the stored authorization, read again, still does not
317// name, while no reader holds g. The caller holds the authorization lock.
318// It returns what it put in the trash.
319func (s *Store) renameWithdrawn(g Generation, names []string) ([]string, error) {
320 a, _, err := s.Authorization()
321 if err != nil {
322 return nil, err
323 }
324 e, err := g.Export()
325 if err != nil {
326 return nil, err
327 }
328 still := map[string]bool{}
329 for _, p := range e.Projects {
330 still[p.Name] = !a.Names(p.Name, p.Identity)
331 }
332 var repos []string
333 for _, name := range names {
334 if repo, _ := g.Repo(name); still[name] && exists(repo) {
335 repos = append(repos, repo)
336 }
337 }
338 if len(repos) == 0 {
339 return nil, nil
340 }
341 f, err := os.Open(g.Dir)
342 if err != nil {
343 return nil, err
344 }
345 defer f.Close()
346 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
347 return nil, ErrHeld
348 } else if err != nil {
349 return nil, err
350 }
351 // Holding the generation exclusively, no reader is in it, and one
352 // that opens it next finds the repositories gone.
353 var trash []string
354 for _, repo := range repos {
355 to := s.path("trash", "withdrawn-"+filepath.Base(repo)+"-"+random())
356 if err := rename(repo, to); err != nil {
357 return trash, err
358 }
359 trash = append(trash, to)
360 }
361 return trash, syncPath(filepath.Join(g.Dir, "repos"))
362}
363
364// pruneSelected, when it is set, is called by prune once it has selected
365// the repositories to delete and before it takes the authorization lock. A
366// test pauses there.
367var pruneSelected func()