-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfrisbii_test.go
More file actions
349 lines (314 loc) · 10.6 KB
/
Copy pathfrisbii_test.go
File metadata and controls
349 lines (314 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package frisbii_test
import (
"compress/gzip"
"context"
"io"
"math/rand"
"net/http"
"net/url"
"strconv"
"testing"
"time"
"github.com/ipfs/go-cid"
unixfstestutil "github.com/ipfs/go-unixfsnode/testutil"
"github.com/ipld/frisbii"
"github.com/ipld/go-car/v2"
unixfsgen "github.com/ipld/go-fixtureplate/generator"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/storage/memstore"
"github.com/ipld/go-trustless-utils/testutil"
"github.com/stretchr/testify/require"
)
func TestFrisbiiServer(t *testing.T) {
testCases := []struct {
name string
acceptGzip bool
noClientCompression bool
serverCompressionLevel int
expectGzip bool
}{
{
name: "default",
},
{
name: "no client compression (no server gzip)",
noClientCompression: true,
serverCompressionLevel: gzip.NoCompression,
expectGzip: false,
},
{
name: "no client compression (with server gzip)",
noClientCompression: true,
serverCompressionLevel: gzip.DefaultCompression,
expectGzip: false,
},
{
name: "gzip (with server 1)",
acceptGzip: true,
serverCompressionLevel: gzip.BestSpeed,
expectGzip: true,
},
{
name: "gzip (with server 9)",
acceptGzip: true,
serverCompressionLevel: gzip.BestCompression,
expectGzip: true,
},
{
name: "gzip (no server gzip)",
acceptGzip: true,
serverCompressionLevel: gzip.NoCompression,
expectGzip: false,
},
{
name: "gzip transparent (no server gzip)",
serverCompressionLevel: gzip.NoCompression,
expectGzip: false,
},
{
name: "gzip transparent (with server gzip)",
serverCompressionLevel: gzip.DefaultCompression,
expectGzip: true,
},
}
rndSeed := time.Now().UTC().UnixNano()
t.Logf("random seed: %d", rndSeed)
var rndReader io.Reader = rand.New(rand.NewSource(rndSeed))
store := &testutil.CorrectedMemStore{ParentStore: &memstore.Store{Bag: make(map[string][]byte)}}
lsys := cidlink.DefaultLinkSystem()
lsys.SetReadStorage(store)
lsys.SetWriteStorage(store)
lsys.TrustedStorage = true
entity, err := unixfsgen.Parse("file:1MiB{zero}")
require.NoError(t, err)
t.Logf("Generating: %s", entity.Describe(""))
rootEnt, err := entity.Generate(lsys, rndReader)
require.NoError(t, err)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
opts := []frisbii.HttpOption{
frisbii.WithLogHandler(func(time time.Time, remoteAddr, method string, url url.URL, status int, duration time.Duration, bytes int, compressionRatio, userAgent, msg string) {
t.Logf("%s %s %s %d %s %d %s %s %s", remoteAddr, method, url.String(), status, duration, bytes, compressionRatio, userAgent, msg)
req.Equal("GET", method)
req.Equal("/ipfs/"+rootEnt.Root.String(), url.Path)
req.Equal(http.StatusOK, status)
if tc.expectGzip {
req.NotEqual("-", compressionRatio)
// convert compressionRatio string to a float64
compressionRatio, err := strconv.ParseFloat(compressionRatio, 64)
req.NoError(err)
req.True(compressionRatio > 10, "compression ratio (%s) should be > 10", compressionRatio) // it's all zeros
}
}),
}
if tc.serverCompressionLevel != gzip.NoCompression {
opts = append(opts, frisbii.WithCompressionLevel(tc.serverCompressionLevel))
}
server, err := frisbii.NewFrisbiiServer(ctx, lsys, "localhost:0", opts...)
req.NoError(err)
go func() {
req.NoError(server.Serve())
}()
addr := server.Addr()
request, err := http.NewRequest("GET", "http://"+addr.String()+"/ipfs/"+rootEnt.Root.String(), nil)
request.Header.Set("Accept", "application/vnd.ipld.car")
if tc.acceptGzip {
request.Header.Set("Accept-Encoding", "gzip")
}
req.NoError(err)
request = request.WithContext(ctx)
client := &http.Client{Transport: &http.Transport{DisableCompression: tc.noClientCompression}}
response, err := client.Do(request)
req.NoError(err)
if response.StatusCode != http.StatusOK {
body, _ := io.ReadAll(response.Body)
req.Failf("wrong response code not received", "expected %d, got %d; body: [%s]", http.StatusOK, response.StatusCode, string(body))
}
req.Equal("application/vnd.ipld.car;version=1;order=dfs;dups=y", response.Header.Get("Content-Type"))
req.Equal("Accept, Accept-Encoding", response.Header.Get("Vary"))
rdr := response.Body
if tc.expectGzip {
if tc.noClientCompression || tc.acceptGzip { // in either of these cases we expect to handle it ourselves
req.Equal("gzip", response.Header.Get("Content-Encoding"))
rdr, err = gzip.NewReader(response.Body)
req.NoError(err)
} // else should be handled by the go client
req.Regexp(`^W/"`+rootEnt.Root.String()+`\.car\.\w{2,13}\.gz"$`, response.Header.Get("Etag"))
} else {
req.Regexp(`^W/".*\.car\.\w{12,13}"$`, response.Header.Get("Etag"))
}
cr, err := car.NewBlockReader(rdr)
req.NoError(err)
req.Equal(cr.Version, uint64(1))
req.Equal(cr.Roots, []cid.Cid{rootEnt.Root})
wantCids := toCids(rootEnt)
gotCids := make([]cid.Cid, 0)
for {
blk, err := cr.Next()
if err != nil {
req.ErrorIs(err, io.EOF)
break
}
req.NoError(err)
gotCids = append(gotCids, blk.Cid())
}
req.ElementsMatch(wantCids, gotCids)
})
}
}
func toCids(e unixfstestutil.DirEntry) []cid.Cid {
cids := make([]cid.Cid, 0)
var r func(e unixfstestutil.DirEntry)
r = func(e unixfstestutil.DirEntry) {
cids = append(cids, e.SelfCids...)
for _, c := range e.Children {
r(c)
}
}
r(e)
return cids
}
func TestCacheControlOnlyIfCached(t *testing.T) {
testCases := []struct {
name string
cidExists bool
expectedStatus int
cacheControlHdr string
}{
{
name: "only-if-cached with existing content",
cidExists: true,
expectedStatus: http.StatusOK,
cacheControlHdr: "only-if-cached",
},
{
name: "only-if-cached with missing content",
cidExists: false,
expectedStatus: http.StatusPreconditionFailed,
cacheControlHdr: "only-if-cached",
},
{
name: "no cache-control with existing content",
cidExists: true,
expectedStatus: http.StatusOK,
cacheControlHdr: "",
},
{
name: "no cache-control with missing content",
cidExists: false,
expectedStatus: http.StatusNotFound,
cacheControlHdr: "",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
store := &testutil.CorrectedMemStore{ParentStore: &memstore.Store{Bag: make(map[string][]byte)}}
lsys := cidlink.DefaultLinkSystem()
lsys.SetReadStorage(store)
lsys.SetWriteStorage(store)
lsys.TrustedStorage = true
rndSeed := time.Now().UTC().UnixNano()
var rndReader io.Reader = rand.New(rand.NewSource(rndSeed))
entity, err := unixfsgen.Parse("file:1KiB{zero}")
req.NoError(err)
rootEnt, err := entity.Generate(lsys, rndReader)
req.NoError(err)
// Create a second link system that may or may not have the content
testStore := &testutil.CorrectedMemStore{ParentStore: &memstore.Store{Bag: make(map[string][]byte)}}
testLsys := cidlink.DefaultLinkSystem()
testLsys.SetReadStorage(testStore)
testLsys.SetWriteStorage(testStore)
testLsys.TrustedStorage = true
if tc.cidExists {
// Copy content to test store
testStore.ParentStore.(*memstore.Store).Bag = store.ParentStore.(*memstore.Store).Bag
}
server, err := frisbii.NewFrisbiiServer(ctx, testLsys, "localhost:0")
req.NoError(err)
go func() {
req.NoError(server.Serve())
}()
addr := server.Addr()
request, err := http.NewRequest("GET", "http://"+addr.String()+"/ipfs/"+rootEnt.Root.String(), nil)
req.NoError(err)
request.Header.Set("Accept", "application/vnd.ipld.car")
if tc.cacheControlHdr != "" {
request.Header.Set("Cache-Control", tc.cacheControlHdr)
}
request = request.WithContext(ctx)
client := &http.Client{}
response, err := client.Do(request)
req.NoError(err)
defer response.Body.Close()
req.Equal(tc.expectedStatus, response.StatusCode, "Expected status %d, got %d", tc.expectedStatus, response.StatusCode)
})
}
}
func TestContentDisposition(t *testing.T) {
testCases := []struct {
name string
acceptHeader string
expectedExtension string
expectedMimePrefix string
}{
{
name: "CAR format",
acceptHeader: "application/vnd.ipld.car",
expectedExtension: ".car",
expectedMimePrefix: "application/vnd.ipld.car",
},
{
name: "raw format",
acceptHeader: "application/vnd.ipld.raw",
expectedExtension: ".bin",
expectedMimePrefix: "application/vnd.ipld.raw",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req := require.New(t)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
store := &testutil.CorrectedMemStore{ParentStore: &memstore.Store{Bag: make(map[string][]byte)}}
lsys := cidlink.DefaultLinkSystem()
lsys.SetReadStorage(store)
lsys.SetWriteStorage(store)
lsys.TrustedStorage = true
rndSeed := time.Now().UTC().UnixNano()
var rndReader io.Reader = rand.New(rand.NewSource(rndSeed))
entity, err := unixfsgen.Parse("file:1KiB{zero}")
req.NoError(err)
rootEnt, err := entity.Generate(lsys, rndReader)
req.NoError(err)
server, err := frisbii.NewFrisbiiServer(ctx, lsys, "localhost:0")
req.NoError(err)
go func() {
req.NoError(server.Serve())
}()
addr := server.Addr()
request, err := http.NewRequest("GET", "http://"+addr.String()+"/ipfs/"+rootEnt.Root.String(), nil)
req.NoError(err)
request.Header.Set("Accept", tc.acceptHeader)
request = request.WithContext(ctx)
client := &http.Client{}
response, err := client.Do(request)
req.NoError(err)
defer response.Body.Close()
req.Equal(http.StatusOK, response.StatusCode)
// Check Content-Disposition header
contentDisposition := response.Header.Get("Content-Disposition")
req.Contains(contentDisposition, "attachment")
req.Contains(contentDisposition, "filename=")
req.Contains(contentDisposition, rootEnt.Root.String()+tc.expectedExtension)
// Check Content-Type header
contentType := response.Header.Get("Content-Type")
req.Contains(contentType, tc.expectedMimePrefix)
})
}
}