Should reads from a net.Conn be made to respect a context deadline

153 views
Skip to first unread message

Sam Whited

unread,
Apr 4, 2021, 9:13:08 AM4/4/21
to golan...@googlegroups.com
In a library I have a `func(context.Context, net.Conn)' (more or less,
https://godoc.org/mellium.im/xmpp#NewSession). The context is used
throughout the function to eg. break out of loops, gets passed into
other functions, etc. and the conn is read from. If the user creates and
passes in a context with a deadline and also sets a deadline on the
conn, should I also cancel reads/writes from the conn when the context
is expired, or allow the user the maximum flexibility of setting their
own deadline on both?

I've asked this elsewhere (and am copying it here to reach a wider
audience) and the responses I've gotten seem to fall into:

- The user might have set a deadline on the conn already and overriding
it defies user expectations, and
- The user expects that when the context is canceled the function stops
blocking, so you have to cancel any reads/writes on the conn too
otherwise the function could keep blocking, defying user expectation

I've gone back and forth a couple of times on how I'd expect this to
behave and I couldn't find any obvious examples in the standard
library that would suggest there's a convention so I'd love to get
other opinions.

—Sam

--
Sam Whited

Ian Lance Taylor

unread,
Apr 4, 2021, 7:42:56 PM4/4/21
to Sam Whited, golang-nuts
My opinion is that when you are using a context, then when the context
is cancelled the operation should also be cancelled. This doesn't
change if the connection happens to have a separately specified
deadline. The point of a context is to cancel an operation, so if
there is a context, it should be honored.

Speaking more broadly, while a context is often a deadline, it can
also be cancelled for other reasons (via ctx.WithCancel). Those other
reasons can include things like "we no longer need this data." So
that is an argument for why the context should be honored even if
there is a deadline.

Ian

Sam Whited

unread,
Apr 6, 2021, 9:29:29 AM4/6/21
to golan...@googlegroups.com
Thanks Ian,

On Sun, Apr 4, 2021, at 19:42, Ian Lance Taylor wrote:
> Speaking more broadly, while a context is often a deadline, it can
> also be cancelled for other reasons (via ctx.WithCancel). Those other
> reasons can include things like "we no longer need this data." So
> that is an argument for why the context should be honored even if
> there is a deadline.

I don't know that the deadline is necessarily the important part (since
the same applies to the conn itself which can be canceled by the user
with conn.SetDeadline(time.Unix(1,0) or something along those line). But
I take your point about the semantics of the context meaning "cancel
this action".

—Sam
Reply all
Reply to author
Forward
0 new messages