godbus / dbus

Native Go bindings for D-Bus
BSD 2-Clause "Simplified" License
959 stars 222 forks source link

Propagate the connection context to exported methods. #374

Open miccoli opened 11 months ago

miccoli commented 11 months ago

If I got it right, each connection has an associated context, accessible as func (*Conn)Context, however this context is not available to exported methods.

It would be nice if the connection context could be propagate to the exported methods, something like this:

type service struct{}

func (s service) MethodWithContext(ctx context.Context) (err *dbus.Error) {
    // propagate DBus connection ctx
    // ...
    return
}

// ...

func main() {
    var s service

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    conn, err := dbus.ConnectSessionBus(dbus.WithContext(ctx))
    // ...        
    err = conn.Export(s, "/com/example/Object", "com.example.Interface")
    // ...        

}

The use case is clear: in the above MethodWithContext I have to call some long running routines that require a context argument. The context should be able to cross the API boundary so that cancellation/cleanup is possible when the connection is closed.

For now I'm forced to write

func (s service) MethodWithContext() (err *dbus.Error) {
    ctx := context.TODO()
    // ...
    return
}

which is suboptimal.