mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
A read across a chunk boundary started a goroutine for each view of the chunk the stream leaves, outside the limit on chunks read at once, so a compressed chunk written over in many places could start any number of them. One goroutine started before the others now reads those views one after another, and the other views are back under the errgroup limit. It reads every view from the held download before a view the download can't serve falls back to a read of its own, as that read can make room and evicting the chunk waits for the holds. The test of a boundary read that doesn't wait for the chunk it leaves now has four times as many views of that chunk as chunks run at once, and checks that the read starts fewer goroutines than that. The waits for a prefetch to reserve and for a boundary read to fetch its last chunk are bounded, so a failing test reports instead of hanging. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1179 lines
43 KiB
Go
1179 lines
43 KiB
Go
package filer
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"runtime"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
|
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
|
)
|
|
|
|
// Two streams (e.g. two S3 GETs) reading the same object through one shared
|
|
// ReaderCache, interleaved in small slices, must share each chunk download:
|
|
// one stream finishing a chunk, or moving on to the next one, must not drop a
|
|
// buffer the other stream is still reading.
|
|
func TestChunkReadAtConcurrentStreamsShareChunks(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const chunkCount = 3
|
|
const sliceSize = 16 << 10
|
|
|
|
var mu sync.Mutex
|
|
fetches := map[string]int{}
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
mu.Lock()
|
|
fetches[fileId]++
|
|
mu.Unlock()
|
|
for i := range buffer {
|
|
buffer[i] = fileId[len(fileId)-1]
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
|
|
newStream := func() *ChunkReadAt {
|
|
views := NewIntervalList[*ChunkView]()
|
|
for i := 0; i < chunkCount; i++ {
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: int64(i * chunkSize),
|
|
StopOffset: int64((i + 1) * chunkSize),
|
|
Value: &ChunkView{
|
|
FileId: fmt.Sprintf("chunk%d", i),
|
|
ViewSize: chunkSize,
|
|
ViewOffset: int64(i * chunkSize),
|
|
ChunkSize: chunkSize,
|
|
},
|
|
})
|
|
}
|
|
return NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
|
}
|
|
streams := []*ChunkReadAt{newStream(), newStream()}
|
|
|
|
// The streams alternate slice by slice, the second one lagging one slice
|
|
// behind, so the leader always finishes a chunk while the follower is
|
|
// still inside it.
|
|
offsets := make([]int64, len(streams))
|
|
offsets[1] = -sliceSize
|
|
for offsets[1] < chunkSize*chunkCount {
|
|
for i, stream := range streams {
|
|
if offsets[i] < 0 || offsets[i] >= chunkSize*chunkCount {
|
|
offsets[i] += sliceSize
|
|
continue
|
|
}
|
|
buf := make([]byte, sliceSize)
|
|
n, err := stream.ReadAt(buf, offsets[i])
|
|
if (err != nil && err != io.EOF) || n != sliceSize {
|
|
t.Fatalf("stream %d at %d: n=%d err=%v", i, offsets[i], n, err)
|
|
}
|
|
if want := byte('0' + offsets[i]/chunkSize); buf[0] != want || buf[n-1] != want {
|
|
t.Fatalf("stream %d at %d: got %q, want %q", i, offsets[i], buf[0], want)
|
|
}
|
|
offsets[i] += sliceSize
|
|
}
|
|
}
|
|
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
for i := 0; i < chunkCount; i++ {
|
|
fileId := fmt.Sprintf("chunk%d", i)
|
|
if fetches[fileId] != 1 {
|
|
t.Errorf("%s fetched %d times for two concurrent streams, want 1", fileId, fetches[fileId])
|
|
}
|
|
}
|
|
}
|
|
|
|
func newStreamTestReaderCache(chunkCache chunk_cache.ChunkCache) *ReaderCache {
|
|
rc := NewReaderCache(64, chunkCache, func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
return len(buffer), nil
|
|
}
|
|
return rc
|
|
}
|
|
|
|
// in reports whether the stream is positioned in fileId's chunk.
|
|
func (stream *chunkStream) in(fileId string) bool {
|
|
stream.mu.Lock()
|
|
defer stream.mu.Unlock()
|
|
return stream.cacher != nil && stream.cacher.chunkFileId == fileId
|
|
}
|
|
|
|
func isRetained(rc *ReaderCache, fileId string) bool {
|
|
rc.Lock()
|
|
defer rc.Unlock()
|
|
_, found := rc.downloaders[fileId]
|
|
return found
|
|
}
|
|
|
|
// A stream moving on to a chunk served from the chunk cache must still
|
|
// release the chunk it was positioned in before.
|
|
func TestChunkStreamReleasesPreviousChunkOnCacheHit(t *testing.T) {
|
|
cache := newMockChunkCacheForReaderCache()
|
|
cache.SetChunk("chunk1", make([]byte, 4<<10))
|
|
rc := newStreamTestReaderCache(cache)
|
|
defer rc.destroy()
|
|
|
|
stream := &chunkStream{}
|
|
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, true); err != nil || n == 0 {
|
|
t.Fatalf("cache hit read: n=%d err=%v", n, err)
|
|
}
|
|
if isRetained(rc, "chunk0") {
|
|
t.Fatal("chunk0 still retained after the stream moved on to a cached chunk")
|
|
}
|
|
}
|
|
|
|
// A chunk the stream leaves while another read is in flight must be dropped
|
|
// once that read ends, even if it did not read the chunk to the end.
|
|
func TestChunkStreamDropsLeftChunkAfterInFlightRead(t *testing.T) {
|
|
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
|
defer rc.destroy()
|
|
|
|
stream := &chunkStream{}
|
|
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Another reader is in the middle of a partial read of chunk0.
|
|
rc.Lock()
|
|
other := rc.downloaders["chunk0"]
|
|
other.wg.Add(1)
|
|
atomic.AddInt32(&other.readers, 1)
|
|
rc.Unlock()
|
|
|
|
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !isRetained(rc, "chunk0") {
|
|
t.Fatal("chunk0 dropped while a read was still in flight")
|
|
}
|
|
|
|
// The in-flight read ends without reaching the end of the chunk.
|
|
other.wg.Done()
|
|
atomic.AddInt32(&other.readers, -1)
|
|
rc.removeConsumed(other)
|
|
if isRetained(rc, "chunk0") {
|
|
t.Fatal("chunk0 retained after the stream left it and the last read ended")
|
|
}
|
|
}
|
|
|
|
// Concurrent ReadAt calls on one ChunkReadAt (as mount does) share its stream
|
|
// pin; they must neither race on it nor leak or double-release pins.
|
|
func TestChunkStreamConcurrentReadsOnOneReader(t *testing.T) {
|
|
const chunkSize = 16 << 10
|
|
const chunkCount = 4
|
|
const sliceSize = 4 << 10
|
|
rc := newStreamTestReaderCache((*chunk_cache.TieredChunkCache)(nil))
|
|
defer rc.destroy()
|
|
|
|
views := NewIntervalList[*ChunkView]()
|
|
for i := 0; i < chunkCount; i++ {
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: int64(i * chunkSize),
|
|
StopOffset: int64((i + 1) * chunkSize),
|
|
Value: &ChunkView{
|
|
FileId: fmt.Sprintf("chunk%d", i),
|
|
ViewSize: chunkSize,
|
|
ViewOffset: int64(i * chunkSize),
|
|
ChunkSize: chunkSize,
|
|
},
|
|
})
|
|
}
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
|
|
|
var wg sync.WaitGroup
|
|
for g := 0; g < 8; g++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
for offset := int64(0); offset < chunkSize*chunkCount; offset += sliceSize {
|
|
if _, err := reader.ReadAt(make([]byte, sliceSize), offset); err != nil && err != io.EOF {
|
|
t.Error(err)
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
|
|
// Finishing the last chunk releases the stream's final pin.
|
|
if _, err := reader.ReadAt(make([]byte, sliceSize), chunkSize*chunkCount-sliceSize); err != nil && err != io.EOF {
|
|
t.Fatal(err)
|
|
}
|
|
rc.Lock()
|
|
defer rc.Unlock()
|
|
for fileId, cacher := range rc.downloaders {
|
|
t.Errorf("%s retained after all reads finished: pins=%d readers=%d", fileId, atomic.LoadInt32(&cacher.pins), atomic.LoadInt32(&cacher.readers))
|
|
}
|
|
}
|
|
|
|
type recordedFetch struct {
|
|
fileId string
|
|
isFullChunk bool
|
|
offset int64
|
|
size int
|
|
}
|
|
|
|
// fetchRecorder stubs the volume fetch and records how each chunk was
|
|
// requested: isFullChunk=false is a range fetch of just the view's slice,
|
|
// isFullChunk=true is a whole-chunk download into the shared cache.
|
|
func fetchRecorder(rc *ReaderCache) (fetches *[]recordedFetch) {
|
|
var mu sync.Mutex
|
|
recorded := &[]recordedFetch{}
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, isFullChunk bool, offset int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
mu.Lock()
|
|
*recorded = append(*recorded, recordedFetch{fileId, isFullChunk, offset, len(buffer)})
|
|
mu.Unlock()
|
|
for i := range buffer {
|
|
buffer[i] = fileId[len(fileId)-1]
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
return recorded
|
|
}
|
|
|
|
// A reader whose views are clipped to a request window — how the S3 gateway
|
|
// builds a ranged GET — must fetch only the covered part of each chunk:
|
|
// clipped edge views take range fetches, a fully covered chunk keeps the
|
|
// shared whole-chunk path. This is what keeps a ranged GET larger than a
|
|
// buffer from multiplying volume-server reads (issue #11564), without giving
|
|
// up whole-chunk caching where the whole chunk is actually wanted.
|
|
func TestChunkReadAtClippedViewsFetchOnlyCoveredParts(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
|
|
// Window [56KiB, 152KiB): tail of chunk0, all of chunk1, head of
|
|
// chunk2, head of ciphered chunk3, head of compressed chunk4 (file
|
|
// chunks need not be aligned).
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: chunkSize - 8<<10,
|
|
StopOffset: chunkSize,
|
|
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: chunkSize - 8<<10, ViewSize: 8 << 10, ViewOffset: chunkSize - 8<<10, ChunkSize: chunkSize},
|
|
})
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: chunkSize,
|
|
StopOffset: 2 * chunkSize,
|
|
Value: &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 2 * chunkSize,
|
|
StopOffset: 2*chunkSize + 8<<10,
|
|
Value: &ChunkView{FileId: "chunk2", ViewSize: 8 << 10, ViewOffset: 2 * chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 2*chunkSize + 8<<10,
|
|
StopOffset: 2*chunkSize + 16<<10,
|
|
Value: &ChunkView{FileId: "chunk3", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 8<<10, ChunkSize: chunkSize, CipherKey: []byte("key")},
|
|
})
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 2*chunkSize + 16<<10,
|
|
StopOffset: 2*chunkSize + 24<<10,
|
|
Value: &ChunkView{FileId: "chunk4", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 16<<10, ChunkSize: chunkSize, IsGzipped: true},
|
|
})
|
|
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 4*chunkSize, 0)
|
|
buf := make([]byte, chunkSize+32<<10)
|
|
if n, err := reader.ReadAt(buf, chunkSize-8<<10); err != nil || n != len(buf) {
|
|
t.Fatalf("window read: n=%d err=%v", n, err)
|
|
}
|
|
// buf holds [56KiB, 152KiB): chunk0's tail, chunk1, and the heads of
|
|
// chunk2, chunk3 and chunk4.
|
|
for i, b := range buf {
|
|
want := byte('1')
|
|
if i < 8<<10 {
|
|
want = '0'
|
|
} else if i >= 24<<10+chunkSize {
|
|
want = '4'
|
|
} else if i >= 16<<10+chunkSize {
|
|
want = '3'
|
|
} else if i >= 8<<10+chunkSize {
|
|
want = '2'
|
|
}
|
|
if b != want {
|
|
t.Fatalf("buf[%d]=%q, want %q", i, b, want)
|
|
}
|
|
}
|
|
|
|
want := []recordedFetch{
|
|
{fileId: "chunk0", isFullChunk: false, offset: chunkSize - 8<<10, size: 8 << 10},
|
|
{fileId: "chunk1", isFullChunk: true, offset: 0, size: chunkSize},
|
|
{fileId: "chunk2", isFullChunk: false, offset: 0, size: 8 << 10},
|
|
// partial views, but ciphered and compressed chunks download whole
|
|
// either way and the shared path decrypts/decompresses once for
|
|
// every buffer
|
|
{fileId: "chunk3", isFullChunk: true, offset: 0, size: chunkSize},
|
|
{fileId: "chunk4", isFullChunk: true, offset: 0, size: chunkSize},
|
|
}
|
|
got := map[string]recordedFetch{}
|
|
for _, f := range *fetches {
|
|
if _, dup := got[f.fileId]; dup {
|
|
t.Fatalf("chunk %s fetched more than once: %+v", f.fileId, *fetches)
|
|
}
|
|
got[f.fileId] = f
|
|
}
|
|
for _, w := range want {
|
|
if g, ok := got[w.fileId]; !ok {
|
|
t.Fatalf("chunk %s never fetched: %+v", w.fileId, *fetches)
|
|
} else if g != w {
|
|
t.Fatalf("chunk %s fetched as %+v, want %+v", w.fileId, g, w)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The regression from issue #11564: a ranged GET sitting inside one big
|
|
// chunk. Every buffer of the request must stay a range fetch — none may
|
|
// escalate into a whole-chunk download once the reads look sequential.
|
|
func TestChunkReadAtRangeInsideOneChunkStaysRangeFetch(t *testing.T) {
|
|
const chunkSize = 1 << 20
|
|
const sliceSize = 16 << 10
|
|
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
|
|
// Range [32KiB, 96KiB) inside one 1MiB chunk: a single clipped view.
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 32 << 10,
|
|
StopOffset: 96 << 10,
|
|
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 64 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize},
|
|
})
|
|
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
|
for offset := int64(32 << 10); offset < 96<<10; offset += sliceSize {
|
|
buf := make([]byte, sliceSize)
|
|
if n, err := reader.ReadAt(buf, offset); err != nil || n != sliceSize {
|
|
t.Fatalf("read at %d: n=%d err=%v", offset, n, err)
|
|
}
|
|
}
|
|
|
|
if len(*fetches) != 4 {
|
|
t.Fatalf("got %d fetches, want 4 range fetches: %+v", len(*fetches), *fetches)
|
|
}
|
|
for i, f := range *fetches {
|
|
wantOffset := int64(32<<10) + int64(i)*sliceSize
|
|
if f.isFullChunk || f.offset != wantOffset || f.size != sliceSize {
|
|
t.Fatalf("fetch %d = %+v, want range fetch offset=%d size=%d", i, f, wantOffset, sliceSize)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A compressed chunk larger than the reader cache budget can never be
|
|
// downloaded whole — the budget rejects the buffer — so its partial view
|
|
// must fall back to a range fetch even though each range costs a full
|
|
// decompress server-side. The alternative is a failed GET.
|
|
func TestChunkReadAtOversizedCompressedChunkFallsBackToRange(t *testing.T) {
|
|
const chunkSize = 1 << 20
|
|
const sliceSize = 16 << 10
|
|
|
|
budget := NewReaderCacheBudget(64 << 10) // smaller than the chunk
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, budget)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 32 << 10,
|
|
StopOffset: 64 << 10,
|
|
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 32 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize, IsGzipped: true},
|
|
})
|
|
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
|
buf := make([]byte, 32<<10)
|
|
if n, err := reader.ReadAt(buf, 32<<10); err != nil || n != len(buf) {
|
|
t.Fatalf("read: n=%d err=%v", n, err)
|
|
}
|
|
|
|
if len(*fetches) != 1 {
|
|
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
|
|
}
|
|
if f := (*fetches)[0]; f.isFullChunk || f.offset != 32<<10 || f.size != 32<<10 {
|
|
t.Fatalf("fetch = %+v, want range fetch offset=%d size=%d", f, 32<<10, 32<<10)
|
|
}
|
|
}
|
|
|
|
// A whole chunk larger than the reader cache budget is range-fetched in a
|
|
// sequential read too, as the budget can't hold it whole.
|
|
func TestChunkReadAtOversizedFullChunkFallsBackToRange(t *testing.T) {
|
|
const chunkSize = 1 << 20
|
|
const sliceSize = 16 << 10
|
|
|
|
budget := NewReaderCacheBudget(64 << 10)
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, budget)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: 0,
|
|
StopOffset: chunkSize,
|
|
Value: &ChunkView{FileId: "chunk0", ViewSize: chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
if n, err := reader.ReadAt(make([]byte, sliceSize), 0); err != nil || n != sliceSize {
|
|
t.Fatalf("read: n=%d err=%v", n, err)
|
|
}
|
|
|
|
if len(*fetches) != 1 {
|
|
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
|
|
}
|
|
if f := (*fetches)[0]; f.isFullChunk || f.offset != 0 || f.size != sliceSize {
|
|
t.Fatalf("fetch = %+v, want range fetch offset=0 size=%d", f, sliceSize)
|
|
}
|
|
}
|
|
|
|
// A read across chunks bigger than the budget range-fetches each of them, as
|
|
// the parallel path can't download them whole either.
|
|
func TestChunkReadAtOversizedFullChunksAcrossABoundaryFallBackToRange(t *testing.T) {
|
|
const chunkSize = 1 << 20
|
|
const sliceSize = 16 << 10
|
|
|
|
budget := NewReaderCacheBudget(64 << 10)
|
|
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, budget)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
|
|
views := NewIntervalList[*ChunkView]()
|
|
for i := int64(0); i < 2; i++ {
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: i * chunkSize,
|
|
StopOffset: (i + 1) * chunkSize,
|
|
Value: &ChunkView{FileId: fmt.Sprintf("chunk%d", i), ViewOffset: i * chunkSize, ViewSize: chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
}
|
|
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 2*chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
if n, err := reader.ReadAt(make([]byte, sliceSize), chunkSize-sliceSize/2); err != nil || n != sliceSize {
|
|
t.Fatalf("read: n=%d err=%v", n, err)
|
|
}
|
|
|
|
if len(*fetches) != 2 {
|
|
t.Fatalf("got %d fetches, want 2 range fetches: %+v", len(*fetches), *fetches)
|
|
}
|
|
for _, f := range *fetches {
|
|
if f.isFullChunk || f.size != sliceSize/2 {
|
|
t.Fatalf("fetch = %+v, want a range fetch of size %d", f, sliceSize/2)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Prefetch skips a chunk that cannot fit the reader budget: only a range
|
|
// fetch can serve it, so a whole-chunk prefetch would take a download slot
|
|
// the chunks after it could use, and then fail.
|
|
func TestReaderCacheMaybeCacheSkipsOversizedChunk(t *testing.T) {
|
|
const oversized = 1 << 20
|
|
const small = 4 << 10
|
|
|
|
rc := NewReaderCache(1, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, NewReaderCacheBudget(64<<10))
|
|
defer rc.destroy()
|
|
fetchRecorder(rc)
|
|
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{StartOffset: 0, StopOffset: oversized,
|
|
Value: &ChunkView{FileId: "chunk0", ViewSize: oversized, ChunkSize: oversized}})
|
|
views.AppendInterval(&Interval[*ChunkView]{StartOffset: oversized, StopOffset: oversized + small,
|
|
Value: &ChunkView{FileId: "chunk1", ViewOffset: oversized, ViewSize: small, ChunkSize: small}})
|
|
|
|
rc.MaybeCache(views.Front(), 2)
|
|
|
|
rc.Lock()
|
|
_, prefetched := rc.downloaders["chunk1"]
|
|
rc.Unlock()
|
|
if !prefetched {
|
|
t.Fatal("the chunk after one over the budget was not prefetched")
|
|
}
|
|
}
|
|
|
|
// A chunk a stream is positioned in must outlast downloader-limit eviction:
|
|
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
|
|
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
|
|
var fetches int32
|
|
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
if fileId == "chunk0" {
|
|
atomic.AddInt32(&fetches, 1)
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
|
|
stream := &chunkStream{}
|
|
buf := make([]byte, 16<<10)
|
|
// One slice in: the stream is positioned in chunk0 but has not left it.
|
|
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Fill the downloader map past its limit with unpinned chunks.
|
|
for _, fileId := range []string{"chunk1", "chunk2", "chunk3"} {
|
|
if _, err := rc.ReadChunkAt(context.Background(), buf, fileId, nil, false, 0, chunkSize, true); err != nil {
|
|
t.Fatalf("read %s: %v", fileId, err)
|
|
}
|
|
}
|
|
|
|
// The stream's next slice must come from the still-pinned buffer.
|
|
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := atomic.LoadInt32(&fetches); got != 1 {
|
|
t.Errorf("chunk0 fetched %d times, want 1", got)
|
|
}
|
|
}
|
|
|
|
// When every downloader is pinned the limit still applies: the oldest pinned
|
|
// buffer is evicted so abandoned streams cannot grow memory past the limit.
|
|
func TestChunkReadAtPinnedEvictionFallsBackWhenAllPinned(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
return len(buffer), nil
|
|
}
|
|
|
|
buf := make([]byte, 16<<10)
|
|
streamA := &chunkStream{}
|
|
streamB := &chunkStream{}
|
|
if _, err := rc.readChunkAt(context.Background(), streamA, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), streamB, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Every downloader is now pinned; the next chunk must still get in.
|
|
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if isRetained(rc, "chunk0") {
|
|
t.Fatal("oldest pinned downloader was not evicted past the limit")
|
|
}
|
|
if !isRetained(rc, "chunk2") {
|
|
t.Fatal("new downloader missing after pinned fallback eviction")
|
|
}
|
|
}
|
|
|
|
// newReaderCacheWithPrefetch returns a cache whose download of "prefetched"
|
|
// runs until release is closed, and counts fetches of chunk0.
|
|
func newReaderCacheWithPrefetch(limit int, release chan struct{}, chunk0Fetches *int32, budgets ...*ReaderCacheBudget) *ReaderCache {
|
|
rc := NewReaderCache(limit, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, budgets...)
|
|
rc.fetchChunkDataFn = func(ctx context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
switch fileId {
|
|
case "chunk0":
|
|
atomic.AddInt32(chunk0Fetches, 1)
|
|
case "prefetched":
|
|
select {
|
|
case <-release:
|
|
case <-ctx.Done():
|
|
}
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
return rc
|
|
}
|
|
|
|
// startPrefetch registers "prefetched" the way MaybeCache does: running and
|
|
// pinned by no stream. It returns once the download holds its reservation,
|
|
// which it takes after it signals that it started.
|
|
func startPrefetch(t *testing.T, rc *ReaderCache, chunkSize int) {
|
|
t.Helper()
|
|
rc.Lock()
|
|
cacher := newSingleChunkCacher(rc, "prefetched", nil, false, chunkSize, false)
|
|
cacher.wg.Add(1)
|
|
rc.downloaders["prefetched"] = cacher
|
|
rc.Unlock()
|
|
go cacher.startCaching()
|
|
<-cacher.cacheStartedCh
|
|
for deadline := time.Now().Add(5 * time.Second); rc.budget != nil; time.Sleep(time.Millisecond) {
|
|
rc.budget.Lock()
|
|
_, reserved := rc.budget.reservations[cacher]
|
|
rc.budget.Unlock()
|
|
if reserved {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the prefetch didn't reserve its buffer")
|
|
}
|
|
}
|
|
}
|
|
|
|
// A running download takes a slot it gives up once it finishes, so a stream's
|
|
// chunk is not evicted to make room next to it.
|
|
func TestChunkReadAtPinnedChunkSurvivesARunningPrefetch(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
var fetches int32
|
|
release := make(chan struct{})
|
|
rc := newReaderCacheWithPrefetch(2, release, &fetches)
|
|
defer rc.destroy()
|
|
defer close(release)
|
|
|
|
stream := &chunkStream{}
|
|
buf := make([]byte, 16<<10)
|
|
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
startPrefetch(t, rc, chunkSize)
|
|
|
|
if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := atomic.LoadInt32(&fetches); got != 1 {
|
|
t.Errorf("chunk0 fetched %d times, want 1", got)
|
|
}
|
|
}
|
|
|
|
// Once pinned chunks fill the limit on their own, the oldest is evicted even
|
|
// while a download runs, so abandoned pins cannot grow the cache past it.
|
|
func TestChunkReadAtPinnedEvictionFallsBackWhilePrefetchRuns(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
var fetches int32
|
|
release := make(chan struct{})
|
|
rc := newReaderCacheWithPrefetch(2, release, &fetches)
|
|
defer rc.destroy()
|
|
defer close(release)
|
|
|
|
buf := make([]byte, 16<<10)
|
|
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
startPrefetch(t, rc, chunkSize)
|
|
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !isRetained(rc, "chunk0") {
|
|
t.Fatal("a pinned chunk was evicted while pinned chunks did not fill the limit")
|
|
}
|
|
|
|
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if isRetained(rc, "chunk0") {
|
|
t.Fatal("oldest pinned downloader was not evicted once pinned ones filled the limit")
|
|
}
|
|
for _, fileId := range []string{"chunk1", "chunk2", "prefetched"} {
|
|
if !isRetained(rc, fileId) {
|
|
t.Fatalf("%s missing after pinned fallback eviction", fileId)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The budget analog: a running download no stream is in holds the rest of the
|
|
// budget, so a stream's chunk is not evicted to make room next to it.
|
|
func TestChunkReadAtPinnedChunkSurvivesARunningPrefetchInTheBudget(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
var fetches int32
|
|
release := make(chan struct{})
|
|
budget := NewReaderCacheBudget(int64(2 * mem.AllocationSize(chunkSize)))
|
|
rc := newReaderCacheWithPrefetch(8, release, &fetches, budget)
|
|
defer rc.destroy()
|
|
defer close(release)
|
|
|
|
stream := &chunkStream{}
|
|
buf := make([]byte, 16<<10)
|
|
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
startPrefetch(t, rc, chunkSize)
|
|
|
|
read := waitForBudgetWaiter(t, func() error {
|
|
_, err := rc.ReadChunkAt(context.Background(), buf, "chunk1", nil, false, 0, chunkSize, false)
|
|
return err
|
|
})
|
|
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 16<<10), "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := atomic.LoadInt32(&fetches); got != 1 {
|
|
t.Errorf("chunk0 fetched %d times, want 1", got)
|
|
}
|
|
release <- struct{}{}
|
|
if err := <-read; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// A stream that leaves its chunk before the end frees that chunk's slot, so
|
|
// the read it leaves for doesn't evict another stream's chunk.
|
|
func TestChunkReadAtLeavingStreamKeepsAnotherStreamsChunk(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
var fetches int32
|
|
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
if fileId == "chunk1" {
|
|
atomic.AddInt32(&fetches, 1)
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
|
|
a, b := &chunkStream{}, &chunkStream{}
|
|
buf := make([]byte, 16<<10)
|
|
if _, err := rc.readChunkAt(context.Background(), b, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), a, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), a, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), b, buf, "chunk1", nil, false, 16<<10, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := atomic.LoadInt32(&fetches); got != 1 {
|
|
t.Errorf("chunk1 fetched %d times, want 1", got)
|
|
}
|
|
if isRetained(rc, "chunk0") {
|
|
t.Error("the chunk stream a left is still cached")
|
|
}
|
|
}
|
|
|
|
// A stream reaching a running download can leave pinned chunks filling the
|
|
// budget, so a read waiting for that download evicts the oldest pinned chunk
|
|
// at once instead.
|
|
func TestChunkReadAtBudgetWaitWakesWhenAStreamReachesARunningDownload(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
var fetches int32
|
|
release := make(chan struct{})
|
|
budget := NewReaderCacheBudget(int64(2 * mem.AllocationSize(chunkSize)))
|
|
rc := newReaderCacheWithPrefetch(8, release, &fetches, budget)
|
|
defer rc.destroy()
|
|
defer close(release)
|
|
|
|
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, make([]byte, 16<<10), "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
startPrefetch(t, rc, chunkSize)
|
|
read := waitForBudgetWaiter(t, func() error {
|
|
_, err := rc.ReadChunkAt(context.Background(), make([]byte, 16<<10), "chunk1", nil, false, 0, chunkSize, false)
|
|
return err
|
|
})
|
|
go func() {
|
|
_, _ = rc.readChunkAt(context.Background(), &chunkStream{}, make([]byte, 16<<10), "prefetched", nil, false, 0, chunkSize, false)
|
|
}()
|
|
|
|
select {
|
|
case err := <-read:
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the read kept waiting for the running download after a stream reached it")
|
|
}
|
|
}
|
|
|
|
// A read across a chunk boundary moves the stream to the chunk it ends in, so
|
|
// that chunk keeps its slot while reads without a stream fill the cache.
|
|
func TestChunkReadAtBoundaryReadMovesTheStream(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
// past the mock chunk cache's cutoff, so chunks don't land in it
|
|
const base = 2 << 20
|
|
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, sequentialChunkViews(base, chunkSize, 3), base+3*chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := reader.ReadAt(make([]byte, 16<<10), base+56<<10); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if isRetained(rc, "chunk0") {
|
|
t.Error("the chunk the stream finished is still cached")
|
|
}
|
|
for _, fileId := range []string{"filler0", "filler1"} {
|
|
if _, err := rc.ReadChunkAt(context.Background(), make([]byte, 1), fileId, nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if _, err := reader.ReadAt(make([]byte, 16<<10), base+72<<10); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n := countFetches(fetches, "chunk1"); n != 1 {
|
|
t.Errorf("chunk1 fetched %d times, want 1", n)
|
|
}
|
|
}
|
|
|
|
func sequentialChunkViews(base int64, chunkSize, count int) *IntervalList[*ChunkView] {
|
|
views := NewIntervalList[*ChunkView]()
|
|
for i := 0; i < count; i++ {
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: base + int64(i*chunkSize),
|
|
StopOffset: base + int64((i+1)*chunkSize),
|
|
Value: &ChunkView{FileId: fmt.Sprintf("chunk%d", i), ViewSize: uint64(chunkSize), ViewOffset: base + int64(i*chunkSize), ChunkSize: uint64(chunkSize)},
|
|
})
|
|
}
|
|
return views
|
|
}
|
|
|
|
func countFetches(fetches *[]recordedFetch, fileId string) (n int) {
|
|
for _, f := range *fetches {
|
|
if f.fileId == fileId {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// A read across a chunk boundary moves the stream when it reaches the last
|
|
// chunk, not when it ends, so a later read in another chunk that ends first
|
|
// keeps the stream, and its chunk stays cached.
|
|
func TestChunkReadAtBoundaryReadKeepsALaterReadsPosition(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
for name, size := range map[string]int{"stays": 16 << 10, "finishes": 8<<10 + chunkSize} {
|
|
t.Run(name, func(t *testing.T) {
|
|
rc := NewReaderCache(64, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
var mu sync.Mutex
|
|
fetches := map[string]int{}
|
|
var once, releaseOnce sync.Once
|
|
started, release := make(chan struct{}), make(chan struct{})
|
|
defer releaseOnce.Do(func() { close(release) })
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
mu.Lock()
|
|
fetches[fileId]++
|
|
mu.Unlock()
|
|
if fileId == "chunk1" {
|
|
once.Do(func() { close(started) })
|
|
<-release
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, sequentialChunkViews(base, chunkSize, 3), base+3*chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
boundary := make(chan error, 1)
|
|
go func() {
|
|
_, err := reader.ReadAt(make([]byte, size), base+56<<10)
|
|
boundary <- err
|
|
}()
|
|
select {
|
|
case <-started:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("the read across the boundary didn't fetch chunk1")
|
|
}
|
|
if _, err := reader.ReadAt(make([]byte, 16<<10), base+2*chunkSize); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
releaseOnce.Do(func() { close(release) })
|
|
if err := <-boundary; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := reader.ReadAt(make([]byte, 16<<10), base+2*chunkSize+16<<10); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if fetches["chunk2"] != 1 {
|
|
t.Errorf("chunk2 fetched %d times, want 1 (fetches %v)", fetches["chunk2"], fetches)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A read across a chunk boundary leaves the stream's chunk before it makes
|
|
// room for the chunks it reads, as a read of one chunk does, so with pinned
|
|
// chunks at the limit it doesn't evict another stream's chunk. It still reads
|
|
// the tail of the chunk it leaves from the cache.
|
|
func TestChunkReadAtBoundaryReadLeavesItsChunkBeforeMakingRoom(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
tests := map[string]struct {
|
|
offset int64
|
|
size int
|
|
}{
|
|
"from its chunk": {base + 56<<10, 16 << 10},
|
|
// more chunks than run at once, so the last one starts after others
|
|
// made room, and the last one is read as a range, so the stream is in
|
|
// no chunk while they do
|
|
"past its chunk": {base + chunkSize + 56<<10, 16<<10 + 3*chunkSize},
|
|
}
|
|
for name, tc := range tests {
|
|
t.Run(name, func(t *testing.T) {
|
|
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil)
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
other := &chunkStream{}
|
|
if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "other", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
views := sequentialChunkViews(base, chunkSize, 5)
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: base + 5*chunkSize,
|
|
StopOffset: base + 5*chunkSize + 8<<10,
|
|
Value: &ChunkView{FileId: "chunk5", ViewSize: 8 << 10, ViewOffset: base + 5*chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+5*chunkSize+8<<10, 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 56<<10), base); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := reader.ReadAt(make([]byte, tc.size), tc.offset); err != nil && err != io.EOF {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "other", nil, false, 1, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, fileId := range []string{"other", "chunk0"} {
|
|
if n := countFetches(fetches, fileId); n != 1 {
|
|
t.Errorf("%s fetched %d times, want 1", fileId, n)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func chunkViewList(chunkViews ...*ChunkView) *IntervalList[*ChunkView] {
|
|
views := NewIntervalList[*ChunkView]()
|
|
for _, v := range chunkViews {
|
|
views.AppendInterval(&Interval[*ChunkView]{StartOffset: v.ViewOffset, StopOffset: v.ViewOffset + int64(v.ViewSize), Value: v})
|
|
}
|
|
return views
|
|
}
|
|
|
|
// A compressed chunk written over in the middle shows up as two views of it,
|
|
// and a read across both that starts in it, where the stream is, downloads it
|
|
// once although the stream leaves it for the last chunk.
|
|
func TestChunkReadAtBoundaryReadHoldsEveryViewOfTheChunkItLeaves(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
|
defer rc.destroy()
|
|
fetches := fetchRecorder(rc)
|
|
views := chunkViewList(
|
|
&ChunkView{FileId: "A", IsGzipped: true, ViewSize: 16 << 10, ViewOffset: base, ChunkSize: chunkSize},
|
|
&ChunkView{FileId: "B", ViewSize: 16 << 10, ViewOffset: base + 16<<10, ChunkSize: 16 << 10},
|
|
&ChunkView{FileId: "A", IsGzipped: true, OffsetInChunk: 32 << 10, ViewSize: 32 << 10, ViewOffset: base + 32<<10, ChunkSize: chunkSize},
|
|
&ChunkView{FileId: "C", ViewSize: chunkSize, ViewOffset: base + chunkSize, ChunkSize: chunkSize},
|
|
)
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+2*chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 8<<10), base); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
buf := make([]byte, chunkSize)
|
|
if _, err := reader.ReadAt(buf, base+8<<10); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n := countFetches(fetches, "A"); n != 1 {
|
|
t.Errorf("A fetched %d times, want 1", n)
|
|
}
|
|
for i, want := range map[int]byte{0: 'A', 8 << 10: 'B', 24 << 10: 'A', 56 << 10: 'C'} {
|
|
if buf[i] != want {
|
|
t.Errorf("byte %d is %q, want %q", i, buf[i], want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The views of the chunk the stream leaves don't queue for a slot, as evicting
|
|
// that chunk waits for them. With more chunks than run at once ahead of one of
|
|
// them and the budget full of that chunk, the reads making room would otherwise
|
|
// wait for a view that can't start.
|
|
func TestChunkReadAtBoundaryReadDoesNotQueueTheChunkItLeaves(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
budget := NewReaderCacheBudget(int64(mem.AllocationSize(chunkSize)))
|
|
rc := NewReaderCache(64, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
|
return []string{"unused"}, nil
|
|
}, nil, budget)
|
|
fetchRecorder(rc)
|
|
list := []*ChunkView{{FileId: "A", IsGzipped: true, ViewSize: 16 << 10, ViewOffset: base, ChunkSize: chunkSize}}
|
|
end := int64(base + 16<<10)
|
|
for i := 0; i <= minReadConcurrency; i++ {
|
|
list = append(list, &ChunkView{FileId: fmt.Sprintf("B%d", i), ViewSize: chunkSize, ViewOffset: end, ChunkSize: chunkSize})
|
|
end += chunkSize
|
|
}
|
|
list = append(list,
|
|
&ChunkView{FileId: "A", IsGzipped: true, OffsetInChunk: 16 << 10, ViewSize: 48 << 10, ViewOffset: end, ChunkSize: chunkSize},
|
|
&ChunkView{FileId: "C", ViewSize: chunkSize, ViewOffset: end + 48<<10, ChunkSize: chunkSize},
|
|
)
|
|
end += 48<<10 + 8<<10
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, chunkViewList(list...), end+chunkSize, 0)
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 8<<10), base); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
read := make(chan error, 1)
|
|
go func() {
|
|
_, err := reader.ReadAt(make([]byte, end-(base+8<<10)), base+8<<10)
|
|
read <- err
|
|
}()
|
|
select {
|
|
case err := <-read:
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
// no cleanup: destroy would wait for the stuck downloads
|
|
t.Fatal("the read waited for a view of the chunk it left that couldn't start")
|
|
}
|
|
reader.ReleaseStream()
|
|
rc.destroy()
|
|
}
|
|
|
|
// A read across a chunk boundary starts its other chunks while the chunk the
|
|
// stream leaves still downloads, here for a concurrent read on the same reader,
|
|
// even with more views of that chunk than chunks run at once, and it doesn't
|
|
// start a goroutine for each of those views.
|
|
func TestChunkReadAtBoundaryReadDoesNotWaitForTheChunkItLeaves(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
const views = 4 * minReadConcurrency
|
|
const step = chunkSize / views
|
|
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
|
defer rc.destroy()
|
|
gate := make(chan struct{})
|
|
var gateOnce sync.Once
|
|
defer gateOnce.Do(func() { close(gate) })
|
|
chunk1Started := make(chan struct{})
|
|
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
|
switch fileId {
|
|
case "chunk0":
|
|
<-gate
|
|
case "chunk1":
|
|
close(chunk1Started)
|
|
}
|
|
return len(buffer), nil
|
|
}
|
|
var list []*ChunkView
|
|
for i := int64(0); i < views; i++ {
|
|
list = append(list,
|
|
&ChunkView{FileId: "chunk0", IsGzipped: true, OffsetInChunk: i * step, ViewSize: step / 2, ViewOffset: base + i*step, ChunkSize: chunkSize},
|
|
&ChunkView{FileId: fmt.Sprintf("gap%d", i), ViewSize: step / 2, ViewOffset: base + i*step + step/2, ChunkSize: step / 2},
|
|
)
|
|
}
|
|
list = append(list, &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: base + chunkSize, ChunkSize: chunkSize})
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, chunkViewList(list...), base+2*chunkSize, 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
head := make(chan error, 1)
|
|
go func() {
|
|
_, err := reader.ReadAt(make([]byte, step/2), base)
|
|
head <- err
|
|
}()
|
|
for deadline := time.Now().Add(5 * time.Second); !reader.stream.in("chunk0"); time.Sleep(time.Millisecond) {
|
|
select {
|
|
case err := <-head:
|
|
t.Fatalf("the head read finished before the stream entered chunk0: %v", err)
|
|
default:
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the stream never entered chunk0")
|
|
}
|
|
}
|
|
before := runtime.NumGoroutine()
|
|
boundary := make(chan error, 1)
|
|
go func() {
|
|
_, err := reader.ReadAt(make([]byte, chunkSize+8<<10), base)
|
|
boundary <- err
|
|
}()
|
|
select {
|
|
case <-chunk1Started:
|
|
if started := runtime.NumGoroutine() - before; started >= views {
|
|
t.Errorf("the read runs %d goroutines with %d views of the chunk it leaves", started, views)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Error("chunk1 was not fetched while chunk0 was still downloading")
|
|
}
|
|
gateOnce.Do(func() { close(gate) })
|
|
for _, done := range []chan error{head, boundary} {
|
|
if err := <-done; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// After a read across a chunk boundary the stream stays out of a last chunk it
|
|
// finished or read as a range, as after a read of that chunk alone, so it
|
|
// doesn't keep that chunk cached once another stream leaves it.
|
|
func TestChunkReadAtBoundaryReadLeavesAFinishedOrRangeChunk(t *testing.T) {
|
|
const chunkSize = 64 << 10
|
|
const base = 2 << 20
|
|
for name, lastView := range map[string]int{"finished": chunkSize, "range": 8 << 10} {
|
|
t.Run(name, func(t *testing.T) {
|
|
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
|
defer rc.destroy()
|
|
views := NewIntervalList[*ChunkView]()
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: base,
|
|
StopOffset: base + chunkSize,
|
|
Value: &ChunkView{FileId: "chunk0", ViewSize: chunkSize, ViewOffset: base, ChunkSize: chunkSize},
|
|
})
|
|
views.AppendInterval(&Interval[*ChunkView]{
|
|
StartOffset: base + chunkSize,
|
|
StopOffset: base + chunkSize + int64(lastView),
|
|
Value: &ChunkView{FileId: "chunk1", ViewSize: uint64(lastView), ViewOffset: base + chunkSize, ChunkSize: chunkSize},
|
|
})
|
|
other := &chunkStream{}
|
|
if _, err := rc.readChunkAt(context.Background(), other, make([]byte, 1), "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, base+chunkSize+int64(lastView), 0)
|
|
defer reader.ReleaseStream()
|
|
|
|
if _, err := reader.ReadAt(make([]byte, 8<<10+lastView), base+chunkSize-8<<10); err != nil && err != io.EOF {
|
|
t.Fatal(err)
|
|
}
|
|
rc.releaseStream(other)
|
|
if isRetained(rc, "chunk1") {
|
|
t.Error("the stream kept a chunk it is done with cached")
|
|
}
|
|
})
|
|
}
|
|
}
|