gunk-dev/the-valley

upload_test.go

source4d6ef35777b0main's published tip history
5.6 KiB
1package main
2
3import (
4 "context"
5 "io"
6 "math"
7 "net/http"
8 "net/http/httptest"
9 "os"
10 "path/filepath"
11 "sync"
12 "testing"
13 "time"
14
15 "the-valley/web/export"
16)
17
18// A body's time is its floor and a second for each 256 KiB, up to the cap,
19// and no size makes it less than the floor or overflows it.
20func TestABodysTimeGrowsWithItsSize(t *testing.T) {
21 const mib = 1 << 20
22 for _, c := range []struct {
23 name string
24 size int64
25 want time.Duration
26 }{
27 {"negative", -1, 2 * time.Minute},
28 {"the least", math.MinInt64, 2 * time.Minute},
29 {"empty", 0, 2 * time.Minute},
30 {"part of a second's bytes", 128 << 10, 2*time.Minute + 500*time.Millisecond},
31 {"a small export.json", 2 * mib, 2*time.Minute + 8*time.Second},
32 {"a medium bundle", 25 * mib, 3*time.Minute + 40*time.Second},
33 {"a second below the cap", 420*mib - 256<<10, 30*time.Minute - time.Second},
34 {"at the cap", 420 * mib, 30 * time.Minute},
35 {"past the cap", 4096 * mib, 30 * time.Minute},
36 {"the greatest", math.MaxInt64, 30 * time.Minute},
37 } {
38 if got := bodyTimeoutFor(c.size); got != c.want {
39 t.Errorf("%s: a body of %d bytes may take %s, want %s", c.name, c.size, got, c.want)
40 }
41 }
42}
43
44// The client closes connections a pass leaves idle, probes the ones it
45// uses, and follows no redirect.
46func TestTheClientKeepsNoDeadConnection(t *testing.T) {
47 c := newClient()
48 tr, ok := c.Transport.(*http.Transport)
49 if !ok {
50 t.Fatalf("the client's transport is a %T", c.Transport)
51 }
52 if tr.HTTP2 == nil {
53 t.Fatal("the transport has no HTTP/2 settings")
54 }
55 for _, d := range []struct {
56 name string
57 got, want time.Duration
58 }{
59 {"IdleConnTimeout", tr.IdleConnTimeout, 15 * time.Second},
60 {"HTTP2.SendPingTimeout", tr.HTTP2.SendPingTimeout, 30 * time.Second},
61 {"HTTP2.PingTimeout", tr.HTTP2.PingTimeout, 15 * time.Second},
62 {"ResponseHeaderTimeout", tr.ResponseHeaderTimeout, commitTimeout},
63 } {
64 if d.got != d.want {
65 t.Errorf("%s is %s, want %s", d.name, d.got, d.want)
66 }
67 }
68 if !tr.ForceAttemptHTTP2 {
69 t.Error("the transport does not attempt HTTP/2")
70 }
71
72 elsewhere := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
73 t.Error("the client followed a redirect")
74 }))
75 defer elsewhere.Close()
76 redirects := httptest.NewServer(http.RedirectHandler(elsewhere.URL, http.StatusTemporaryRedirect))
77 defer redirects.Close()
78 res, err := c.Post(redirects.URL, "", nil)
79 if err != nil {
80 t.Fatal(err)
81 }
82 res.Body.Close()
83 if res.StatusCode != http.StatusTemporaryRedirect {
84 t.Errorf("a redirect was answered with %s", res.Status)
85 }
86}
87
88// firstPutTimesOut is the client's transport, with the first PUT's timeout
89// shortened to one a test can wait for.
90type firstPutTimesOut struct {
91 *http.Transport
92 once sync.Once
93}
94
95func (f *firstPutTimesOut) RoundTrip(req *http.Request) (*http.Response, error) {
96 first := false
97 if req.Method == http.MethodPut {
98 f.once.Do(func() { first = true })
99 }
100 if !first {
101 return f.Transport.RoundTrip(req)
102 }
103 ctx, cancel := context.WithTimeout(req.Context(), 500*time.Millisecond)
104 defer cancel()
105 return f.Transport.RoundTrip(req.WithContext(ctx))
106}
107
108// An upload whose first PUT the receiver never answers times out, and the
109// retry sends the body over a new HTTP/2 connection. The pause between
110// them is the real one, since it is what ends the stream that timed out.
111func TestATimedOutBodyIsRetriedOnANewConnection(t *testing.T) {
112 v := &testValley{t: t, state: filepath.Join(t.TempDir(), "state")}
113 rv := newReceiver(t, v)
114 var mu sync.Mutex
115 var puts []string // the connection each PUT came over
116 server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
117 if r.ProtoMajor != 2 {
118 t.Errorf("%s %s came over %s", r.Method, r.URL.Path, r.Proto)
119 }
120 if r.Method == http.MethodPut {
121 mu.Lock()
122 puts = append(puts, r.RemoteAddr)
123 stall := len(puts) == 1
124 mu.Unlock()
125 if stall {
126 <-r.Context().Done()
127 return
128 }
129 }
130 rv.ServeHTTP(w, r)
131 }))
132 server.EnableHTTP2 = true
133 server.StartTLS()
134 defer server.Close()
135
136 client := newClient()
137 tr := client.Transport.(*http.Transport)
138 tr.TLSClientConfig = server.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
139 client.Transport = &firstPutTimesOut{Transport: tr}
140 defer client.CloseIdleConnections()
141 p := &publisher{
142 cfg: config{state: v.state, instance: instanceName, destination: destination, receiver: server.URL,
143 maxBundles: 1 << 20, maxStorage: 1 << 20},
144 cache: filepath.Join(t.TempDir(), "valley-web-publish"), signer: instanceName + "/web-export", token: rv.token,
145 client: client, now: time.Now, sleep: sleepContext, stdout: io.Discard, stderr: io.Discard,
146 }
147 if err := os.MkdirAll(v.state, 0o700); err != nil {
148 t.Fatal(err)
149 }
150 var err error
151 if p.key, err = p.loadKey(); err != nil {
152 t.Fatal(err)
153 }
154 e := &export.Export{Schema: export.Schema, Collected: "2000-01-01T00:00:00Z", Projects: []export.Project{}}
155 data, err := e.Encode()
156 if err != nil {
157 t.Fatal(err)
158 }
159 digest, err := e.Digest()
160 if err != nil {
161 t.Fatal(err)
162 }
163
164 if err := p.upload(context.Background(), &reading{export: e, json: data}, digest, acknowledged{}); err != nil {
165 t.Fatalf("the upload failed: %v", err)
166 }
167 sameRequests(t, "the upload", rv.taken(), "manifest", "manifest", "body export.json", "commit")
168 mu.Lock()
169 defer mu.Unlock()
170 if len(puts) != 2 || puts[0] == puts[1] {
171 t.Errorf("the PUTs came over the connections %q, want two different ones", puts)
172 }
173 ack, err := p.readAcknowledged()
174 if err != nil {
175 t.Fatal(err)
176 }
177 if ack.Digest != digest || ack.Sequence == 0 {
178 t.Errorf("the upload is acknowledged as digest %q, sequence %d, want digest %q", ack.Digest, ack.Sequence, digest)
179 }
180}