Skip to content

Commit ed4bdd4

Browse files
Ensure bufferWriter is always closed in Migration.Buffer and propagate close errors (#1308)
* Ensure bufferWriter is always closed and error is returned in Buffer() * Ensure bufferWriter is always closed and error is returned in Buffer() * addressed review comments. used named error and joined error to return final error * Fixed defer block --------- Co-authored-by: Chandra kant <chandra.kant@cohesity.com>
1 parent 8945e85 commit ed4bdd4

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

migration.go

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package migrate
22

33
import (
44
"bufio"
5+
"errors"
56
"fmt"
67
"io"
78
"time"
@@ -118,7 +119,7 @@ func (m *Migration) LogString() string {
118119

119120
// Buffer buffers Body up to BufferSize.
120121
// Calling this function blocks. Call with goroutine.
121-
func (m *Migration) Buffer() error {
122+
func (m *Migration) Buffer() (berr error) {
122123
if m.Body == nil {
123124
return nil
124125
}
@@ -127,6 +128,21 @@ func (m *Migration) Buffer() error {
127128

128129
b := bufio.NewReaderSize(m.Body, int(m.BufferSize))
129130

131+
// defer closing buffer writer and body.
132+
defer func() {
133+
// close bufferWriter so Buffer knows that there is no
134+
// more data coming.
135+
if err := m.bufferWriter.Close(); err != nil {
136+
berr = errors.Join(berr, err)
137+
}
138+
139+
// it's safe to close the Body too.
140+
if err := m.Body.Close(); err != nil {
141+
berr = errors.Join(berr, err)
142+
}
143+
144+
}()
145+
130146
// start reading from body, peek won't move the read pointer though
131147
// poor man's solution?
132148
if _, err := b.Peek(int(m.BufferSize)); err != nil && err != io.EOF {
@@ -145,16 +161,5 @@ func (m *Migration) Buffer() error {
145161
m.FinishedReading = time.Now()
146162
m.BytesRead = n
147163

148-
// close bufferWriter so Buffer knows that there is no
149-
// more data coming
150-
if err := m.bufferWriter.Close(); err != nil {
151-
return err
152-
}
153-
154-
// it's safe to close the Body too
155-
if err := m.Body.Close(); err != nil {
156-
return err
157-
}
158-
159164
return nil
160165
}

0 commit comments

Comments
 (0)