Skip to content

Commit da16cab

Browse files
committed
Set self-adjusting deadline for connection writing
In #16055 it appears that the simple 5s deadline doesn't work for large file writes. Now we can't - or at least shouldn't just set no deadline as go will happily let these connections block indefinitely. However, what seems reasonable is to set some minimum rate we expect for writing. This PR suggests the following algorithm: * Every write has a minimum timeout of 5s (adjustable at compile time.) * If there has been a previous write - then consider its previous deadline, add half of the minimum timeout + 2s per kb about to written. * If that new deadline is after the minimum timeout use that. Fix #16055 Signed-off-by: Andrew Thornton <[email protected]>
1 parent 7979c36 commit da16cab

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

modules/graceful/server.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ var (
3131
// PerWriteWriteTimeout timeout for writes
3232
const PerWriteWriteTimeout = 5 * time.Second
3333

34+
// PerWriteWriteTimeoutKbRate is a timeout taking account of how much there is to be written
35+
const PerWriteWriteTimeoutKbRate = 2 * time.Second
36+
3437
func init() {
3538
DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)
3639
}
@@ -249,13 +252,19 @@ func (wl *wrappedListener) File() (*os.File, error) {
249252

250253
type wrappedConn struct {
251254
net.Conn
252-
server *Server
253-
closed *int32
255+
server *Server
256+
closed *int32
257+
deadline time.Time
254258
}
255259

256260
func (w wrappedConn) Write(p []byte) (n int, err error) {
257261
if PerWriteWriteTimeout > 0 {
258-
_ = w.Conn.SetWriteDeadline(time.Now().Add(PerWriteWriteTimeout))
262+
minDeadline := time.Now().Add(PerWriteWriteTimeout)
263+
w.deadline = w.deadline.Add(PerWriteWriteTimeout/2 + time.Duration(len(p)/1024)*PerWriteWriteTimeoutKbRate)
264+
if minDeadline.After(w.deadline) {
265+
w.deadline = minDeadline
266+
}
267+
_ = w.Conn.SetWriteDeadline(w.deadline)
259268
}
260269
return w.Conn.Write(p)
261270
}

0 commit comments

Comments
 (0)