seaweed-block: filer contract suite and fake modes

MemFiler now passes the filer contract suite the real filer is held to:

- An unconditional delete of a missing entry succeeds and a conditional
  one is ErrPrecondition, as the Filer interface and the filer say (it
  returned ErrNotFound for both).
- A listed directory's one trailing slash is trimmed, as the filer's
  listing does.
- Blobs: chunk payloads by fid (Put, Get, DeleteBlob), returned by
  Blobs() so the filer's own method set is unchanged. Chunks an entry
  drops (delete, an update, a plain create over it) are freed.
- SetFreeDelay/FlushFrees: the free is late, as the filer's deletion
  queue; a read by fid succeeds until it runs.
- ApplyAfterDeadline: a mutation applies while its caller gets the
  context's gRPC status, as a reply lost after the filer applied it.
- SetCap: a byte or object cap refused with the filer's full-store text,
  which matches storage.ErrChunkRemoteFull.

Every mode is off by default, so existing callers see the old behaviour
apart from the delete and listing fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-06 01:03:53 -08:00
1 parent 65f5744e08
commit 945223e882
1 file changed
+282 -24
@@ -2,16 +2,33 @@ package chunkstore
// MemFiler is an in-memory Filer for development and for tests outside this
// package: exclusive create, conditional update and delete on extended
// attributes, and name-ordered listing of one directory's children. It has
// no fault injection; this package's own tests use their own fake.
// attributes, and name-ordered listing of one directory's children.
//
// It is a fake of the layer below and passes the filer contract suite
// (contract_suite_test.go) that a real filer passes. By default it behaves
// as it always has; these modes model what a real filer does and a test can
// switch on:
// - Blobs: chunk payloads stored by fid, so it can serve a LayoutStore's
// blobs. Chunks an entry drops (delete, an update or a plain create over
// it) are freed, as the filer's deletion queue frees them.
// - SetFreeDelay / FlushFrees: the free happens later, not at once (the
// filer polls its deletion queue); a read by fid in between succeeds.
// - ApplyAfterDeadline: a mutation is applied but its caller only sees its
// deadline pass (a reply lost after the filer applied the request).
// - SetCap: a byte or object cap; a put past it is refused with the
// filer's full-store text, as storage.ErrChunkRemoteFull.
import (
"context"
"errors"
"fmt"
"path"
"sort"
"strings"
"sync"
"time"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
@@ -20,16 +37,166 @@ import (
type MemFiler struct {
mu sync.Mutex
e map[string]*filerpb.Entry
// blobs holds chunk payloads by fid; used is their total size.
blobs map[string][]byte
used int64
needle uint64
// freeDelay: 0 frees a dropped chunk at once, > 0 after that long,
// < 0 only on FlushFrees. frees is the queue of dropped chunks.
freeDelay time.Duration
frees []memFree
// lateReplies: how many next mutations apply but answer only the
// caller's deadline.
lateReplies int
// capBytes, capObjects: the store's capacity (0: none).
capBytes int64
capObjects int
}
type memFree struct {
fid string
due time.Time // zero: only on FlushFrees
}
// NewMemFiler returns an empty MemFiler.
func NewMemFiler() *MemFiler { return &MemFiler{e: map[string]*filerpb.Entry{}} }
func NewMemFiler() *MemFiler {
return &MemFiler{e: map[string]*filerpb.Entry{}, blobs: map[string][]byte{}}
}
var _ Filer = (*MemFiler)(nil)
var (
_ Filer = (*MemFiler)(nil)
_ ChunkConditionFiler = (*MemFiler)(nil)
_ Blobs = memBlobs{}
)
// memFullText is the text a filer answers an assign with when the store has
// no writable volume and no free slot to grow one (SeaweedFS master,
// weed/server/master_grpc_server_assign.go, relayed by the filer).
const memFullText = "assign volume: No writable volumes and no free volumes left for {\"replication\":\"000\"}"
// SetFreeDelay sets when a chunk an entry drops is freed: 0 at once (the
// default), d > 0 after d (checked on every call), d < 0 only on FlushFrees.
func (m *MemFiler) SetFreeDelay(d time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
m.freeDelay = d
}
// FlushFrees frees every queued chunk now, as the filer's deletion loop does
// when it runs.
func (m *MemFiler) FlushFrees() {
m.mu.Lock()
defer m.mu.Unlock()
for _, f := range m.frees {
m.dropBlob(f.fid)
}
m.frees = nil
}
// ApplyAfterDeadline arms the next n mutations (create, update, delete): each
// is applied, then its reply is held until the caller's context ends and the
// caller gets the context's gRPC status (DeadlineExceeded), as a filer whose
// reply arrives after the caller's deadline. A context with no deadline gets
// DeadlineExceeded at once.
func (m *MemFiler) ApplyAfterDeadline(n int) {
m.mu.Lock()
defer m.mu.Unlock()
m.lateReplies = n
}
// SetCap sets the store's capacity in bytes and in objects (0: no limit). A
// put that would pass it is refused with the filer's full-store answer,
// which matches storage.ErrChunkRemoteFull. A freed chunk gives its room
// back only when it is freed.
func (m *MemFiler) SetCap(maxBytes int64, maxObjects int) {
m.mu.Lock()
defer m.mu.Unlock()
m.capBytes, m.capObjects = maxBytes, maxObjects
}
// Blobs returns the chunk store that goes with this filer: its fids are the
// ones the filer frees when an entry drops them.
func (m *MemFiler) Blobs() Blobs { return memBlobs{m} }
// reapLocked frees the queued chunks whose delay has passed.
func (m *MemFiler) reapLocked() {
if len(m.frees) == 0 {
return
}
now := time.Now()
kept := m.frees[:0]
for _, f := range m.frees {
if !f.due.IsZero() && !now.Before(f.due) {
m.dropBlob(f.fid)
continue
}
kept = append(kept, f)
}
m.frees = kept
}
func (m *MemFiler) dropBlob(fid string) {
if b, ok := m.blobs[fid]; ok {
m.used -= int64(len(b))
delete(m.blobs, fid)
}
}
// dropChunksLocked queues for freeing the chunks of old that next does not
// list (next nil: all of them), as the filer's garbage of an update.
func (m *MemFiler) dropChunksLocked(old, next *filerpb.Entry) {
if old == nil {
return
}
keep := map[string]int{}
for _, f := range entryFids(next) {
keep[f]++
}
for _, f := range entryFids(old) {
if keep[f] > 0 {
keep[f]--
continue
}
switch {
case m.freeDelay == 0:
m.dropBlob(f)
case m.freeDelay < 0:
m.frees = append(m.frees, memFree{fid: f})
default:
m.frees = append(m.frees, memFree{fid: f, due: time.Now().Add(m.freeDelay)})
}
}
}
// beginLocked starts a mutation: it reaps due frees and reports whether this
// mutation's reply is to be lost.
func (m *MemFiler) beginLocked() (late bool) {
m.reapLocked()
if m.lateReplies > 0 {
m.lateReplies--
return true
}
return false
}
// lateReply waits out the caller's context and returns what a gRPC client
// returns then, wrapped as the SWFS client wraps an unclassified error.
func lateReply(ctx context.Context, op, dir, name string) error {
if _, ok := ctx.Deadline(); ok {
<-ctx.Done()
}
cause := ctx.Err()
if cause == nil {
cause = context.DeadlineExceeded
}
return fmt.Errorf("chunkstore: %s %s/%s: %w", op, dir, name, status.FromContextError(cause).Err())
}
func (m *MemFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
e, ok := m.e[path.Join(dir, name)]
if !ok {
return nil, ErrNotFound
@@ -37,52 +204,80 @@ func (m *MemFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.En
return proto.Clone(e).(*filerpb.Entry), nil
}
func (m *MemFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
func (m *MemFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.createLocked(dir, e, oExcl)
m.mu.Unlock()
if late {
return lateReply(ctx, "create", dir, e.GetName())
}
return err
}
func (m *MemFiler) createLocked(dir string, e *filerpb.Entry, oExcl bool) error {
p := path.Join(dir, e.GetName())
if _, ok := m.e[p]; ok && oExcl {
old, ok := m.e[p]
if ok && oExcl {
return ErrExists
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
m.dropChunksLocked(old, e)
return nil
}
func (m *MemFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
func (m *MemFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
m.mu.Lock()
defer m.mu.Unlock()
p := path.Join(dir, e.GetName())
cur, ok := m.e[p]
if !ok {
return ErrNotFound
late := m.beginLocked()
err := m.updateLocked(dir, e, expected, nil)
m.mu.Unlock()
if late {
return lateReply(ctx, "update", dir, e.GetName())
}
if !extendedMatch(cur, expected) {
return ErrPrecondition
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
return nil
return err
}
// UpdateEntryIfChunks is UpdateEntry that also requires the stored chunk
// fids to equal fids as a multiset, as the filer's IF_CHUNKS_EQUAL does.
func (m *MemFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
func (m *MemFiler) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
if fids == nil {
fids = []string{}
}
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.updateLocked(dir, e, expected, fids)
m.mu.Unlock()
if late {
return lateReply(ctx, "update", dir, e.GetName())
}
return err
}
// updateLocked applies e if expected holds and, when fids is not nil, the
// stored chunk fids equal fids.
func (m *MemFiler) updateLocked(dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
p := path.Join(dir, e.GetName())
cur, ok := m.e[p]
if !ok {
return ErrNotFound
}
if !extendedMatch(cur, expected) || !fidsEqual(entryFids(cur), fids) {
if !extendedMatch(cur, expected) || (fids != nil && !fidsEqual(entryFids(cur), fids)) {
return ErrPrecondition
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
m.dropChunksLocked(cur, e)
return nil
}
func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
// The filer trims one trailing slash from the listed directory
// (weed/filer/filer_search.go StreamListDirectoryEntries).
if len(dir) > 1 {
dir = strings.TrimSuffix(dir, "/")
}
var names []string
for p := range m.e {
if name := path.Base(p); path.Dir(p) == dir && strings.HasPrefix(name, prefix) && name > startAfter {
@@ -100,18 +295,34 @@ func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string
return out, nil
}
func (m *MemFiler) DeleteEntry(_ context.Context, dir, name string, expected map[string][]byte) error {
// DeleteEntry follows Filer: an unconditional delete of a missing entry
// succeeds; a conditional one (expected not empty) is ErrPrecondition, as
// the filer cannot read the entry it is asked to check.
func (m *MemFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
m.mu.Lock()
defer m.mu.Unlock()
late := m.beginLocked()
err := m.deleteLocked(dir, name, expected)
m.mu.Unlock()
if late {
return lateReply(ctx, "delete", dir, name)
}
return err
}
func (m *MemFiler) deleteLocked(dir, name string, expected map[string][]byte) error {
p := path.Join(dir, name)
cur, ok := m.e[p]
if !ok {
return ErrNotFound
if len(expected) > 0 {
return ErrPrecondition
}
return nil
}
if !extendedMatch(cur, expected) {
return ErrPrecondition
}
delete(m.e, p)
m.dropChunksLocked(cur, nil)
return nil
}
@@ -123,3 +334,50 @@ func extendedMatch(e *filerpb.Entry, expected map[string][]byte) bool {
}
return true
}
// memBlobs is MemFiler's chunk store (Blobs plus DeleteBlob, as SWFS).
type memBlobs struct{ m *MemFiler }
// Put stores data under a new fid, or refuses past the cap as a full
// SeaweedFS store answers the assign.
func (b memBlobs) Put(_ context.Context, data []byte) (string, error) {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
if (m.capObjects > 0 && len(m.blobs)+1 > m.capObjects) || (m.capBytes > 0 && m.used+int64(len(data)) > m.capBytes) {
return "", assignErr("chunkstore: assign", errors.New(memFullText))
}
if m.blobs == nil {
m.blobs = map[string][]byte{}
}
m.needle++
fid := fmt.Sprintf("1,%x00000000", m.needle)
m.blobs[fid] = append([]byte(nil), data...)
m.used += int64(len(data))
return fid, nil
}
// Get returns the payload; a freed or unknown fid is ErrBlobNotFound, as a
// volume server's 404.
func (b memBlobs) Get(_ context.Context, fid string) ([]byte, error) {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.reapLocked()
d, ok := m.blobs[fid]
if !ok {
return nil, fmt.Errorf("chunkstore: read %s: %w", fid, &blobNotFoundError{&blobStatusError{code: 404, host: "memfiler"}})
}
return append([]byte(nil), d...), nil
}
// DeleteBlob removes a needle at once (a direct needle delete, not the
// filer's queue); an absent one is not an error.
func (b memBlobs) DeleteBlob(_ context.Context, fid string) error {
m := b.m
m.mu.Lock()
defer m.mu.Unlock()
m.dropBlob(fid)
return nil
}