gunk-dev/the-valley

upload.go

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