routing.go 1.78 KB
Newer Older
Brian Tiger Chow's avatar
Brian Tiger Chow committed
1 2 3 4 5 6 7
package bitswap

import (
	"errors"
	"sync"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
8
	bsnet "github.com/jbenet/go-ipfs/exchange/bitswap/network"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
9 10 11 12 13 14 15 16 17 18 19 20 21
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

type RoutingServer interface {
	// TODO
	Announce(*peer.Peer, u.Key) error

	// TODO
	Providers(u.Key) []*peer.Peer

	// TODO
	// Returns a Routing instance configured to query this hash table
22
	Client(*peer.Peer) bsnet.Routing
Brian Tiger Chow's avatar
Brian Tiger Chow committed
23 24
}

25
func VirtualRoutingServer() RoutingServer {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
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
	return &hashTable{
		m: make(map[u.Key]map[*peer.Peer]bool),
	}
}

type hashTable struct {
	lock sync.RWMutex
	m    map[u.Key]map[*peer.Peer]bool
}

var TODO = errors.New("TODO")

func (rs *hashTable) Announce(p *peer.Peer, k u.Key) error {
	rs.lock.Lock()
	defer rs.lock.Unlock()

	_, ok := rs.m[k]
	if !ok {
		rs.m[k] = make(map[*peer.Peer]bool)
	}
	rs.m[k][p] = true
	return nil
}

func (rs *hashTable) Providers(k u.Key) []*peer.Peer {
	rs.lock.RLock()
	defer rs.lock.RUnlock()
	ret := make([]*peer.Peer, 0)
	peerset, ok := rs.m[k]
	if !ok {
		return ret
	}
	for peer, _ := range peerset {
		ret = append(ret, peer)
	}
	return ret
}

// TODO
65
func (rs *hashTable) Client(p *peer.Peer) bsnet.Routing {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
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
	return &routingClient{
		peer:      p,
		hashTable: rs,
	}
}

type routingClient struct {
	peer      *peer.Peer
	hashTable RoutingServer
}

func (a *routingClient) FindProvidersAsync(ctx context.Context, k u.Key, max int) <-chan *peer.Peer {
	out := make(chan *peer.Peer)
	go func() {
		defer close(out)
		for i, p := range a.hashTable.Providers(k) {
			if max <= i {
				return
			}
			select {
			case out <- p:
			case <-ctx.Done():
				return
			}
		}
	}()
	return out
}

func (a *routingClient) Provide(key u.Key) error {
	return a.hashTable.Announce(a.peer, key)
}