Skip to content

Commit

Permalink
conn: add a context to the connection
Browse files Browse the repository at this point in the history
  • Loading branch information
jhenstridge authored and jsouthworth committed Sep 25, 2019
1 parent 6eb4cf1 commit 0953362
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ var ErrClosed = errors.New("dbus: connection closed by user")
type Conn struct {
transport

ctx context.Context
cancelCtx context.CancelFunc

busObj BusObject
unixFD bool
uuid string
Expand Down Expand Up @@ -210,6 +213,14 @@ func WithOutgoingInterceptor(interceptor Interceptor) ConnOption {
}
}

// WithContext overrides the default context for the connection.
func WithContext(ctx context.Context) ConnOption {
return func(conn *Conn) error {
conn.ctx = ctx
return nil
}
}

// NewConn creates a new private *Conn from an already established connection.
func NewConn(conn io.ReadWriteCloser, opts ...ConnOption) (*Conn, error) {
return newConn(genericTransport{conn}, opts...)
Expand All @@ -231,6 +242,10 @@ func newConn(tr transport, opts ...ConnOption) (*Conn, error) {
return nil, err
}
}
if conn.ctx == nil {
conn.ctx = context.Background()
}
conn.ctx, conn.cancelCtx = context.WithCancel(conn.ctx)
conn.calls = newCallTracker()
if conn.handler == nil {
conn.handler = NewDefaultHandler()
Expand Down Expand Up @@ -272,9 +287,17 @@ func (conn *Conn) Close() error {
}
conn.eavesdroppedLck.Unlock()

conn.cancelCtx()

return conn.transport.Close()
}

// Context returns the context associated with the connection. The
// context will be cancelled when the connection is closed.
func (conn *Conn) Context() context.Context {
return conn.ctx
}

// Eavesdrop causes conn to send all incoming messages to the given channel
// without further processing. Method replies, errors and signals will not be
// sent to the appropriate channels and method calls will not be handled. If nil
Expand Down

0 comments on commit 0953362

Please sign in to comment.