Skip to content

Commit

Permalink
Merge pull request #63 from libp2p/feat/refactor
Browse files Browse the repository at this point in the history
refactor for new transports
  • Loading branch information
Stebalien authored Jun 6, 2018
2 parents 0f7ab34 + 4e39954 commit 1c4ee32
Show file tree
Hide file tree
Showing 20 changed files with 1,151 additions and 1,034 deletions.
23 changes: 19 additions & 4 deletions p2p/net/swarm/dial_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@ import (
peer "github.com/libp2p/go-libp2p-peer"
)

// DialFunc is the type of function expected by DialSync.
type DialFunc func(context.Context, peer.ID) (*Conn, error)

// NewDialSync constructs a new DialSync
func NewDialSync(dfn DialFunc) *DialSync {
return &DialSync{
dials: make(map[peer.ID]*activeDial),
dialFunc: dfn,
}
}

// DialSync is a dial synchronization helper that ensures that at most one dial
// to any given peer is active at any given time.
type DialSync struct {
dials map[peer.ID]*activeDial
dialsLk sync.Mutex
Expand All @@ -35,11 +39,11 @@ type activeDial struct {
ds *DialSync
}

func (dr *activeDial) wait(ctx context.Context) (*Conn, error) {
defer dr.decref()
func (ad *activeDial) wait(ctx context.Context) (*Conn, error) {
defer ad.decref()
select {
case <-dr.waitch:
return dr.conn, dr.err
case <-ad.waitch:
return ad.conn, ad.err
case <-ctx.Done():
return nil, ctx.Err()
}
Expand Down Expand Up @@ -102,6 +106,17 @@ func (ds *DialSync) getActiveDial(p peer.ID) *activeDial {
return actd
}

// DialLock initiates a dial to the given peer if there are none in progress
// then waits for the dial to that peer to complete.
func (ds *DialSync) DialLock(ctx context.Context, p peer.ID) (*Conn, error) {
return ds.getActiveDial(p).wait(ctx)
}

// CancelDial cancels all in-progress dials to the given peer.
func (ds *DialSync) CancelDial(p peer.ID) {
ds.dialsLk.Lock()
defer ds.dialsLk.Unlock()
if ad, ok := ds.dials[p]; ok {
ad.cancel()
}
}
4 changes: 3 additions & 1 deletion p2p/net/swarm/dial_sync_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package swarm
package swarm_test

import (
"context"
Expand All @@ -7,6 +7,8 @@ import (
"testing"
"time"

. "github.com/libp2p/go-libp2p-swarm"

peer "github.com/libp2p/go-libp2p-peer"
)

Expand Down
Loading

0 comments on commit 1c4ee32

Please sign in to comment.