Skip to content

Commit

Permalink
Don't compress empty or small messages
Browse files Browse the repository at this point in the history
Fixes grpc#6831.

gzip compressing messages less than 21 bytes is always unfruitful, it always
results in "compressed" messages that are longer than the original message
length, since the minimum length of a gzipped message is 21 bytes, due to
headers and CRC trailer.
  • Loading branch information
jroper committed Dec 3, 2023
1 parent 1b05500 commit e11b125
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions rpc_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -640,14 +640,23 @@ func encode(c baseCodec, msg any) ([]byte, error) {
return b, nil
}

// compress returns the input bytes compressed by compressor or cp. If both
// compressors are nil, returns nil.
const (
// minCompressionLength is the number of bytes that the gzip algorithm "compresses" an empty message to
minCompressionLength = 21
)

// compress returns the input bytes compressed by compressor or cp. Only
// compresses the bytes if compression is likely to reduce the size of the
// message, otherwise returns nil. If both compressors are nil, returns nil.
//
// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor.
func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) {
if compressor == nil && cp == nil {
return nil, nil
}
if len(in) <= minCompressionLength {
return nil, nil
}
wrapErr := func(err error) error {
return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error())
}
Expand Down

0 comments on commit e11b125

Please sign in to comment.