Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix write lock deadline handling #7

Merged
merged 4 commits into from
Nov 17, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ var ErrCloseSent = errors.New("websocket: close sent")
// read limit set for the connection.
var ErrReadLimit = errors.New("websocket: read limit exceeded")

// ErrWriteDeadlineExceeded is returned when a writing to a connection has exceeded
// the specified deadline
var ErrWriteDeadlineExceeded = errors.New("websocket: writing deadline exceeded")

// netError satisfies the net Error interface.
type netError struct {
msg string
Expand Down Expand Up @@ -428,7 +432,36 @@ func (c *Conn) read(n int) ([]byte, error) {
}

func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error {
<-c.mu
// if user has provided no deadline
if deadline.IsZero() {
// just wait for the mutex.
<-c.mu
} else {
// see how far the deadline is from now
sleepTime := deadline.Sub(time.Now())

// is the deadline pointing to the future, or the past ?
if sleepTime < 0 {
// operation timed out already.
return ErrWriteDeadlineExceeded
}

select {
case <-c.mu:
// good, we've got the writing lock.

// the default case would be taken if the above lock could not be aquired right away.
default:
// writing lock is currently taken.
select {
case <-c.mu:
// great ! we got the writing lock.
case <-time.After(sleepTime):
// we were not able to aquire the writing lock.
return ErrWriteDeadlineExceeded
}
}
}
defer func() { c.mu <- true }()

c.writeErrMu.Lock()
Expand Down