Files
seaweedfs/weed/mount/weedfs_dir_read_pagination_test.go
T
Yip LeoandClaude Opus 5.5 82a435c468 mount: list a directory from the filer when the cache disk cannot hold it (#13204)
* mount: list a directory from the filer when the cache disk cannot hold it

A listing builds the directory into the mount's local metadata cache, a
leveldb store under -cacheDir, and serves it from there. Once that disk is
full the build fails at its first write, and the listing failed with it:
readdir returned EIO for every directory the mount had not cached, and for
one whose cached listing a refused event had just dropped (#13141). Files
could still be opened, read and written; only listing them broke.

A build the store refuses now reports a LocalStoreError, and the listing
reads the directory through from the filer, the way it already does for a
directory too large to cache. Builds then wait out a 10s backoff instead of
re-listing a directory from the filer only to fail at its first insert
again; once the disk has room the next build caches the directory. While
the store refuses, at most 4 listings per mount read through at once, so a
burst of them reaches the filer spread out rather than all together.

The hand-over from a walk served from the cache to one read through from
the filer resumed at the request's offset, so the entries the cached walk
had just put in the same reply were sent again and the client listed them
twice. A directory found too large partway through a walk took that path
rarely; a full cache disk takes it on every request. The direct walk now
resumes past the entries already in the reply.

Lookups needed no change: in a directory the cache does not hold, a lookup
already asks the filer for the one entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: list unflushed creates and every page when reading a directory through

Listings read through from the filer are now the common path on a full
cache disk. This fixes three gaps in them:

- A file created on this mount is not on the filer until its first flush.
  Until then the local store holds a placeholder for it, which a rebuild
  keeps. A cached listing showed such a file; a listing read through from
  the filer left it out. The read-through now merges in, page by page and
  in name order, the children the local store keeps for a rebuild
  (MetaCache.LocalOnlyChildren, which asks the same pinnedChildFn as the
  rebuild's wipe). Each page takes the ones after its start and up to its
  last name; the last page takes every one past its start. A name the
  filer also has by now is listed once. Directories too large to cache
  read through the same way, so they get the fix as well.
- The filer applies the page limit before the loader leaves out the root's
  hidden system entries (etc, topics). A full page that held one came back
  short, and the listing ended there. The end of the directory is now read
  from the number of entries the filer sent. If a failover reruns a page,
  the loader starts its entries and that count over.
- A walk served from the cache also hands over to the filer when
  refreshing a stale section would list too many entries
  (ErrRefreshRangeTooLarge). That hand-over still resumed at the request's
  offset, so it sent again the entries already in the reply. It now
  resumes where the cached walk reached, like the other hand-over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the rest of a read-through page on the directory handle

A page listed from the filer went onto the directory handle only up to the
entry the reply had no room for. The next request listed the filer again
from there and merged the unflushed creates again, so with small replies
each filer page was listed, and the local store scanned, once per reply.
Now the whole page goes onto the handle, and later requests take what is
left from it, as they do from the cache. The unflushed creates are also
looked up without decoding chunk lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:57:29 -08:00

664 lines
21 KiB
Go

package mount
import (
"context"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// pagingSink collects names, accepting at most limit per round the way a kernel
// reply buffer does.
type pagingSink struct {
limit int
names []string
lastOff uint64
round int
}
func (s *pagingSink) AddEntry(entry fuse.DirEntry) bool {
if s.round >= s.limit {
return false
}
s.round++
s.names = append(s.names, entry.Name)
s.lastOff = entry.Off
return true
}
func (s *pagingSink) AddEntryPlus(entry fuse.DirEntry) *fuse.EntryOut { return nil }
func (s *pagingSink) TakesLookupRef() bool { return true }
func newPagingWFS(tb testing.TB, dir util.FullPath, names []string, ttlSec int32) *WFS {
tb.Helper()
uidGidMapper, err := meta_cache.NewUidGidMapper("", "")
if err != nil {
tb.Fatalf("uid/gid mapper: %v", err)
}
root := util.FullPath("/")
wfs := &WFS{
option: &Option{
ChunkSizeLimit: 1024, ConcurrentReaders: 1, VolumeServerAccess: "filerProxy",
FilerAddresses: []pb.ServerAddress{pb.NewServerAddressWithGrpcPort("127.0.0.1:1", 1)},
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
FilerMountRootPath: "/", MountUid: 99, MountGid: 100, MountMode: 0o777,
MountMtime: time.Now(), MountCtime: time.Now(), UidGidMapper: uidGidMapper,
},
signature: 1, inodeToPath: NewInodeToPath(root, 0),
fhMap: NewFileHandleToInode(), dhMap: NewDirectoryHandleToInode(),
fhLockTable: util.NewLockTable[FileHandleId](), hardLinkLockTable: util.NewLockTable[string](),
}
wfs.metaCache = meta_cache.NewMetaCache(
filepath.Join(tb.TempDir(), "meta"), uidGidMapper, root, false,
func(p util.FullPath) { wfs.inodeToPath.MarkChildrenCached(p) },
func(p util.FullPath) bool { return wfs.inodeToPath.IsChildrenCached(p) },
func(meta_cache.EntryInvalidation) {}, nil,
)
tb.Cleanup(wfs.metaCache.Shutdown)
now := time.Now()
ctx := context.Background()
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{
FullPath: dir,
Attr: filer.Attr{Mode: os.ModeDir | 0o755, Mtime: now, Crtime: now},
}, 0); err != nil {
tb.Fatalf("insert dir: %v", err)
}
for _, name := range names {
child := dir.Child(name)
attr := filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 1, Inode: child.AsInode(now.Unix())}
if ttlSec > 0 {
// Expired well in the past, so the meta cache drops it after the
// store has already counted it against the limit.
attr.TtlSec = ttlSec
attr.Crtime = now.Add(-time.Duration(ttlSec+60) * time.Second)
}
if err := wfs.metaCache.InsertEntry(ctx, &filer.Entry{FullPath: child, Attr: attr}, 0); err != nil {
tb.Fatalf("insert %s: %v", name, err)
}
}
wfs.inodeToPath.MarkChildrenCached(root)
wfs.inodeToPath.Lookup(dir, now.Unix(), true, false, 0, true)
wfs.inodeToPath.MarkChildrenCached(dir)
return wfs
}
// TestReadDirResumePastShrunkDirectory covers a client resuming a fresh handle
// at a cookie from an earlier, larger listing. The directory has since shrunk
// past that offset, and the readdir used to fall back to listing from the first
// child again, handing back names the client had already consumed.
func TestReadDirResumePastShrunkDirectory(t *testing.T) {
dir := util.FullPath("/d")
var names []string
for i := 0; i < 100; i++ {
names = append(names, fmt.Sprintf("f%03d", i))
}
wfs := newPagingWFS(t, dir, names, 0)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 4096}
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: 152, // past the end of a directory that now holds 100
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if len(sink.names) != 0 {
t.Errorf("resuming past the end returned %d entries (first %q), want none", len(sink.names), sink.names[0])
}
}
// TestReadDirWithExpiredEntries covers a batch the store fills to the limit but
// whose entries the meta cache then drops as expired. The post-filter count used
// to be read as end-of-directory, silently hiding every later child.
func TestReadDirWithExpiredEntries(t *testing.T) {
dir := util.FullPath("/d")
// One full store batch of entries that all expire, then live ones behind
// them. Nothing survives the first batch, which is the case that latched.
var names []string
for i := 0; i < batchSize; i++ {
names = append(names, fmt.Sprintf("a%05d", i))
}
wfs := newPagingWFS(t, dir, names, 30)
live := []string{"z001", "z002", "z003"}
now := time.Now()
for _, name := range live {
child := dir.Child(name)
if err := wfs.metaCache.InsertEntry(context.Background(), &filer.Entry{
FullPath: child,
Attr: filer.Attr{Mode: 0o644, Mtime: now, Crtime: now, FileSize: 1, Inode: child.AsInode(now.Unix())},
}, 0); err != nil {
t.Fatalf("insert %s: %v", name, err)
}
}
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 4096}
var offset uint64
for round := 0; round < 20; round++ {
sink.round = 0
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
var seen []string
for _, n := range sink.names {
if n != "." && n != ".." {
seen = append(seen, n)
}
}
if len(seen) != len(live) {
t.Fatalf("listed %d entries %v, want the %d live ones %v", len(seen), seen, len(live), live)
}
}
// TestReadDirTrimsConsumedEntries checks that a walk does not accumulate the
// whole directory in the handle. Offsets index into the stream from
// entryStreamOffset, so the two have to advance together or the listing
// silently misaligns.
func TestReadDirTrimsConsumedEntries(t *testing.T) {
dir := util.FullPath("/d")
const total = 5000
var names []string
for i := 0; i < total; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
wfs := newPagingWFS(t, dir, names, 0)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, dh := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
// A small sink forces many rounds, which is when the stream would grow.
sink := &pagingSink{limit: 64}
var offset uint64
var seen []string
peak := 0
for round := 0; round < 500; round++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if n := len(dh.entryStream); n > peak {
peak = n
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
for _, n := range sink.names {
if n != "." && n != ".." {
seen = append(seen, n)
}
}
if len(seen) != total {
t.Fatalf("listed %d entries, want %d", len(seen), total)
}
for i, name := range seen {
if want := fmt.Sprintf("f%05d", i); name != want {
t.Fatalf("entry %d is %q, want %q -- trimming misaligned the offsets", i, name, want)
}
}
// Without trimming the handle ends up holding every entry.
if peak >= total {
t.Errorf("handle held %d entries at peak, want well under the %d in the directory", peak, total)
}
}
// listingFilerServer serves a fixed, sorted child list the way the filer
// paginates one.
type listingFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
names []string
}
func (s *listingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
var sent uint32
for _, name := range s.names {
if name < req.StartFromFileName || (name == req.StartFromFileName && !req.InclusiveStartFrom) {
continue
}
if req.Limit > 0 && sent >= req.Limit {
break
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: 1},
}}); err != nil {
return err
}
sent++
}
return nil
}
// TestReadDirDirectTrimsConsumedEntries is the same check for a directory read
// through to the filer. That path is taken precisely for directories too big to
// cache, so holding the whole walk in the handle is where a listing turns into
// gigabytes of resident memory.
func TestReadDirDirectTrimsConsumedEntries(t *testing.T) {
dir := util.FullPath("/d")
const total = 5000
var names []string
for i := 0; i < total; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
wfs := newPagingWFS(t, dir, nil, 0)
startFakeFiler(t, wfs, &listingFilerServer{names: names})
dirInode, _ := wfs.inodeToPath.GetInode(dir)
if !wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now()) {
t.Fatal("directory did not enter read-through mode")
}
dhid, dh := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 64}
var offset uint64
var seen []string
peak := 0
for round := 0; round < 500; round++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if n := len(dh.entryStream); n > peak {
peak = n
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
for _, n := range sink.names {
if n != "." && n != ".." {
seen = append(seen, n)
}
}
if len(seen) != total {
t.Fatalf("listed %d entries, want %d", len(seen), total)
}
for i, name := range seen {
if want := fmt.Sprintf("f%05d", i); name != want {
t.Fatalf("entry %d is %q, want %q -- trimming misaligned the offsets", i, name, want)
}
}
if peak >= total {
t.Errorf("handle held %d entries at peak, want well under the %d in the directory", peak, total)
}
}
// The table has to key on the sanitized name, not the stored bytes.
func TestReadDirPlusSanitizedName(t *testing.T) {
dir := util.FullPath("/images")
const rawName = "bad\xffname.jpg"
wfs := newPagingWFS(t, dir, []string{"good.jpg", rawName}, 0)
dirInode, _ := wfs.inodeToPath.GetInode(dir)
sink := &benchSink{plus: true, takesRef: true, sinkLimit: 16}
if got := walkOnce(t, wfs, dirInode, sink, false); got != 4 {
t.Fatalf("listed %d entries, want 4 (. .. and two children)", got)
}
sanitized := dir.Child(util.SanitizeUTF8Name(rawName))
if !wfs.inodeToPath.HasPath(sanitized) {
t.Errorf("%s not in the inode table", sanitized)
}
if wfs.inodeToPath.HasPath(dir.Child(rawName)) {
t.Errorf("%s keyed on the unsanitized name", dir.Child(rawName))
}
}
// A listing that began from the cache hands over to the filer when the
// directory stops being cacheable partway: here its cached listing is dropped
// and the rebuild finds it too large. The hand-over resumed the direct walk at
// the request's offset, so the entries the cached walk had just put in the same
// reply were sent again and the client saw names twice. A full cache disk
// takes the same hand-over on every request.
func TestReadDirHandOverToTheFilerMidWalkSendsEachNameOnce(t *testing.T) {
dir := util.FullPath("/d")
const total = 2500
var names []string
for i := 0; i < total; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
// The cache holds the first 1500 names, the filer all of them: a walk
// that lists every name finished from the filer.
wfs := newPagingWFS(t, dir, names[:1500], 0)
wfs.option.CacheDirMaxEntries = 100
startFakeFiler(t, wfs, &listingFilerServer{names: names})
dirInode, _ := wfs.inodeToPath.GetInode(dir)
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: 64}
var offset uint64
dropped := false
for round := 0; round < 1000; round++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if !dropped {
// The cached listing goes away after the first reply.
wfs.inodeToPath.InvalidateChildrenCache(dir)
dropped = true
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
seen := map[string]int{}
var listed []string
for _, n := range sink.names {
if n == "." || n == ".." {
continue
}
seen[n]++
listed = append(listed, n)
}
for n, count := range seen {
if count > 1 {
t.Errorf("%s listed %d times", n, count)
}
}
if len(seen) != total {
t.Fatalf("listed %d distinct names (%d in all), want %d", len(seen), len(listed), total)
}
}
// listWholeDirectory lists dir through one handle in replies of at most
// sinkLimit entries, calling afterReply after each, and returns the names in
// listing order without "." and "..".
func listWholeDirectory(t *testing.T, wfs *WFS, dir util.FullPath, sinkLimit int, afterReply func(reply int)) []string {
t.Helper()
dirInode, found := wfs.inodeToPath.GetInode(dir)
if !found {
t.Fatalf("no inode for %s", dir)
}
dhid, _ := wfs.AcquireDirectoryHandle()
defer wfs.ReleaseDirectoryHandle(dhid)
sink := &pagingSink{limit: sinkLimit}
var offset uint64
for reply := 0; reply < 100000; reply++ {
sink.round = 0
before := len(sink.names)
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
InHeader: fuse.InHeader{NodeId: dirInode},
Fh: uint64(dhid),
Offset: offset,
Size: 1 << 20,
}, sink, false)
if status != fuse.OK {
t.Fatalf("readdir: %v", status)
}
if afterReply != nil {
afterReply(reply)
}
if len(sink.names) == before || sink.lastOff <= offset {
break
}
offset = sink.lastOff
}
var names []string
for _, name := range sink.names {
if name != "." && name != ".." {
names = append(names, name)
}
}
return names
}
// requireListing fails unless got is want: every name once, in order.
func requireListing(t *testing.T, got, want []string) {
t.Helper()
if slices.Equal(got, want) {
return
}
seen := map[string]int{}
for _, name := range got {
seen[name]++
}
var twice, missing []string
for name, count := range seen {
if count > 1 {
twice = append(twice, name)
}
}
for _, name := range want {
if seen[name] == 0 {
missing = append(missing, name)
}
}
sort.Strings(twice)
first := func(names []string) []string {
if len(names) > 5 {
return names[:5]
}
return names
}
t.Fatalf("listed %d names, want %d; listed more than once: %d %v; missing: %d %v", len(got), len(want), len(twice), first(twice), len(missing), first(missing))
}
// createUnflushed leaves dir/name as Create leaves a file before its first
// flush: a placeholder in the local store, and an open handle with dirty
// metadata.
func createUnflushed(t *testing.T, wfs *WFS, dir util.FullPath, name string) {
t.Helper()
path := dir.Child(name)
now := time.Now()
inode := wfs.inodeToPath.Lookup(path, now.Unix(), false, false, 0, true)
entry := &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, Mtime: now.Unix(), Crtime: now.Unix(), Inode: inode},
}
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(string(dir), entry), 0); err != nil {
t.Fatalf("insert placeholder %s: %v", path, err)
}
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
fh.dirtyMetadata = true
t.Cleanup(fh.dirtyPages.Destroy)
}
// A directory read through from the filer lists the files this mount created
// and has not flushed, as a cached listing does, though the filer has none of
// them yet: each once and in name order, wherever it falls among the filer's
// pages. One the filer has by now is listed once.
func TestReadDirReadThroughListsUnflushedCreates(t *testing.T) {
dir := util.FullPath("/d")
var filerNames []string
for i := 0; i < 2500; i++ {
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
}
// Before the first page, right after a page's last name, inside a page, a
// name the filer has by now, and past the last page.
unflushed := []string{"a-new", "f00999x", "f01500x", "f02000", "z-new"}
want := append(append([]string{}, filerNames...), "a-new", "f00999x", "f01500x", "z-new")
sort.Strings(want)
for _, sinkLimit := range []int{64, 5000} {
t.Run(fmt.Sprintf("replies of %d", sinkLimit), func(t *testing.T) {
wfs := newPagingWFS(t, dir, nil, 0)
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
for _, name := range unflushed {
createUnflushed(t, wfs, dir, name)
}
// Too large to cache: listings read it through.
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
requireListing(t, listWholeDirectory(t, wfs, dir, sinkLimit, nil), want)
})
}
}
// The mount's root read through from the filer. The loader leaves out the
// hidden system entries, etc and topics, so a full page from the filer that
// held one came back short and was taken for the end of the directory.
func TestReadDirReadThroughRootPastHiddenEntries(t *testing.T) {
root := util.FullPath("/")
var visible []string
for _, prefix := range []string{"d", "s", "u"} {
for i := 0; i < 500; i++ {
visible = append(visible, fmt.Sprintf("%s%04d", prefix, i))
}
}
// etc falls inside the first page of 1000, topics inside the second.
filerNames := append([]string{"etc", "topics"}, visible...)
sort.Strings(filerNames)
wfs := newPagingWFS(t, "/x", nil, 0)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
wfs.inodeToPath.MarkDirectoryReadThrough(root, time.Now())
requireListing(t, listWholeDirectory(t, wfs, root, 5000, nil), visible)
}
// A listing walking the cache hands over to the filer when a section of the
// directory changed so much that refreshing it would list more than a
// refresh may (ErrRefreshRangeTooLarge). That hand-over, too, resumed at the
// request's offset and sent again the entries the cached walk had just put in
// the reply.
func TestReadDirHandOverOnOvergrownSectionSendsEachNameOnce(t *testing.T) {
ctx := context.Background()
dir := util.FullPath("/d")
var cached, filerNames, burst []string
for i := 0; i < 2000; i++ {
cached = append(cached, fmt.Sprintf("f%05d", i))
}
// Far more than one refresh may list.
for i := 0; i < 6000; i++ {
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
}
// Enough changes in one go to make a section stale.
for i := 0; i < 64; i++ {
burst = append(burst, fmt.Sprintf("g-%03d", i))
}
filerNames = append(filerNames, burst...)
wfs := newPagingWFS(t, dir, cached, 0)
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
// One section over the directory, as a build of it leaves.
if err := wfs.metaCache.BeginDirectoryBuild(ctx, dir); err != nil {
t.Fatalf("begin build: %v", err)
}
if err := wfs.metaCache.CompleteDirectoryBuild(ctx, dir, 1000, nil); err != nil {
t.Fatalf("complete build: %v", err)
}
got := listWholeDirectory(t, wfs, dir, 64, func(reply int) {
if reply != 0 {
return
}
// After the first reply other clients create a burst of files: the
// section goes stale, and refreshing it would list too much.
for i, name := range burst {
resp := &filer_pb.SubscribeMetadataResponse{
Directory: string(dir),
EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0o100644, FileSize: 1},
}},
TsNs: 2000 + int64(i),
}
if err := wfs.metaCache.ApplyMetadataResponse(ctx, resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
t.Fatalf("apply %s: %v", name, err)
}
}
})
requireListing(t, got, filerNames)
}
// countingListingFilerServer counts the listings it serves.
type countingListingFilerServer struct {
listingFilerServer
listings atomic.Int32
}
func (s *countingListingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
s.listings.Add(1)
return s.listingFilerServer.ListEntries(req, stream)
}
// A page listed from the filer stays on the handle until the client has read
// it. A listing in small replies then lists each filer page once, and merges
// the unflushed creates once per page, rather than again for every reply.
func TestReadDirReadThroughListsEachFilerPageOnce(t *testing.T) {
dir := util.FullPath("/d")
var names []string
for i := 0; i < 2500; i++ {
names = append(names, fmt.Sprintf("f%05d", i))
}
wfs := newPagingWFS(t, dir, nil, 0)
server := &countingListingFilerServer{listingFilerServer: listingFilerServer{names: names}}
startFakeFiler(t, wfs, server)
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
requireListing(t, listWholeDirectory(t, wfs, dir, 64, nil), names)
// Three pages, and the empty one that finds the end.
if n := server.listings.Load(); n > 4 {
t.Errorf("the filer was asked for %d listings, want one per page of %d", n, batchSize)
}
}