gunk-dev/the-valley

upload.go

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