-
Notifications
You must be signed in to change notification settings - Fork 17
/
e2e_retrieve_test.go
343 lines (297 loc) · 10.1 KB
/
e2e_retrieve_test.go
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
package provider_test
import (
"context"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
datatransfer "github.com/filecoin-project/go-data-transfer/v2"
retrievaltypes "github.com/filecoin-project/go-retrieval-types"
blockstore "github.com/ipfs/boxo/blockstore"
"github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
"github.com/ipfs/go-graphsync/storeutil"
"github.com/ipld/go-car/v2"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
selectorparse "github.com/ipld/go-ipld-prime/traversal/selector/parse"
"github.com/ipni/go-libipni/dagsync"
"github.com/ipni/go-libipni/ingest/schema"
"github.com/ipni/go-libipni/metadata"
provider "github.com/ipni/index-provider"
"github.com/ipni/index-provider/cardatatransfer"
"github.com/ipni/index-provider/engine"
"github.com/ipni/index-provider/supplier"
"github.com/ipni/index-provider/testutil"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/require"
)
const testTopic = "test/topic"
type testCase struct {
name string
serverConfigOpts func(*testing.T) []engine.Option
}
var testCases = []testCase{
{
name: "Libp2p Publisher",
serverConfigOpts: func(t *testing.T) []engine.Option {
// Use env var to signal what publisher kind is being used.
setPubKindEnvVarKey(t, engine.Libp2pPublisher)
return []engine.Option{
engine.WithTopicName(testTopic),
engine.WithPublisherKind(engine.Libp2pPublisher),
}
},
},
{
name: "HTTP Publisher",
serverConfigOpts: func(t *testing.T) []engine.Option {
// Use env var to signal what publisher kind is being used.
setPubKindEnvVarKey(t, engine.HttpPublisher)
return []engine.Option{
engine.WithTopicName(testTopic),
engine.WithPublisherKind(engine.HttpPublisher),
}
},
},
}
// setPubKindEnvVarKey to signal to newTestServer, which publisher kind is being used so that
// the test server can be configured correctly.
func setPubKindEnvVarKey(t *testing.T, kind engine.PublisherKind) {
// Set env var via direct call to os instead of t.SetEnv, because CI runs tests on 1.16 and
// that function is only available after 1.17
key := pubKindEnvVarKey(t)
err := os.Setenv(key, string(kind))
require.NoError(t, err)
t.Cleanup(func() {
os.Unsetenv(key)
})
}
func TestRetrievalRoundTrip(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
testRetrievalRoundTripWithTestCase(t, tc)
})
}
}
func testRetrievalRoundTripWithTestCase(t *testing.T, tc testCase) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Initialize everything
server := newTestServer(t, ctx, tc.serverConfigOpts(t)...)
client := newTestClient(t)
disseminateNetworkState(server.h, client.h)
carBs := testutil.OpenSampleCar(t, "sample-v1-2.car")
roots, err := carBs.Roots()
require.NoError(t, err)
require.Len(t, roots, 1)
carBs.Close()
contextID := []byte("applesauce")
tp, err := cardatatransfer.TransportFromContextID(contextID)
require.NoError(t, err)
md := metadata.Default.New(tp)
advCid, err := server.cs.Put(ctx, contextID, filepath.Join(testutil.ThisDir(t), "./testdata/sample-v1-2.car"), md)
require.NoError(t, err)
subHost := newHost(t)
sub, err := dagsync.NewSubscriber(subHost, client.lsys)
require.NoError(t, err)
serverInfo := peer.AddrInfo{
ID: server.h.ID(),
Addrs: []multiaddr.Multiaddr{server.publisherAddr},
}
headCid, err := sub.SyncAdChain(ctx, serverInfo)
require.NoError(t, err)
require.Equal(t, advCid, headCid)
// Close the subscriber so it doesn't interfere with the next data transfer.
err = sub.Close()
require.NoError(t, err)
// Get first advertisement
advNode, err := client.lsys.Load(ipld.LinkContext{}, cidlink.Link{Cid: advCid}, schema.AdvertisementPrototype)
require.NoError(t, err)
adv, err := schema.UnwrapAdvertisement(advNode)
require.NoError(t, err)
dtm := &metadata.GraphsyncFilecoinV1{}
err = dtm.UnmarshalBinary(adv.Metadata)
require.NoError(t, err)
proposal := &retrievaltypes.DealProposal{
PayloadCID: roots[0],
ID: 1,
Params: retrievaltypes.Params{
PieceCID: &dtm.PieceCID,
},
}
done := make(chan bool, 1)
unsub := client.dt.SubscribeToEvents(func(event datatransfer.Event, channelState datatransfer.ChannelState) {
switch channelState.Status() {
case datatransfer.Failed, datatransfer.Cancelled:
done <- false
case datatransfer.Completed:
done <- true
}
})
defer unsub()
require.NoError(t, err)
_, err = client.dt.OpenPullDataChannel(ctx, server.h.ID(), proposal.AsVoucher(), roots[0], selectorparse.CommonSelector_ExploreAllRecursively)
require.NoError(t, err)
select {
case <-ctx.Done():
require.FailNow(t, "context closed")
case result := <-done:
require.True(t, result)
}
}
func TestReimportCar(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
testReimportCarWtihTestCase(t, tc)
})
}
}
func testReimportCarWtihTestCase(t *testing.T, tc testCase) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
server := newTestServer(t, ctx, tc.serverConfigOpts(t)...)
client := newTestClient(t)
disseminateNetworkState(server.h, client.h)
contextID := []byte("applesauce")
tp, err := cardatatransfer.TransportFromContextID(contextID)
require.NoError(t, err)
md := metadata.Default.New(tp)
advCid, err := server.cs.Put(ctx, contextID, filepath.Join(testutil.ThisDir(t), "./testdata/sample-v1-2.car"), md)
require.NoError(t, err)
subHost := newHost(t)
sub, err := dagsync.NewSubscriber(subHost, client.lsys)
require.NoError(t, err)
serverInfo := peer.AddrInfo{
ID: server.h.ID(),
Addrs: []multiaddr.Multiaddr{server.publisherAddr},
}
headCid, err := sub.SyncAdChain(ctx, serverInfo)
require.NoError(t, err)
require.Equal(t, advCid, headCid)
// Get first advertisement
advNode, err := client.lsys.Load(ipld.LinkContext{}, cidlink.Link{Cid: advCid}, schema.AdvertisementPrototype)
require.NoError(t, err)
adv, err := schema.UnwrapAdvertisement(advNode)
require.NoError(t, err)
receivedMd := metadata.Default.New()
err = receivedMd.UnmarshalBinary(adv.Metadata)
require.NoError(t, err)
// Check the reimporting CAR with same contextID and metadata does not
// result in advertisement.
_, err = server.cs.Put(ctx, contextID, filepath.Join(testutil.ThisDir(t), "./testdata/sample-v1-2.car"), md)
require.Equal(t, err, provider.ErrAlreadyAdvertised)
// Test that reimporting CAR with same contextID and different metadata generates new advertisement.
contextID2 := []byte("applesauce2")
tp2, err := cardatatransfer.TransportFromContextID(contextID2)
require.NoError(t, err)
md2 := metadata.Default.New(tp2)
advCid2, err := server.cs.Put(ctx, contextID, filepath.Join(testutil.ThisDir(t), "./testdata/sample-v1-2.car"), md2)
require.NoError(t, err)
// Sync the new advertisement
headCid, err = sub.SyncAdChain(ctx, serverInfo)
require.NoError(t, err)
require.Equal(t, advCid2, headCid)
// Close the subscriber so it doesn't interfere with the next data transfer.
err = sub.Close()
require.NoError(t, err)
// Get second advertisement
advNode2, err := client.lsys.Load(ipld.LinkContext{}, cidlink.Link{Cid: advCid2}, schema.AdvertisementPrototype)
require.NoError(t, err)
adv2, err := schema.UnwrapAdvertisement(advNode2)
require.NoError(t, err)
receivedMd2 := metadata.Default.New()
err = receivedMd2.UnmarshalBinary(adv2.Metadata)
require.NoError(t, err)
require.NotEqual(t, receivedMd2, receivedMd)
// Check that both advertisements have the same entries link.
linkCid := adv.Entries.(cidlink.Link).Cid
linkCid2 := adv2.Entries.(cidlink.Link).Cid
require.True(t, linkCid.Equals(linkCid2))
}
func disseminateNetworkState(hosts ...host.Host) {
for _, one := range hosts {
for _, other := range hosts {
if one.ID() != other.ID() {
one.Peerstore().AddAddrs(other.ID(), other.Addrs(), time.Hour)
}
}
}
}
type testServer struct {
h host.Host
cs *supplier.CarSupplier
e *engine.Engine
publisherAddr multiaddr.Multiaddr
}
func newTestServer(t *testing.T, ctx context.Context, o ...engine.Option) *testServer {
// Explicitly override host so that the host is known for testing purposes.
h := newHost(t)
store := dssync.MutexWrap(datastore.NewMapDatastore())
o = append(o, engine.WithHost(h), engine.WithDatastore(store))
var publisherAddr multiaddr.Multiaddr
pubKind := engine.PublisherKind(os.Getenv(pubKindEnvVarKey(t)))
if pubKind == engine.HttpPublisher {
var err error
port := findOpenPort(t)
publisherAddr, err = multiaddr.NewMultiaddr("/ip4/0.0.0.0/tcp/" + port + "/http")
require.NoError(t, err)
o = append(o, engine.WithHttpPublisherListenAddr("0.0.0.0:"+port))
} else {
publisherAddr = h.Addrs()[0]
}
e, err := engine.New(o...)
require.NoError(t, err)
require.NoError(t, e.Start(ctx))
dt := testutil.SetupDataTransferOnHost(t, h, store, cidlink.DefaultLinkSystem())
cs := supplier.NewCarSupplier(e, store, car.ZeroLengthSectionAsEOF(false))
require.NoError(t, cardatatransfer.StartCarDataTransfer(dt, cs))
return &testServer{
h: h,
cs: cs,
e: e,
publisherAddr: publisherAddr,
}
}
func pubKindEnvVarKey(t *testing.T) string {
return t.Name() + "_publisher_kind"
}
type testClient struct {
h host.Host
dt datatransfer.Manager
lsys ipld.LinkSystem
store datastore.Batching
}
func newTestClient(t *testing.T) *testClient {
store := dssync.MutexWrap(datastore.NewMapDatastore())
blockStore := blockstore.NewBlockstore(store)
lsys := storeutil.LinkSystemForBlockstore(blockStore)
h := newHost(t)
dt := testutil.SetupDataTransferOnHost(t, h, store, lsys)
return &testClient{
h: h,
dt: dt,
lsys: lsys,
store: store,
}
}
func newHost(t *testing.T) host.Host {
h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))
require.NoError(t, err)
t.Cleanup(func() {
h.Close()
})
return h
}
func findOpenPort(t *testing.T) string {
l, err := net.Listen("tcp", "0.0.0.0:0")
require.NoError(t, err)
defer l.Close()
parts := strings.Split(l.Addr().String(), ":")
return parts[len(parts)-1]
}