filer: RecursiveLister, a subtree in path order from one range of postgres_flat (#13261)

* filer: RecursiveLister, a store capability to list a subtree in path order

The wrapper hands it to the default store, reading hard links as listings
do, and declines it when path-specific stores could hold part of the
subtree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: list a subtree with one range scan when rows are keyed by path

AbstractSqlStore lists recursively when its generator implements
RecursiveListSqlGenerator. The range runs from the directory and prefix to
the least string past every path starting with them. A directory whose
subtree spans the bucket tables is declined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: the postgres_flat generator lists a path range

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/store_test: check recursive listings

Byte order across +, -, / and non-ASCII names, prefixes holding a slash,
literal % and _, resuming after a path, pages of one and three, a
directory outside the buckets, and the directories that span bucket
tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: a recursive listing's start path outside the bucket table bounds it by full path

A start path in another bucket was trimmed as if it were inside this one, so
a start path past the bucket listed it all again, and one before it could
skip entries.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-12-02 12:03:18 -08:00
1 parent b7536bd6f6
commit 38422bd1fa
7 files changed
+240

No files matched your search

@@ -0,0 +1,95 @@
package abstract_sql
import (
"context"
"fmt"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
var _ filer.RecursiveLister = (*AbstractSqlStore)(nil)
// RecursiveListSqlGenerator is implemented by a generator whose rows are keyed
// by their path. GetSqlListRecursive selects directory, name and meta of the
// rows with after < path, from <= path and, unless to is empty, path < to, in
// path order.
type RecursiveListSqlGenerator interface {
GetSqlListRecursive(tableName string, after, from, to string, limit int64) (string, []interface{})
}
// ListRecursivePrefixedEntries implements filer.RecursiveLister for a
// generator keyed by path, and for a directory whose subtree is in one table.
func (store *AbstractSqlStore) ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastPath util.FullPath, err error) {
gen, ok := store.SqlGenerator.(RecursiveListSqlGenerator)
if !ok {
return "", filer.ErrUnsupportedRecursiveListing
}
if store.SupportBucketTable && (dirPath == "/" || string(dirPath) == bucketsRoot) {
return "", fmt.Errorf("%w: %s spans the bucket tables", filer.ErrUnsupportedRecursiveListing, dirPath)
}
db, table, shortPath, err := store.getTxOrDB(ctx, dirPath, true)
if err != nil {
return "", fmt.Errorf("findDB %s : %v", dirPath, err)
}
base := ""
if table != DEFAULT_TABLE {
base = bucketBase(table)
}
from := strings.TrimSuffix(string(shortPath), "/") + "/" + prefix
to, _ := prefixEnd(from)
after := string(startPath)
if base != "" {
switch {
case strings.HasPrefix(after, base+"/"):
after = after[len(base):]
case after < base+"/":
after = ""
default:
return "", nil
}
}
sqlText, args := gen.GetSqlListRecursive(table, after, from, to, limit)
rows, err := db.QueryContext(ctx, sqlText, args...)
if err != nil {
return "", fmt.Errorf("list %s recursively: %v", dirPath, err)
}
defer rows.Close()
// The callback may query the store (a hard link's record), so the entries
// are handed over after the rows close.
var entries []*filer.Entry
for rows.Next() {
var dir, name string
var data []byte
if err = rows.Scan(&dir, &name, &data); err != nil {
return lastPath, fmt.Errorf("scan %s: %v", dirPath, err)
}
if base != "" {
dir = base + strings.TrimSuffix(dir, "/")
}
entry := &filer.Entry{FullPath: util.NewFullPath(dir, name)}
if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
return lastPath, fmt.Errorf("decode %s : %v", entry.FullPath, err)
}
entries = append(entries, entry)
}
if err = rows.Err(); err != nil {
return lastPath, fmt.Errorf("list %s recursively: %w", dirPath, err)
}
rows.Close()
for _, entry := range entries {
lastPath = entry.FullPath
more, eachErr := eachEntryFunc(entry)
if eachErr != nil {
return lastPath, fmt.Errorf("failed to process eachEntryFunc: %w", eachErr)
}
if !more {
break
}
}
return lastPath, nil
}
+13
View File
@@ -118,6 +118,19 @@ type EntryScanner interface {
ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error
}
// ErrUnsupportedRecursiveListing is returned by RecursiveLister, before any
// entry is listed, when the store cannot list below dirPath in path order.
var ErrUnsupportedRecursiveListing = errors.New("recursive listing not supported by this filer store")
// RecursiveLister is an optional FilerStore capability: list the entries below
// dirPath, directories included, in byte order of their full paths. Only
// paths after startPath that start with dirPath + "/" + prefix are listed;
// prefix may hold "/". lastPath is the last path the store read, and a
// listing continues after it.
type RecursiveLister interface {
ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc ListEachEntryFunc) (lastPath util.FullPath, err error)
}
type BucketAware interface {
OnBucketCreation(bucket string)
OnBucketDeletion(bucket string)
+4
View File
@@ -478,6 +478,7 @@ type hardLinkListing struct {
each ListEachEntryFunc
held []*Entry // waiting for their records; the first has a hard link
last string // the name of the last entry handed on
byPath bool // last holds the full path instead
ended bool // each ended the listing or failed
passed bool // each ended it at an entry with others waiting behind
}
@@ -545,6 +546,9 @@ func (l *hardLinkListing) handOn(entry *Entry) (bool, error) {
return more, err
}
l.last = entry.Name()
if l.byPath {
l.last = string(entry.FullPath)
}
l.ended = !more
return more, nil
}
+27
View File
@@ -22,6 +22,7 @@ var (
_ = VirtualFilerStore(&FilerStoreWrapper{})
_ = Debuggable(&FilerStoreWrapper{})
_ = EntryScanner(&FilerStoreWrapper{})
_ = RecursiveLister(&FilerStoreWrapper{})
)
type VirtualFilerStore interface {
@@ -453,6 +454,32 @@ func (fsw *FilerStoreWrapper) ScanEntries(ctx context.Context, dirPath util.Full
})
}
// ListRecursivePrefixedEntries delegates to the default store, and is declined
// when path-specific stores could hold part of the subtree.
func (fsw *FilerStoreWrapper) ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc ListEachEntryFunc) (lastPath util.FullPath, err error) {
if fsw.hasPathSpecificStore {
return "", ErrUnsupportedRecursiveListing
}
lister, ok := fsw.defaultStore.(RecursiveLister)
if !ok {
return "", ErrUnsupportedRecursiveListing
}
ctx = context.WithoutCancel(ctx)
stats.FilerStoreCounter.WithLabelValues(fsw.defaultStore.GetName(), "recursiveList").Inc()
start := time.Now()
defer func() {
stats.FilerStoreHistogram.WithLabelValues(fsw.defaultStore.GetName(), "recursiveList").Observe(time.Since(start).Seconds())
}()
listing := fsw.newHardLinkListing(ctx, eachEntryFunc)
listing.byPath = true
defer func() {
var last string
last, err = listing.finish(string(lastPath), err)
lastPath = util.FullPath(last)
}()
return lister.ListRecursivePrefixedEntries(ctx, dirPath, startPath, prefix, limit, listing.add)
}
func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) {
actualStore := fsw.getActualStore(dirPath + "/")
@@ -21,6 +21,7 @@ const DefaultFlatUpsertQuery = `INSERT INTO "%s" (path,directory,name,meta) VALU
var (
_ = abstract_sql.SqlGenerator(&SqlGenPostgresFlat{})
_ = abstract_sql.PathListSqlGenerator(&SqlGenPostgresFlat{})
_ = abstract_sql.RecursiveListSqlGenerator(&SqlGenPostgresFlat{})
)
func flatPath(key abstract_sql.RowKey) string {
@@ -109,3 +110,16 @@ func (gen *SqlGenPostgresFlat) GetSqlListPath(tableName, dir, after, from, to st
return fmt.Sprintf(`SELECT directory, name, CASE WHEN directory=$1 THEN meta END FROM "%s" WHERE %s>$2 AND %s>=$3 AND %s<$4 ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), path, path, path, path),
[]interface{}{dir, after, from, to, limit}
}
func (gen *SqlGenPostgresFlat) GetSqlListRecursive(tableName string, after, from, to string, limit int64) (string, []interface{}) {
path := "path"
if gen.ForceBinaryCollation {
path = `path COLLATE "C"`
}
if to == "" {
return fmt.Sprintf(`SELECT directory, name, meta FROM "%s" WHERE %s>$1 AND %s>=$2 ORDER BY %s ASC LIMIT $3`, tableIdent(tableName), path, path, path),
[]interface{}{after, from, limit}
}
return fmt.Sprintf(`SELECT directory, name, meta FROM "%s" WHERE %s>$1 AND %s>=$2 AND %s<$3 ORDER BY %s ASC LIMIT $4`, tableIdent(tableName), path, path, path, path),
[]interface{}{after, from, to, limit}
}
@@ -44,6 +44,22 @@ func TestFlatStatementsAddressRowsByPath(t *testing.T) {
}
}
func TestFlatRecursiveListing(t *testing.T) {
gen := &SqlGenPostgresFlat{}
list, args := gen.GetSqlListRecursive("bkt", "/a/b", "/a/", "/a0", 100)
if !strings.Contains(list, "WHERE path>$1 AND path>=$2 AND path<$3 ORDER BY path ASC LIMIT $4") || len(args) != 4 || args[0] != "/a/b" || args[2] != "/a0" {
t.Fatalf("list %s %v", list, args)
}
list, args = gen.GetSqlListRecursive("bkt", "", "/", "", 100)
if strings.Contains(list, "$4") || len(args) != 3 {
t.Fatalf("unbounded list %s %v", list, args)
}
gen.ForceBinaryCollation = true
if list, _ = gen.GetSqlListRecursive("bkt", "", "/", "/0", 1); !strings.Contains(list, `ORDER BY path COLLATE "C"`) {
t.Fatalf("list without a byte-ordered column: %s", list)
}
}
func TestFlatPathListing(t *testing.T) {
gen := &SqlGenPostgresFlat{}
list, args := gen.GetSqlListPath("bkt", "/a", "/a/b", "/a/", "/a0", 100)
+71
View File
@@ -192,6 +192,77 @@ func TestFilerStoreConformance(t *testing.T, store filer.FilerStore) {
})
}
if lister, ok := store.(filer.RecursiveLister); ok {
t.Run("recursive listing", func(t *testing.T) {
listAll := func(t *testing.T, d, start, prefix string, limit int64) ([]string, error) {
t.Helper()
var paths []string
for {
n := 0
last, err := lister.ListRecursivePrefixedEntries(ctx, util.FullPath(d), util.FullPath(start), prefix, limit, func(e *filer.Entry) (bool, error) {
paths = append(paths, string(e.FullPath))
n++
return true, nil
})
if err != nil || int64(n) < limit {
return paths, err
}
start = string(last)
}
}
root := "/buckets/bkt1/rec"
if _, err := listAll(t, root, "", "", 10); errors.Is(err, filer.ErrUnsupportedRecursiveListing) {
t.Skip(err)
}
insert(t, dir(root), dir(root+"/a"), dir(root+"/a/y"), dir(root+"/a-b"), dir(root+"/日本"),
file(root+"/a+b", 1), file(root+"/a/x", 1), file(root+"/a/y/z", 1), file(root+"/a-b/x", 1),
file(root+"/a0", 1), file(root+"/日本/x", 1), file(root+"/%_!", 1), file("/buckets/bkt1/rec0", 1))
rel := func(names ...string) []string {
for i, n := range names {
names[i] = root + "/" + n
}
return names
}
all := rel("%_!", "a", "a+b", "a-b", "a-b/x", "a/x", "a/y", "a/y/z", "a0", "日本", "日本/x")
for _, limit := range []int64{1000, 3, 1} {
got, err := listAll(t, root, "", "", limit)
require.NoError(t, err)
require.Equal(t, all, got, "limit %d", limit)
}
got, err := listAll(t, root, "", "a/", 1000)
require.NoError(t, err)
require.Equal(t, rel("a/x", "a/y", "a/y/z"), got)
got, err = listAll(t, root, "", "a", 2)
require.NoError(t, err)
require.Equal(t, rel("a", "a+b", "a-b", "a-b/x", "a/x", "a/y", "a/y/z", "a0"), got)
got, err = listAll(t, root, "", "%_", 1000)
require.NoError(t, err)
require.Equal(t, rel("%_!"), got, "% and _ are literal")
got, err = listAll(t, root, root+"/a-b/x", "", 1000)
require.NoError(t, err)
require.Equal(t, rel("a/x", "a/y", "a/y/z", "a0", "日本", "日本/x"), got)
got, err = listAll(t, root+"/a", "", "", 1000)
require.NoError(t, err)
require.Equal(t, rel("a/x", "a/y", "a/y/z"), got)
got, err = listAll(t, root, "/buckets/aaa/z", "", 1000)
require.NoError(t, err)
require.Equal(t, all, got, "a start path before the subtree")
got, err = listAll(t, root, "/buckets/bkt2/a", "", 1000)
require.NoError(t, err)
require.Empty(t, got, "a start path past the subtree")
got, err = listAll(t, "/topics", "", "", 1000)
require.NoError(t, err)
require.Equal(t, []string{"/topics/t.log"}, got)
if bucketAware, ok := store.(filer.BucketAware); ok && bucketAware.CanDropWholeBucket() {
for _, d := range []string{"/", "/buckets"} {
_, err := listAll(t, d, "", "", 10)
require.ErrorIs(t, err, filer.ErrUnsupportedRecursiveListing, "%s spans the bucket tables", d)
}
}
})
}
t.Run("delete folder children", func(t *testing.T) {
require.NoError(t, store.DeleteFolderChildren(ctx, "/buckets/bkt1/order"))
require.Empty(t, list(t, "/buckets/bkt1/order", "", false, 100, ""))