gunk-dev/the-valley

upload.go

sourcec14b0e68e9c3main's published tip history
20.6 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "net"
12 "net/http"
13 "net/url"
14 "os"
15 "path/filepath"
16 "strings"
17 "time"
18
19 "the-valley/web/export"
20)
21
22// How an upload is retried. A pass makes at most uploadAttempts attempts.
23// It waits for its clock to pass a receiver's high-water mark only when
24// that is at most maxClockWait away; a mark further ahead is a clock fault
25// the operator has to see, and the next pass tries again.
26const (
27 uploadAttempts = 5
28 maxClockWait = 2 * export.MaxAhead
29 firstBackoff = 2 * time.Second
30)
31
32// How long each request may take. A commit waits for the receiver to
33// fetch and check every bundle it was sent.
34const (
35 authorizationTimeout = time.Minute
36 manifestTimeout = 2 * time.Minute
37 bodyTimeout = 30 * time.Minute
38 commitTimeout = 30 * time.Minute
39 maxReply = 1 << 20
40)
41
42// bundles are each exported project's bundle of main, by project: the
43// file, and the body it makes. A bundle is made once for each source tip
44// and kept in the cache, so the body a manifest declares for a tip is the
45// same in every pass. The bundles the export does not declare are removed
46// first. Each bundle still to be made is then written only into the room
47// --max-bundles and --max-storage leave: its writing stops there, and the
48// pass then removes every bundle it wrote and sends nothing.
49func (p *publisher) bundles(ctx context.Context, r *reading) (map[string]string, map[string]export.Body, error) {
50 root := filepath.Join(p.cache, "bundles")
51 paths := map[string]string{}
52 for _, proj := range r.export.Projects {
53 paths[proj.Name] = filepath.Join(root, proj.Name, proj.SourceTip+".bundle")
54 }
55 pruneBundles(root, paths)
56 used, err := p.storageUsed()
57 if err != nil {
58 return nil, nil, err
59 }
60 var held int64 // what the export's bundles hold together
61 var missing []export.Project
62 for _, proj := range r.export.Projects {
63 info, err := os.Stat(paths[proj.Name])
64 switch {
65 case errors.Is(err, os.ErrNotExist):
66 missing = append(missing, proj)
67 case err != nil:
68 return nil, nil, err
69 default:
70 held += info.Size()
71 }
72 }
73 if held > int64(p.cfg.maxBundles) {
74 return nil, nil, fmt.Errorf("the bundles hold %d bytes together, more than --max-bundles %d, so the pass sends nothing", held, p.cfg.maxBundles)
75 }
76 if used > int64(p.cfg.maxStorage) {
77 return nil, nil, p.overStorage(used)
78 }
79 var made []string
80 for _, proj := range missing {
81 room, bound := int64(p.cfg.maxBundles)-held, fmt.Sprintf("--max-bundles %d", p.cfg.maxBundles)
82 if left := int64(p.cfg.maxStorage) - used; left < room {
83 room, bound = left, fmt.Sprintf("--max-storage %d", p.cfg.maxStorage)
84 }
85 size, err := makeBundle(ctx, r.mirrors[proj.Name], paths[proj.Name], proj.SourceTip, room)
86 if errors.Is(err, errOverBudget) {
87 err = fmt.Errorf("its bundle is larger than the %d bytes %s leaves for it, so the pass sends nothing and removes the bundles it wrote", room, bound)
88 }
89 if err != nil {
90 // Each bundle's directory goes with it, once it is empty.
91 for _, path := range append(made, paths[proj.Name]) {
92 os.Remove(path)
93 os.Remove(filepath.Dir(path))
94 }
95 return nil, nil, fmt.Errorf("%s: %w", proj.Name, err)
96 }
97 made = append(made, paths[proj.Name])
98 held += size
99 used += size
100 }
101 bodies := map[string]export.Body{}
102 for name, path := range paths {
103 if bodies[name], err = export.FileBody(name, path); err != nil {
104 return nil, nil, err
105 }
106 }
107 return paths, bodies, nil
108}
109
110// pruneBundles removes everything under root but the bundles keep names:
111// the bundles of a project's earlier tips, of projects the export does not
112// hold, and what a pass that was stopped left of one it was writing.
113func pruneBundles(root string, keep map[string]string) {
114 projects, _ := os.ReadDir(root)
115 for _, d := range projects {
116 dir := filepath.Join(root, d.Name())
117 if _, ok := keep[d.Name()]; !ok || !d.IsDir() {
118 os.RemoveAll(dir)
119 continue
120 }
121 files, _ := os.ReadDir(dir)
122 for _, f := range files {
123 if path := filepath.Join(dir, f.Name()); path != keep[d.Name()] {
124 os.RemoveAll(path)
125 }
126 }
127 }
128}
129
130// checkStorage holds the state directory and the caches to --max-storage.
131// A pass checks before it fetches anything, and again once it has read the
132// valley, whether it then sends anything or not.
133func (p *publisher) checkStorage() error {
134 used, err := p.storageUsed()
135 if err != nil {
136 return err
137 }
138 if used > int64(p.cfg.maxStorage) {
139 return p.overStorage(used)
140 }
141 return nil
142}
143
144func (p *publisher) overStorage(used int64) error {
145 return fmt.Errorf("the state directory and the cache hold %d bytes, more than --max-storage %d, so the pass sends nothing", used, p.cfg.maxStorage)
146}
147
148// storageUsed is the size of every regular file the publisher keeps: in
149// its state directory, its cache, and the valley CLI's cache beside it,
150// which holds the CLI's clones of every project.
151func (p *publisher) storageUsed() (int64, error) {
152 var total int64
153 for _, dir := range []string{p.cfg.state, p.cache, filepath.Join(filepath.Dir(p.cache), "valley")} {
154 err := filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
155 if err == nil && d.Type().IsRegular() {
156 var info fs.FileInfo
157 if info, err = d.Info(); err == nil {
158 total += info.Size()
159 }
160 }
161 if errors.Is(err, fs.ErrNotExist) {
162 return nil
163 }
164 return err
165 })
166 if err != nil {
167 return 0, err
168 }
169 }
170 return total, nil
171}
172
173// errOverBudget is makeBundle's error for a bundle larger than the room
174// it is given.
175var errOverBudget = errors.New("the bundle is larger than the room left for it")
176
177// makeBundle writes a full bundle of the mirror's main to path, and returns
178// its size. git writes the bundle to its stdout, and the publisher writes
179// it to a temporary name, which is renamed into place once git bundle
180// list-heads shows it carries main at tip. At most room bytes reach the
181// file: a write past them fails, which ends git at its next write, and
182// makeBundle removes the file and returns errOverBudget.
183func makeBundle(ctx context.Context, mirror, path, tip string, room int64) (int64, error) {
184 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
185 return 0, err
186 }
187 tmp := path + ".new"
188 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
189 if err != nil {
190 return 0, err
191 }
192 defer os.Remove(tmp)
193 w := &budgeted{w: f, room: room}
194 err = gitStream(ctx, mirror, nil, w, "bundle", "create", "--quiet", "-", export.MainRef)
195 if cerr := f.Close(); err == nil {
196 err = cerr
197 }
198 if w.over {
199 return 0, errOverBudget
200 }
201 if err != nil {
202 return 0, err
203 }
204 heads, err := git(ctx, mirror, "bundle", "list-heads", tmp)
205 if err != nil {
206 return 0, err
207 }
208 if got, want := strings.TrimSpace(string(heads)), tip+" "+export.MainRef; got != want {
209 return 0, fmt.Errorf("the bundle made of main carries %q, not %q", got, want)
210 }
211 return w.written, os.Rename(tmp, path)
212}
213
214// budgeted writes through to w until room bytes are written. A write that
215// would pass room writes nothing, fails, and sets over. It is no
216// io.ReaderFrom, so os/exec copies through Write.
217type budgeted struct {
218 w io.Writer
219 room, written int64
220 over bool
221}
222
223func (b *budgeted) Write(p []byte) (int, error) {
224 if int64(len(p)) > b.room-b.written {
225 b.over = true
226 return 0, errOverBudget
227 }
228 n, err := b.w.Write(p)
229 b.written += int64(n)
230 return n, err
231}
232
233// writeOut writes the export to --out, as a pass would send it: the
234// signed authorization, the signed manifest, export.json, and
235// bundles/<project>.bundle. The
236// directory is written beside its place and renamed into it whole, so a
237// reader never sees part of it.
238func (p *publisher) writeOut(ctx context.Context, r *reading) error {
239 dir := p.cfg.out
240 if entries, err := os.ReadDir(dir); err == nil && len(entries) > 0 {
241 return fmt.Errorf("--out %s is not empty", dir)
242 } else if err != nil && !errors.Is(err, os.ErrNotExist) {
243 return err
244 }
245 paths, bodies, err := p.bundles(ctx, r)
246 if err != nil {
247 return err
248 }
249 m, signed, err := p.sign(r, bodies, p.now().UnixNano())
250 if err != nil {
251 return err
252 }
253 parent := filepath.Dir(filepath.Clean(dir))
254 tmp, err := os.MkdirTemp(parent, "."+filepath.Base(dir)+".new-")
255 if err != nil {
256 return err
257 }
258 defer os.RemoveAll(tmp)
259 if err := os.WriteFile(filepath.Join(tmp, "manifest"), signed, 0o644); err != nil {
260 return err
261 }
262 if err := os.WriteFile(filepath.Join(tmp, authorizationFile), p.signedAuthorization, 0o644); err != nil {
263 return err
264 }
265 if err := os.WriteFile(filepath.Join(tmp, export.ExportFile), r.json, 0o644); err != nil {
266 return err
267 }
268 if err := os.Mkdir(filepath.Join(tmp, "bundles"), 0o755); err != nil {
269 return err
270 }
271 for name, path := range paths {
272 if err := copyFile(path, filepath.Join(tmp, "bundles", name+".bundle")); err != nil {
273 return err
274 }
275 }
276 if err := os.Chmod(tmp, 0o755); err != nil {
277 return err
278 }
279 if err := os.Rename(tmp, dir); err != nil {
280 return err
281 }
282 p.say("wrote the export to %s, as sequence %d", dir, m.Sequence)
283 return nil
284}
285
286func copyFile(from, to string) error {
287 in, err := os.Open(from)
288 if err != nil {
289 return err
290 }
291 defer in.Close()
292 out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
293 if err != nil {
294 return err
295 }
296 if _, err := io.Copy(out, in); err != nil {
297 out.Close()
298 return err
299 }
300 return out.Close()
301}
302
303// sign makes and signs the manifest for the export, with the sequence
304// given.
305func (p *publisher) sign(r *reading, bodies map[string]export.Body, sequence int64) (*export.Manifest, []byte, error) {
306 m, err := export.NewManifest(p.cfg.instance, p.cfg.destination, sequence, r.export, r.json, bodies)
307 if err != nil {
308 return nil, nil, err
309 }
310 signed, err := m.Sign(p.signer, p.key)
311 if err != nil {
312 return nil, nil, err
313 }
314 return m, signed, nil
315}
316
317// upload sends the export to the receiver, by the protocol package export
318// defines, and records the receiver's acknowledgement. It retries:
319//
320// - a request that failed in transit, that the receiver answered with a
321// status and no refusal, or that it refused as unreadable, with the
322// same manifest, after a pause that doubles each time; the receiver
323// keeps the bodies already sent;
324// - incomplete, with the same manifest, whose inventory names what is
325// still needed;
326// - replayed, with a manifest signed once the clock has passed the
327// receiver's high-water mark, waiting for it when it is close;
328// - superseded and no-manifest, with a new manifest, after a pause.
329//
330// Every other refusal ends the pass: it says the token, the manifest or a
331// body is wrong, or that the clocks disagree by more than the receiver's
332// window, and the operator has to see it. Out-of-window is the last of
333// those.
334func (p *publisher) upload(ctx context.Context, r *reading, digest string, ack acknowledged) error {
335 paths, bodies, err := p.bundles(ctx, r)
336 if err != nil {
337 return err
338 }
339 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
340 highWater := ack.Sequence
341 var m *export.Manifest
342 var signed []byte
343 backoff := firstBackoff
344 for attempt := 1; ; attempt++ {
345 if m == nil {
346 seq, err := p.sequenceAfter(ctx, highWater)
347 if err != nil {
348 return err
349 }
350 if m, signed, err = p.sign(r, bodies, seq); err != nil {
351 return err
352 }
353 }
354 active, err := p.send(ctx, rc, m, signed, r.json, paths, digest)
355 if err == nil {
356 return p.recordAcknowledged(digest, active)
357 }
358 if ctx.Err() != nil {
359 return ctx.Err()
360 }
361 if attempt == uploadAttempts {
362 return fmt.Errorf("the upload failed %d times: %w", attempt, err)
363 }
364 pause := time.Duration(0)
365 var refusal *export.Error
366 switch {
367 case !errors.As(err, &refusal) || refusal.Code == export.CodeUnreadable:
368 pause, backoff = backoff, 2*backoff
369 case refusal.Code == export.CodeIncomplete:
370 case refusal.Code == export.CodeReplayed:
371 highWater = max(highWater, refusal.HighWater)
372 m = nil
373 case refusal.Code == export.CodeSuperseded || refusal.Code == export.CodeNoManifest:
374 pause, backoff = backoff, 2*backoff
375 m = nil
376 case refusal.Code == export.CodeOutOfWindow:
377 return fmt.Errorf("the receiver refused the manifest signed at %s: %s; check this host's clock and the receiver's", m.SignedAt().Format(time.RFC3339), refusal.Message)
378 default:
379 return fmt.Errorf("the receiver refused the upload: %w", err)
380 }
381 p.warn("%v; trying again", err)
382 if err := p.sleep(ctx, pause); err != nil {
383 return err
384 }
385 }
386}
387
388// sequenceAfter is a sequence for a new manifest: the clock now, in Unix
389// nanoseconds, once it is past the greatest sequence the receiver is known
390// to have accepted. The clock is waited for when it is close behind, and
391// is otherwise a fault: publishing out of order is never done.
392func (p *publisher) sequenceAfter(ctx context.Context, highWater int64) (int64, error) {
393 seq := p.now().UnixNano()
394 if seq > highWater {
395 return seq, nil
396 }
397 behind := time.Duration(highWater-seq) + time.Millisecond
398 if behind > maxClockWait {
399 return 0, fmt.Errorf("the receiver has accepted sequence %d (signed at %s), and this host's clock is %s behind it; that exceeds the 2m wait limit, so the pass fails", highWater, time.Unix(0, highWater).UTC().Format(time.RFC3339), behind.Round(time.Second))
400 }
401 if err := p.sleep(ctx, behind); err != nil {
402 return 0, err
403 }
404 if seq = p.now().UnixNano(); seq <= highWater {
405 return 0, fmt.Errorf("this host's clock did not pass the receiver's sequence %d", highWater)
406 }
407 return seq, nil
408}
409
410// send is one attempt at the three steps. It returns the sequence the
411// receiver serves the export as: the active one when the inventory shows
412// it already serves this digest and needs no bundle, and otherwise the
413// manifest's, once committed.
414func (p *publisher) send(ctx context.Context, rc receiver, m *export.Manifest, signed, exportJSON []byte,
415 bundles map[string]string, digest string) (int64, error) {
416 inv, err := rc.postManifest(ctx, signed)
417 if err != nil {
418 return 0, err
419 }
420 if inv.Sequence != m.Sequence {
421 return 0, fmt.Errorf("the receiver's inventory is for sequence %d, not %d", inv.Sequence, m.Sequence)
422 }
423 needsBundle := false
424 for _, n := range inv.Needs {
425 needsBundle = needsBundle || n.Name != export.ExportFile
426 }
427 if inv.Active != nil && inv.Active.Digest == digest && !needsBundle {
428 p.say("the receiver serves this export already, as sequence %d; nothing is sent", inv.Active.Sequence)
429 return inv.Active.Sequence, nil
430 }
431 declared := map[string]export.Body{}
432 for _, b := range m.Bodies() {
433 declared[b.SHA256] = b
434 }
435 var sent []string
436 for _, n := range inv.Needs {
437 b, ok := declared[n.SHA256]
438 if !ok || b.Size != n.Size {
439 return 0, fmt.Errorf("the receiver needs a body, %s %s, that the manifest does not declare", n.Name, n.SHA256)
440 }
441 open := func() (io.ReadCloser, error) { return os.Open(bundles[b.Name]) }
442 if b.Name == export.ExportFile {
443 open = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(exportJSON)), nil }
444 }
445 if err := rc.putBody(ctx, m.Sequence, b, open); err != nil {
446 return 0, err
447 }
448 sent = append(sent, b.Name)
449 }
450 c, err := rc.commit(ctx, m.Sequence)
451 if err != nil {
452 return 0, err
453 }
454 if c.Sequence != m.Sequence {
455 return 0, fmt.Errorf("the receiver committed sequence %d, not %d", c.Sequence, m.Sequence)
456 }
457 if len(sent) == 0 {
458 sent = []string{"nothing"}
459 }
460 p.say("sent %s; the receiver activated sequence %d, digest %s", strings.Join(sent, ", "), c.Sequence, short(digest))
461 return c.Sequence, nil
462}
463
464// receiver is the receiver's upload endpoints under its base URL, and the
465// token every request to them carries.
466type receiver struct {
467 base string
468 token string
469 client *http.Client
470}
471
472// checkReceiver holds --receiver to an http or https URL with a host, and
473// no query or fragment the paths would be appended after.
474func checkReceiver(raw string) error {
475 u, err := url.Parse(raw)
476 if err != nil {
477 return fmt.Errorf("--receiver %q: %w", raw, err)
478 }
479 if (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
480 return fmt.Errorf("--receiver %q is not an http or https URL with a host, and no user, query or fragment", raw)
481 }
482 return nil
483}
484
485// newClient is the HTTP client uploads are made with. It follows no
486// redirect and uses no proxy: it connects to the receiver configured, and
487// neither a POST nor the token is ever sent elsewhere.
488func newClient() *http.Client {
489 return &http.Client{
490 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
491 Transport: &http.Transport{
492 DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
493 TLSHandshakeTimeout: 30 * time.Second,
494 ResponseHeaderTimeout: commitTimeout,
495 IdleConnTimeout: 90 * time.Second,
496 ForceAttemptHTTP2: true,
497 },
498 }
499}
500
501// postAuthorization posts a signed authorization.
502func (rc receiver) postAuthorization(ctx context.Context, signed []byte) (export.AuthorizationReply, error) {
503 var reply export.AuthorizationReply
504 err := rc.do(ctx, authorizationTimeout, http.MethodPost, export.AuthorizationPath, "text/plain; charset=utf-8",
505 func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(signed)), nil },
506 int64(len(signed)), http.StatusOK, export.AuthorizedSchema, &reply)
507 return reply, err
508}
509
510// statusError is a reply with a status other than the one wanted, and no
511// refusal in it.
512type statusError struct {
513 method, path, status string
514 code int
515}
516
517func (e statusError) Error() string {
518 return fmt.Sprintf("%s %s: the receiver replied %s", e.method, e.path, e.status)
519}
520
521// postManifest is step 1.
522func (rc receiver) postManifest(ctx context.Context, signed []byte) (export.Inventory, error) {
523 var inv export.Inventory
524 err := rc.do(ctx, manifestTimeout, http.MethodPost, export.ManifestPath, "text/plain; charset=utf-8",
525 func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(signed)), nil },
526 int64(len(signed)), http.StatusOK, export.InventorySchema, &inv)
527 return inv, err
528}
529
530// putBody is step 2, for one body: its bytes as they are, with their
531// declared size as the Content-Length and no Content-Encoding.
532func (rc receiver) putBody(ctx context.Context, sequence int64, b export.Body, open func() (io.ReadCloser, error)) error {
533 return rc.do(ctx, bodyTimeout, http.MethodPut, export.BodyPath(sequence, b.SHA256), "application/octet-stream",
534 open, b.Size, http.StatusNoContent, "", nil)
535}
536
537// commit is step 3.
538func (rc receiver) commit(ctx context.Context, sequence int64) (export.Committed, error) {
539 var c export.Committed
540 err := rc.do(ctx, commitTimeout, http.MethodPost, export.CommitPath(sequence), "",
541 nil, 0, http.StatusOK, export.CommittedSchema, &c)
542 return c, err
543}
544
545// do makes one request and reads its reply. A refusal the receiver replies
546// with is returned as an *export.Error; any other failure, in transit or
547// a status with no refusal in it, is an error of its own, which upload
548// retries.
549func (rc receiver) do(ctx context.Context, timeout time.Duration, method, path, contentType string,
550 open func() (io.ReadCloser, error), size int64, wantStatus int, schema string, into any) error {
551 ctx, cancel := context.WithTimeout(ctx, timeout)
552 defer cancel()
553 var body io.ReadCloser = http.NoBody
554 if open != nil {
555 var err error
556 if body, err = open(); err != nil {
557 return err
558 }
559 }
560 req, err := http.NewRequestWithContext(ctx, method, rc.base+path, body)
561 if err != nil {
562 body.Close()
563 return err
564 }
565 req.ContentLength = size
566 if size == 0 {
567 req.Body = http.NoBody
568 }
569 if contentType != "" {
570 req.Header.Set("Content-Type", contentType)
571 }
572 req.Header.Set("Authorization", export.BearerHeader(rc.token))
573 resp, err := rc.client.Do(req)
574 if err != nil {
575 return fmt.Errorf("%s %s: %w", method, path, err)
576 }
577 defer resp.Body.Close()
578 reply, err := io.ReadAll(io.LimitReader(resp.Body, maxReply+1))
579 if err != nil {
580 return fmt.Errorf("%s %s: reading the reply: %w", method, path, err)
581 }
582 if len(reply) > maxReply {
583 return fmt.Errorf("%s %s: the reply is longer than %d bytes", method, path, maxReply)
584 }
585 if resp.StatusCode != wantStatus {
586 var refusal export.ErrorReply
587 if json.Unmarshal(reply, &refusal) == nil && refusal.Schema == export.ErrorSchema && refusal.Code != "" {
588 return &export.Error{Code: refusal.Code, Message: refusal.Message, HighWater: refusal.HighWater, Needs: refusal.Needs}
589 }
590 return statusError{method: method, path: path, status: resp.Status, code: resp.StatusCode}
591 }
592 if into == nil {
593 return nil
594 }
595 var head struct {
596 Schema string `json:"schema"`
597 }
598 if err := json.Unmarshal(reply, &head); err != nil || head.Schema != schema {
599 return fmt.Errorf("%s %s: the reply is not %s", method, path, schema)
600 }
601 if err := json.Unmarshal(reply, into); err != nil {
602 return fmt.Errorf("%s %s: the reply is not %s: %w", method, path, schema, err)
603 }
604 return nil
605}