1
1
package blockservice
2
2
3
3
import (
4
+ "context"
4
5
"testing"
5
6
6
7
blocks "github.com/ipfs/go-block-format"
7
8
ds "github.com/ipfs/go-datastore"
8
9
dssync "github.com/ipfs/go-datastore/sync"
9
10
blockstore "github.com/ipfs/go-ipfs-blockstore"
10
11
butil "github.com/ipfs/go-ipfs-blocksutil"
12
+ exchange "github.com/ipfs/go-ipfs-exchange-interface"
11
13
offline "github.com/ipfs/go-ipfs-exchange-offline"
12
14
)
13
15
@@ -35,6 +37,52 @@ func TestWriteThroughWorks(t *testing.T) {
35
37
}
36
38
}
37
39
40
+ func TestLazySessionInitialization (t * testing.T ) {
41
+ ctx := context .Background ()
42
+ ctx , cancel := context .WithCancel (ctx )
43
+ defer cancel ()
44
+
45
+ bstore := blockstore .NewBlockstore (dssync .MutexWrap (ds .NewMapDatastore ()))
46
+ bstore2 := blockstore .NewBlockstore (dssync .MutexWrap (ds .NewMapDatastore ()))
47
+ bstore3 := blockstore .NewBlockstore (dssync .MutexWrap (ds .NewMapDatastore ()))
48
+ session := offline .Exchange (bstore2 )
49
+ exchange := offline .Exchange (bstore3 )
50
+ sessionExch := & fakeSessionExchange {Interface : exchange , session : session }
51
+ bservSessEx := NewWriteThrough (bstore , sessionExch )
52
+ bgen := butil .NewBlockGenerator ()
53
+
54
+ block := bgen .Next ()
55
+ bstore .Put (block )
56
+
57
+ block2 := bgen .Next ()
58
+ session .HasBlock (block2 )
59
+
60
+ bsession := NewSession (ctx , bservSessEx )
61
+ if bsession .ses != nil {
62
+ t .Fatal ("Session exchange should not instantiated session immediately" )
63
+ }
64
+ returnedBlock , err := bsession .GetBlock (ctx , block .Cid ())
65
+ if err != nil {
66
+ t .Fatal ("Should have fetched block locally" )
67
+ }
68
+ if returnedBlock .Cid () != block .Cid () {
69
+ t .Fatal ("Got incorrect block" )
70
+ }
71
+ if bsession .ses != nil {
72
+ t .Fatal ("Session exchange should not instantiated session if local store had block" )
73
+ }
74
+ returnedBlock , err = bsession .GetBlock (ctx , block2 .Cid ())
75
+ if err != nil {
76
+ t .Fatal ("Should have fetched block remotely" )
77
+ }
78
+ if returnedBlock .Cid () != block2 .Cid () {
79
+ t .Fatal ("Got incorrect block" )
80
+ }
81
+ if bsession .ses != session {
82
+ t .Fatal ("Should have initialized session to fetch block" )
83
+ }
84
+ }
85
+
38
86
var _ blockstore.Blockstore = (* PutCountingBlockstore )(nil )
39
87
40
88
type PutCountingBlockstore struct {
@@ -46,3 +94,14 @@ func (bs *PutCountingBlockstore) Put(block blocks.Block) error {
46
94
bs .PutCounter ++
47
95
return bs .Blockstore .Put (block )
48
96
}
97
+
98
+ var _ exchange.SessionExchange = (* fakeSessionExchange )(nil )
99
+
100
+ type fakeSessionExchange struct {
101
+ exchange.Interface
102
+ session exchange.Fetcher
103
+ }
104
+
105
+ func (fe * fakeSessionExchange ) NewSession (context.Context ) exchange.Fetcher {
106
+ return fe .session
107
+ }
0 commit comments