Skip to content

Commit

Permalink
swarm: update record conn metrics only once
Browse files Browse the repository at this point in the history
This causes discrepancy when the connection is closed before being
added to the swarm. This happens only in dial_worker loop when adding
to the swarm fails. It's nicer to fix this with a once than to ensure
that Close is never called twice within the swarm.
  • Loading branch information
sukunrt committed Dec 7, 2024
1 parent 31b9d3a commit 5e679d4
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions p2p/net/swarm/swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -823,31 +823,36 @@ type connWithMetrics struct {
opened time.Time
dir network.Direction
metricsTracer MetricsTracer
once sync.Once
closeErr error
}

func wrapWithMetrics(capableConn transport.CapableConn, metricsTracer MetricsTracer, opened time.Time, dir network.Direction) connWithMetrics {
c := connWithMetrics{CapableConn: capableConn, opened: opened, dir: dir, metricsTracer: metricsTracer}
func wrapWithMetrics(capableConn transport.CapableConn, metricsTracer MetricsTracer, opened time.Time, dir network.Direction) *connWithMetrics {
c := &connWithMetrics{CapableConn: capableConn, opened: opened, dir: dir, metricsTracer: metricsTracer}
c.metricsTracer.OpenedConnection(c.dir, capableConn.RemotePublicKey(), capableConn.ConnState(), capableConn.LocalMultiaddr())
return c
}

func (c connWithMetrics) completedHandshake() {
func (c *connWithMetrics) completedHandshake() {
c.metricsTracer.CompletedHandshake(time.Since(c.opened), c.ConnState(), c.LocalMultiaddr())
}

func (c connWithMetrics) Close() error {
c.metricsTracer.ClosedConnection(c.dir, time.Since(c.opened), c.ConnState(), c.LocalMultiaddr())
return c.CapableConn.Close()
func (c *connWithMetrics) Close() error {
c.once.Do(func() {
c.metricsTracer.ClosedConnection(c.dir, time.Since(c.opened), c.ConnState(), c.LocalMultiaddr())
c.closeErr = c.CapableConn.Close()
})
return c.closeErr
}

func (c connWithMetrics) Stat() network.ConnStats {
func (c *connWithMetrics) Stat() network.ConnStats {
if cs, ok := c.CapableConn.(network.ConnStat); ok {
return cs.Stat()
}
return network.ConnStats{}
}

var _ network.ConnStat = connWithMetrics{}
var _ network.ConnStat = &connWithMetrics{}

type ResolverFromMaDNS struct {
*madns.Resolver
Expand Down

0 comments on commit 5e679d4

Please sign in to comment.