Optimize for a fast flush

This commit is contained in:
9seconds
2021-12-01 10:51:13 +03:00
parent ffad717829
commit 33e0509c5a
2 changed files with 14 additions and 3 deletions
+2 -2
View File
@@ -3,8 +3,8 @@ package relay
import "time" import "time"
const ( const (
copyBufferSize = 32 * 1024 copyBufferSize = 64 * 1024
writerBufferSize = 2 * copyBufferSize writerBufferSize = 128 * 1024
readTimeout = 10 * time.Millisecond readTimeout = 10 * time.Millisecond
) )
+12 -1
View File
@@ -26,6 +26,7 @@ func (s *syncPair) Sync() (int64, error) {
func (s *syncPair) Read(p []byte) (int, error) { func (s *syncPair) Read(p []byte) (int, error) {
n, err := s.readBlocking(p, false) n, err := s.readBlocking(p, false)
// nothing has been delivered for readTimeout time. Let's flush.
if errors.Is(err, os.ErrDeadlineExceeded) { if errors.Is(err, os.ErrDeadlineExceeded) {
if err := s.Flush(); err != nil { if err := s.Flush(); err != nil {
return 0, fmt.Errorf("cannot flush writer hand-side: %w", err) return 0, fmt.Errorf("cannot flush writer hand-side: %w", err)
@@ -41,7 +42,17 @@ func (s *syncPair) Write(p []byte) (int, error) {
s.mutex.Lock() s.mutex.Lock()
defer s.mutex.Unlock() defer s.mutex.Unlock()
return s.writer.Write(p) // nolint: wrapcheck n, err := s.writer.Write(p) // nolint: wrapcheck
// optimization for a case when we have a small package and want to avoid a
// delay in readTimeout. In that case, we assume that peer has finished to
// sent a data it wants to send so we can flush without waiting for anything
// else.
if err == nil && n < copyBufferSize {
err = s.writer.Flush()
}
return n, err
} }
func (s *syncPair) Flush() error { func (s *syncPair) Flush() error {