gunk-dev/the-valley

authorize.go

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