Server should accept a context
drewwells opened this issue · comments
Drew Wells commented
If I wanted to be notified via a channel that the server has shutdown, I can't currently doing this. Accepting a context and exposing a listening context would make this possible. This way I could write the following code
client code using smux
// Session will be closed by server after 10 seconds
ctx := context.WithTimeout(context.TODO(), 10 * time.Second)
session, err := smux.Server(conn, &smux.Config{Ctx: ctx})
go func() {
// Get a reference to the server's context, to be notified that the server is complete
<-session.Context().Done()
// server has shutdown
// The convention for returning errors is to expose .Err() method
err := session.Err()
if err != nil {
log.Error(session.Err())
}
}()
Inside server code, you would create a WithCancel context. Call this cancel when the server shuts down after updating Err()'s return.
smux/server
ctx, cancel := context.WithCancel(config.Ctx)
// cancel() when the server shuts down, notifying those listening to server context
session.ctx = ctx
session.cancel = cancel
func (*s session) Close() {
session.cancel()
}
xtaci commented
there are 2 ways to shutdown the server
- to Close() the session manually
- the underlying connection passively closed, then AcceptStream() will return error