gunk-dev/the-valley

upload.go

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