Skip to content

Commit

Permalink
fix(network): block routing connection until dht is ready
Browse files Browse the repository at this point in the history
Signed-off-by: Godefroy Ponsinet <godefroy.ponsinet@outlook.com>
  • Loading branch information
90dy committed Mar 8, 2019
1 parent f386503 commit 0c91499
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
55 changes: 52 additions & 3 deletions core/network/host/routing.go
Expand Up @@ -2,19 +2,24 @@ package host

import (
"context"
"sync"
"time"

"berty.tech/core/pkg/tracing"
datastore "github.com/ipfs/go-datastore"
syncdatastore "github.com/ipfs/go-datastore/sync"
host "github.com/libp2p/go-libp2p-host"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
inet "github.com/libp2p/go-libp2p-net"
routing "github.com/libp2p/go-libp2p-routing"
)

var _ routing.IpfsRouting = (*BertyRouting)(nil)

type BertyRouting struct {
routing.IpfsRouting
muReady *sync.Cond
ready bool
}

func NewBertyRouting(ctx context.Context, h host.Host, dhtSvc bool) (*BertyRouting, error) {
Expand All @@ -30,9 +35,53 @@ func NewBertyRouting(ctx context.Context, h host.Host, dhtSvc bool) (*BertyRouti
dht = kaddht.NewDHTClient(ctx, h, ds)
}

if err := dht.Bootstrap(ctx); err != nil {
return nil, err
return &BertyRouting{IpfsRouting: dht}, nil
}

func (br *BertyRouting) isReady(ctx context.Context) error {
cready := make(chan *struct{})
go func() {
br.muReady.L.Lock()
if !br.ready {
br.muReady.Wait()
}
cready <- nil
br.muReady.L.Unlock()
}()

select {
case <-ctx.Done():
return ctx.Err()
case <-cready:
return nil
}
}

// Connected block connection until dht is ready
func (br *BertyRouting) Connected(s inet.Network, c inet.Conn) {
go func() {
br.muReady.L.Lock()
if !br.ready {
// Wait for datastore to be ready
time.Sleep(2 * time.Second)
br.ready = true

logger().Debug("DHT is now ready")

// Advertise Provider/FindProviders that dht should be ready
br.muReady.Broadcast()
}
br.muReady.L.Unlock()
}()
}

return &BertyRouting{dht}, nil
// Disconnected wait connection to be ready before disconnect
func (br *BertyRouting) Disconnected(s inet.Network, c inet.Conn) {
go func() {
br.muReady.L.Lock()
if len(s.Conns()) == 0 {
br.ready = false
}
br.muReady.L.Unlock()
}()
}
1 change: 0 additions & 1 deletion core/node/network.go
Expand Up @@ -44,7 +44,6 @@ func (n *Node) UseNetworkDriver(ctx context.Context, driver network.Driver) erro
zap.String("id", n.UserID()),
zap.Error(err),
)
return err
}

// FIXME: subscribe to every owned device IDs
Expand Down

0 comments on commit 0c91499

Please sign in to comment.