Files
2026-11-30 16:32:37 +00:00

83 lines
2.8 KiB
Go

package main
import (
"errors"
"io"
"os"
"slices"
"sort"
"unicode/utf8"
)
// maxDirListEntries caps how many entries a directory-listing response may
// contain. Every other bulk operation in the files API is already bounded
// (maxExtractFiles for archive extraction, the delete batch cap); an
// uncapped listing let a multi-million-entry directory turn every list
// request into proportional memory, stat and JSON work on the shared node.
// Clients keep working with a prefix: responses carry "truncated" so the
// panel can say so instead of implying the directory ends there.
const maxDirListEntries = 10000
// readDirEntriesBounded returns up to keep UTF-8 names in name-sorted order,
// plus whether any UTF-8 names were dropped because of the cap.
//
// Entries are read in bounded batches and merged, so peak memory stays
// O(keep) instead of growing with the directory - safeReadDirSorted's single
// ReadDir(-1) plus full sort held one slice and one sort of every member.
// The full name scan is unavoidable (a directory fd has no positional read),
// but per-entry stat work and response size are now capped by keep, because
// only the returned entries are stat'd and serialized by the callers.
func readDirEntriesBounded(dir *os.File, keep int) ([]os.DirEntry, bool, error) {
if keep <= 0 {
keep = 1
}
const batchSize = 4096
kept := make([]os.DirEntry, 0, keep)
truncated := false
for {
chunk, err := dir.ReadDir(batchSize)
// adpanel:fs-path-identity - JSON would replace invalid bytes, potentially naming a different file.
chunk = slices.DeleteFunc(chunk, func(entry os.DirEntry) bool { return !utf8.ValidString(entry.Name()) })
if len(chunk) > 0 {
// Batch arrival order is the raw dirent order, not name order.
sort.Slice(chunk, func(i, j int) bool { return chunk[i].Name() < chunk[j].Name() })
if len(kept) == 0 && len(chunk) <= keep {
kept = append(kept, chunk...)
} else {
var overflow bool
kept, overflow = mergeKeepDirEntries(kept, chunk, keep)
if overflow {
truncated = true
}
}
}
if errors.Is(err, io.EOF) {
return kept, truncated, nil
}
if err != nil {
return nil, false, err
}
}
}
// mergeKeepDirEntries merges two name-sorted entry slices and keeps only the
// first keep entries; it reports whether anything beyond keep was dropped,
// i.e. whether the directory holds more members than the cap.
func mergeKeepDirEntries(a, b []os.DirEntry, keep int) ([]os.DirEntry, bool) {
merged := make([]os.DirEntry, 0, keep)
i, j := 0, 0
for len(merged) < keep {
switch {
case i < len(a) && (j >= len(b) || a[i].Name() <= b[j].Name()):
merged = append(merged, a[i])
i++
case j < len(b):
merged = append(merged, b[j])
j++
default:
return merged, false
}
}
return merged, i < len(a) || j < len(b)
}