gunk-dev/the-valley

upload.go

sourcee5e09626b3e3main's published tip history
19.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 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 token, the manifest or a
326// body is wrong, or that the clocks disagree by more than the receiver's
327// window, and the operator has to see it. Out-of-window is the last of
328// those.
329func (p *publisher) upload(ctx context.Context, r *reading, digest string, ack acknowledged) error {
330 paths, bodies, err := p.bundles(ctx, r)
331 if err != nil {
332 return err
333 }
334 rc := receiver{base: strings.TrimSuffix(p.cfg.receiver, "/"), token: p.token, client: p.client}
335 highWater := ack.Sequence
336 var m *export.Manifest
337 var signed []byte
338 backoff := firstBackoff
339 for attempt := 1; ; attempt++ {
340 if m == nil {
341 seq, err := p.sequenceAfter(ctx, highWater)
342 if err != nil {
343 return err
344 }
345 if m, signed, err = p.sign(r, bodies, seq); err != nil {
346 return err
347 }
348 }
349 active, err := p.send(ctx, rc, m, signed, r.json, paths, digest)
350 if err == nil {
351 return p.recordAcknowledged(digest, active)
352 }
353 if ctx.Err() != nil {
354 return ctx.Err()
355 }
356 if attempt == uploadAttempts {
357 return fmt.Errorf("the upload failed %d times: %w", attempt, err)
358 }
359 pause := time.Duration(0)
360 var refusal *export.Error
361 switch {
362 case !errors.As(err, &refusal) || refusal.Code == export.CodeUnreadable:
363 pause, backoff = backoff, 2*backoff
364 case refusal.Code == export.CodeIncomplete:
365 case refusal.Code == export.CodeReplayed:
366 highWater = max(highWater, refusal.HighWater)
367 m = nil
368 case refusal.Code == export.CodeSuperseded || refusal.Code == export.CodeNoManifest:
369 pause, backoff = backoff, 2*backoff
370 m = nil
371 case refusal.Code == export.CodeOutOfWindow:
372 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)
373 default:
374 return fmt.Errorf("the receiver refused the upload: %w", err)
375 }
376 p.warn("%v; trying again", err)
377 if err := p.sleep(ctx, pause); err != nil {
378 return err
379 }
380 }
381}
382
383// sequenceAfter is a sequence for a new manifest: the clock now, in Unix
384// nanoseconds, once it is past the greatest sequence the receiver is known
385// to have accepted. The clock is waited for when it is close behind, and
386// is otherwise a fault: publishing out of order is never done.
387func (p *publisher) sequenceAfter(ctx context.Context, highWater int64) (int64, error) {
388 seq := p.now().UnixNano()
389 if seq > highWater {
390 return seq, nil
391 }
392 behind := time.Duration(highWater-seq) + time.Millisecond
393 if behind > maxClockWait {
394 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))
395 }
396 if err := p.sleep(ctx, behind); err != nil {
397 return 0, err
398 }
399 if seq = p.now().UnixNano(); seq <= highWater {
400 return 0, fmt.Errorf("this host's clock did not pass the receiver's sequence %d", highWater)
401 }
402 return seq, nil
403}
404
405// send is one attempt at the three steps. It returns the sequence the
406// receiver serves the export as: the active one when the inventory shows
407// it already serves this digest and needs no bundle, and otherwise the
408// manifest's, once committed.
409func (p *publisher) send(ctx context.Context, rc receiver, m *export.Manifest, signed, exportJSON []byte,
410 bundles map[string]string, digest string) (int64, error) {
411 inv, err := rc.postManifest(ctx, signed)
412 if err != nil {
413 return 0, err
414 }
415 if inv.Sequence != m.Sequence {
416 return 0, fmt.Errorf("the receiver's inventory is for sequence %d, not %d", inv.Sequence, m.Sequence)
417 }
418 needsBundle := false
419 for _, n := range inv.Needs {
420 needsBundle = needsBundle || n.Name != export.ExportFile
421 }
422 if inv.Active != nil && inv.Active.Digest == digest && !needsBundle {
423 p.say("the receiver serves this export already, as sequence %d; nothing is sent", inv.Active.Sequence)
424 return inv.Active.Sequence, nil
425 }
426 declared := map[string]export.Body{}
427 for _, b := range m.Bodies() {
428 declared[b.SHA256] = b
429 }
430 var sent []string
431 for _, n := range inv.Needs {
432 b, ok := declared[n.SHA256]
433 if !ok || b.Size != n.Size {
434 return 0, fmt.Errorf("the receiver needs a body, %s %s, that the manifest does not declare", n.Name, n.SHA256)
435 }
436 open := func() (io.ReadCloser, error) { return os.Open(bundles[b.Name]) }
437 if b.Name == export.ExportFile {
438 open = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(exportJSON)), nil }
439 }
440 if err := rc.putBody(ctx, m.Sequence, b, open); err != nil {
441 return 0, err
442 }
443 sent = append(sent, b.Name)
444 }
445 c, err := rc.commit(ctx, m.Sequence)
446 if err != nil {
447 return 0, err
448 }
449 if c.Sequence != m.Sequence {
450 return 0, fmt.Errorf("the receiver committed sequence %d, not %d", c.Sequence, m.Sequence)
451 }
452 if len(sent) == 0 {
453 sent = []string{"nothing"}
454 }
455 p.say("sent %s; the receiver activated sequence %d, digest %s", strings.Join(sent, ", "), c.Sequence, short(digest))
456 return c.Sequence, nil
457}
458
459// receiver is the receiver's upload endpoints under its base URL, and the
460// token every request to them carries.
461type receiver struct {
462 base string
463 token string
464 client *http.Client
465}
466
467// checkReceiver holds --receiver to an http or https URL with a host, and
468// no query or fragment the paths would be appended after.
469func checkReceiver(raw string) error {
470 u, err := url.Parse(raw)
471 if err != nil {
472 return fmt.Errorf("--receiver %q: %w", raw, err)
473 }
474 if (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
475 return fmt.Errorf("--receiver %q is not an http or https URL with a host, and no user, query or fragment", raw)
476 }
477 return nil
478}
479
480// newClient is the HTTP client uploads are made with. It follows no
481// redirect: the receiver is the URL configured, and neither a POST nor
482// the token is ever sent elsewhere.
483func newClient() *http.Client {
484 return &http.Client{
485 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
486 Transport: &http.Transport{
487 Proxy: http.ProxyFromEnvironment,
488 DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
489 TLSHandshakeTimeout: 30 * time.Second,
490 ResponseHeaderTimeout: commitTimeout,
491 IdleConnTimeout: 90 * time.Second,
492 ForceAttemptHTTP2: true,
493 },
494 }
495}
496
497// postManifest is step 1.
498func (rc receiver) postManifest(ctx context.Context, signed []byte) (export.Inventory, error) {
499 var inv export.Inventory
500 err := rc.do(ctx, manifestTimeout, http.MethodPost, export.ManifestPath, "text/plain; charset=utf-8",
501 func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(signed)), nil },
502 int64(len(signed)), http.StatusOK, export.InventorySchema, &inv)
503 return inv, err
504}
505
506// putBody is step 2, for one body: its bytes as they are, with their
507// declared size as the Content-Length and no Content-Encoding.
508func (rc receiver) putBody(ctx context.Context, sequence int64, b export.Body, open func() (io.ReadCloser, error)) error {
509 return rc.do(ctx, bodyTimeout, http.MethodPut, export.BodyPath(sequence, b.SHA256), "application/octet-stream",
510 open, b.Size, http.StatusNoContent, "", nil)
511}
512
513// commit is step 3.
514func (rc receiver) commit(ctx context.Context, sequence int64) (export.Committed, error) {
515 var c export.Committed
516 err := rc.do(ctx, commitTimeout, http.MethodPost, export.CommitPath(sequence), "",
517 nil, 0, http.StatusOK, export.CommittedSchema, &c)
518 return c, err
519}
520
521// do makes one request and reads its reply. A refusal the receiver replies
522// with is returned as an *export.Error; any other failure, in transit or
523// a status with no refusal in it, is an error of its own, which upload
524// retries.
525func (rc receiver) do(ctx context.Context, timeout time.Duration, method, path, contentType string,
526 open func() (io.ReadCloser, error), size int64, wantStatus int, schema string, into any) error {
527 ctx, cancel := context.WithTimeout(ctx, timeout)
528 defer cancel()
529 var body io.ReadCloser = http.NoBody
530 if open != nil {
531 var err error
532 if body, err = open(); err != nil {
533 return err
534 }
535 }
536 req, err := http.NewRequestWithContext(ctx, method, rc.base+path, body)
537 if err != nil {
538 body.Close()
539 return err
540 }
541 req.ContentLength = size
542 if size == 0 {
543 req.Body = http.NoBody
544 }
545 if contentType != "" {
546 req.Header.Set("Content-Type", contentType)
547 }
548 req.Header.Set("Authorization", export.Authorization(rc.token))
549 resp, err := rc.client.Do(req)
550 if err != nil {
551 return fmt.Errorf("%s %s: %w", method, path, err)
552 }
553 defer resp.Body.Close()
554 reply, err := io.ReadAll(io.LimitReader(resp.Body, maxReply+1))
555 if err != nil {
556 return fmt.Errorf("%s %s: reading the reply: %w", method, path, err)
557 }
558 if len(reply) > maxReply {
559 return fmt.Errorf("%s %s: the reply is longer than %d bytes", method, path, maxReply)
560 }
561 if resp.StatusCode != wantStatus {
562 var refusal export.ErrorReply
563 if json.Unmarshal(reply, &refusal) == nil && refusal.Schema == export.ErrorSchema && refusal.Code != "" {
564 return &export.Error{Code: refusal.Code, Message: refusal.Message, HighWater: refusal.HighWater, Needs: refusal.Needs}
565 }
566 return fmt.Errorf("%s %s: the receiver replied %s", method, path, resp.Status)
567 }
568 if into == nil {
569 return nil
570 }
571 var head struct {
572 Schema string `json:"schema"`
573 }
574 if err := json.Unmarshal(reply, &head); err != nil || head.Schema != schema {
575 return fmt.Errorf("%s %s: the reply is not %s", method, path, schema)
576 }
577 if err := json.Unmarshal(reply, into); err != nil {
578 return fmt.Errorf("%s %s: the reply is not %s: %w", method, path, schema, err)
579 }
580 return nil
581}