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

improve error handling in writePacket #1601

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 4 additions & 2 deletions connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ func TestPingMarkBadConnection(t *testing.T) {
netConn: nc,
buf: newBuffer(nc),
maxAllowedPacket: defaultMaxAllowedPacket,
closech: make(chan struct{}),
cfg: NewConfig(),
}

err := mc.Ping(context.Background())
Expand All @@ -184,8 +186,8 @@ func TestPingErrInvalidConn(t *testing.T) {

err := mc.Ping(context.Background())

if err != ErrInvalidConn {
t.Errorf("expected ErrInvalidConn, got %#v", err)
if err != nc.err {
t.Errorf("expected %#v, got %#v", nc.err, err)
}
}

Expand Down
34 changes: 17 additions & 17 deletions packets.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,32 +124,32 @@ func (mc *mysqlConn) writePacket(data []byte) error {
}

n, err := mc.netConn.Write(data[:4+size])
if err == nil && n == 4+size {
mc.sequence++
if size != maxPacketSize {
return nil
}
pktLen -= size
data = data[size:]
continue
}

// Handle error
if err == nil { // n != len(data)
mc.cleanup()
mc.log(ErrMalformPkt)
} else {
if err != nil {
if cerr := mc.canceled.Value(); cerr != nil {
return cerr
}
mc.cleanup()
if n == 0 && pktLen == len(data)-4 {
// only for the first loop iteration when nothing was written yet
mc.log(err)
return errBadConnNoWrite
} else {
return err
}
}
if n != 4+size {
// io.Writer(b) must return a non-nil error if it cannot write len(b) bytes.
// The io.ErrShortWrite error is used to indicate that this rule has not been followed.
mc.cleanup()
mc.log(err)
return io.ErrShortWrite
}

mc.sequence++
if size != maxPacketSize {
return nil
}
return ErrInvalidConn
pktLen -= size
data = data[size:]
}
}

Expand Down
Loading