diff --git a/weed/filer/filechunk_group.go b/weed/filer/filechunk_group.go index dac6e1eed3..ed46c52bad 100644 --- a/weed/filer/filechunk_group.go +++ b/weed/filer/filechunk_group.go @@ -101,7 +101,13 @@ func (group *ChunkGroup) ReadDataAt(ctx context.Context, fileSize int64, buff [] return 0, 0, group.resolveErr } - sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff)))/SectionSize) + if len(buff) == 0 { + return 0, 0, nil + } + if int64(len(buff)) > fileSize-offset { + buff = buff[:fileSize-offset] + } + sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff))-1)/SectionSize) numSections := int(sectionIndexStop - sectionIndexStart + 1) // For single section or when concurrency is disabled, use sequential reading diff --git a/weed/filer/filechunk_group_eof_test.go b/weed/filer/filechunk_group_eof_test.go new file mode 100644 index 0000000000..0367305cf4 --- /dev/null +++ b/weed/filer/filechunk_group_eof_test.go @@ -0,0 +1,54 @@ +package filer + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +func TestChunkGroupReadAcrossEOF(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1") + _, _ = w.Write([]byte{'A'}) + })) + defer server.Close() + lookup := func(ctx context.Context, id string) ([]string, error) { + return []string{server.URL + "/" + id}, ctx.Err() + } + const offset = SectionSize - 4 + const fileSize = SectionSize - 3 + for _, hasData := range []bool{false, true} { + for _, concurrent := range []int{1, 16} { + for _, length := range []int{1, 8} { + t.Run(fmt.Sprintf("data_%v/readers_%d/bytes_%d", hasData, concurrent, length), func(t *testing.T) { + var chunks []*filer_pb.FileChunk + expected := byte(0) + if hasData { + chunks = []*filer_pb.FileChunk{{FileId: "1,0100000001", Offset: offset, Size: 1, ModifiedTsNs: 1}} + expected = 'A' + } + group, err := NewChunkGroup(lookup, newMockChunkCacheForReaderCache(), chunks, concurrent, nil, nil) + if err != nil { + t.Fatal(err) + } + defer group.Close() + dst := bytes.Repeat([]byte{0xcd}, length) + n, _, err := group.ReadDataAt(context.Background(), fileSize, dst, offset) + t.Logf("offset=%d fileSize=%d requested=%d n=%d err=%v data=%x", offset, fileSize, length, n, err, dst) + if n != 1 || (err != nil && err != io.EOF) || dst[0] != expected { + t.Fatal("section aggregation returned an invalid count/content for a valid read crossing EOF") + } + if !bytes.Equal(dst[1:], bytes.Repeat([]byte{0xcd}, length-1)) { + t.Fatal("read modified the buffer beyond EOF") + } + }) + } + } + } +}