11package sessioninterestmanager
22
33import (
4+ "sync"
5+
46 bsswl "github.com/ipfs/go-bitswap/internal/sessionwantlist"
57 blocks "github.com/ipfs/go-block-format"
68
79 cid "github.com/ipfs/go-cid"
810)
911
12+ // SessionInterestManager records the CIDs that each session is interested in.
1013type SessionInterestManager struct {
14+ lk sync.RWMutex
1115 interested * bsswl.SessionWantlist
1216 wanted * bsswl.SessionWantlist
1317}
@@ -20,29 +24,52 @@ func New() *SessionInterestManager {
2024 }
2125}
2226
27+ // When the client asks the session for blocks, the session calls
28+ // RecordSessionInterest() with those cids.
2329func (sim * SessionInterestManager ) RecordSessionInterest (ses uint64 , ks []cid.Cid ) {
30+ sim .lk .Lock ()
31+ defer sim .lk .Unlock ()
32+
2433 sim .interested .Add (ks , ses )
2534 sim .wanted .Add (ks , ses )
2635}
2736
37+ // When the session shuts down it calls RemoveSessionInterest().
2838func (sim * SessionInterestManager ) RemoveSessionInterest (ses uint64 ) []cid.Cid {
39+ sim .lk .Lock ()
40+ defer sim .lk .Unlock ()
41+
2942 sim .wanted .RemoveSession (ses )
3043 return sim .interested .RemoveSession (ses )
3144}
3245
46+ // When the session receives blocks, it calls RemoveSessionWants().
3347func (sim * SessionInterestManager ) RemoveSessionWants (ses uint64 , wants []cid.Cid ) {
48+ sim .lk .Lock ()
49+ defer sim .lk .Unlock ()
50+
3451 sim .wanted .RemoveSessionKeys (ses , wants )
3552}
3653
54+ // The session calls FilterSessionInterested() to filter the sets of keys for
55+ // those that the session is interested in
3756func (sim * SessionInterestManager ) FilterSessionInterested (ses uint64 , ksets ... []cid.Cid ) [][]cid.Cid {
57+ sim .lk .RLock ()
58+ defer sim .lk .RUnlock ()
59+
3860 kres := make ([][]cid.Cid , len (ksets ))
3961 for i , ks := range ksets {
4062 kres [i ] = sim .interested .SessionHas (ses , ks ).Keys ()
4163 }
4264 return kres
4365}
4466
67+ // When bitswap receives blocks it calls SplitWantedUnwanted() to discard
68+ // unwanted blocks
4569func (sim * SessionInterestManager ) SplitWantedUnwanted (blks []blocks.Block ) ([]blocks.Block , []blocks.Block ) {
70+ sim .lk .RLock ()
71+ defer sim .lk .RUnlock ()
72+
4673 // Get the wanted block keys
4774 ks := make ([]cid.Cid , len (blks ))
4875 for _ , b := range blks {
@@ -63,7 +90,12 @@ func (sim *SessionInterestManager) SplitWantedUnwanted(blks []blocks.Block) ([]b
6390 return wantedBlks , notWantedBlks
6491}
6592
93+ // When the WantManager receives a message is calls InterestedSessions() to
94+ // find out which sessions are interested in the message.
6695func (sim * SessionInterestManager ) InterestedSessions (blks []cid.Cid , haves []cid.Cid , dontHaves []cid.Cid ) []uint64 {
96+ sim .lk .RLock ()
97+ defer sim .lk .RUnlock ()
98+
6799 ks := make ([]cid.Cid , 0 , len (blks )+ len (haves )+ len (dontHaves ))
68100 ks = append (ks , blks ... )
69101 ks = append (ks , haves ... )
0 commit comments