chunkstore, storage: batch assign for upload rounds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-20 16:57:01 -08:00
1 parent 6a89b14a85
commit c32467824d
8 files changed
+527 -41

No files matched your search

@@ -90,6 +90,8 @@ type ChunkRemote struct {
mu sync.Mutex
fids map[string]string // key -> fid; key entries are write-once
assigns assignCounters // reservations made by upload rounds
}
// NewChunkRemote returns the remote for the volume rooted at root, an
@@ -150,26 +152,42 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error {
}
func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error {
if err := storage.ValidChunkKey(key); err != nil {
return fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
name, err := keyName(key)
name, err := r.ownKeyName(key)
if err != nil {
return err
}
r.mu.Lock()
_, known := r.fids[key]
r.mu.Unlock()
if known {
if r.knownKey(key) {
return storage.ErrChunkKeyExists
}
fid, err := r.b.Put(ctx, data)
if err != nil {
return err
}
return r.bindKey(ctx, key, name, fid, data, object)
}
// ownKeyName checks that key is one of this volume's own keys and returns
// its binding's entry name.
func (r *ChunkRemote) ownKeyName(key string) (string, error) {
if err := storage.ValidChunkKey(key); err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
return keyName(key)
}
// knownKey reports whether key is already bound (as far as this remote saw).
func (r *ChunkRemote) knownKey(key string) bool {
r.mu.Lock()
defer r.mu.Unlock()
_, known := r.fids[key]
return known
}
// bindKey binds key to the stored needle fid with an exclusive create.
func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error {
now := time.Now().Unix()
e := &filerpb.Entry{
Name: name,
@@ -0,0 +1,260 @@
package chunkstore
// Upload rounds over batch assign. The n objects of one round are split into
// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G),
// and each group takes one reservation for all its slots, made when its
// first object is uploaded. So a round costs G assigns instead of n, its
// objects still spread over up to G volumes, and a round with no upload
// makes none.
//
// A slot is frozen once reserved: retrying object i sends the same fid. A
// group's ranges change only for slots no upload has stored yet:
// - a short grant is topped up by a reservation for the remaining slots;
// - a refusal before append (read-only or full volume) moves this and the
// later slots of the group to a fresh range, at most roundMaxReplacements
// times per group;
// - a range whose token is past its stated expiry is never sent to; its
// unsent slots get a fresh range under the same bound.
// A rejected token (401) is terminal. Extra reservations are counted apart
// from the initial ones (AssignCounts).
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const (
roundGroupSize = 64
roundMaxGroups = 8
roundMaxReplacements = 3
)
// AssignCounts counts the reservations this remote's upload rounds made.
type AssignCounts struct {
Initial int64 // the first reservation of each group
Short int64 // top-ups after a short grant
Capacity int64 // replacements after a refusal before append
Expired int64 // replacements of ranges whose token expired before use
}
// Extra is every reservation beyond the initial ones.
func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired }
type assignCounters struct{ initial, short, capacity, expired atomic.Int64 }
// AssignCounts reports the reservations made so far.
func (r *ChunkRemote) AssignCounts() AssignCounts {
return AssignCounts{
Initial: r.assigns.initial.Load(),
Short: r.assigns.short.Load(),
Capacity: r.assigns.capacity.Load(),
Expired: r.assigns.expired.Load(),
}
}
var _ storage.ChunkPutRounds = (*ChunkRemote)(nil)
// BeginPutRound starts a round of n objects of objSize bytes. Without batch
// support in the blob store, the round is one Put per object.
func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound {
rb, ok := r.b.(rangeBlobs)
if !ok || n <= 0 {
return plainRound{r}
}
g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize)
rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)}
for j := range rd.groups {
// Group j holds objects j, j+g, j+2g, ...
rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g}
}
return rd
}
type plainRound struct{ r *ChunkRemote }
func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error {
return p.r.Put(ctx, key, data)
}
type putRound struct {
r *ChunkRemote
rb rangeBlobs
n int
size uint64
groups []*roundGroup
}
// roundGroup's ranges cover its slots [0, end) as consecutive spans.
type roundGroup struct {
slots int
mu sync.Mutex
spans []roundSpan
reserving chan struct{} // non-nil while a reservation is in flight
replacements int
next reserveReason // what the next reservation is for
}
type reserveReason int
const (
reserveInitial reserveReason = iota
reserveShort
reserveCapacity
reserveExpired
)
type roundSpan struct {
from int
rng blobRange
}
func (g *roundGroup) end() int {
if len(g.spans) == 0 {
return 0
}
last := g.spans[len(g.spans)-1]
return last.from + last.rng.count
}
// lookup returns the range and offset of slot s, if reserved. g.mu held.
func (g *roundGroup) lookup(s int) (blobRange, int, bool) {
for _, sp := range g.spans {
if s >= sp.from && s < sp.from+sp.rng.count {
return sp.rng, s - sp.from, true
}
}
return blobRange{}, 0, false
}
// retire drops slots s and later of the span using rng, so they take a fresh
// range; it reports false once the group's replacements are used up. A span
// already replaced (by a concurrent upload) is left as is.
func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
g.mu.Lock()
defer g.mu.Unlock()
for k, sp := range g.spans {
if sp.rng.base != rng.base {
continue
}
if g.replacements >= roundMaxReplacements {
return false
}
g.replacements++
g.next = why
if s <= sp.from {
g.spans = g.spans[:k]
} else {
g.spans[k].rng.count = s - sp.from
g.spans = g.spans[:k+1]
}
return true
}
return true
}
// slot returns slot s's range and offset, reserving the group's remaining
// slots when s is not covered yet. Concurrent callers share one reservation;
// waiting follows ctx, and a reply after ctx ends is not used.
func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) {
for {
g.mu.Lock()
if rng, off, ok := g.lookup(s); ok {
g.mu.Unlock()
return rng, off, nil
}
if wait := g.reserving; wait != nil {
g.mu.Unlock()
select {
case <-wait:
continue
case <-ctx.Done():
return blobRange{}, 0, ctx.Err()
}
}
from := g.end()
why := g.next
done := make(chan struct{})
g.reserving = done
g.mu.Unlock()
rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size)
if err == nil {
err = ctx.Err()
}
g.mu.Lock()
g.reserving = nil
close(done)
if err == nil {
g.spans = append(g.spans, roundSpan{from: from, rng: rng})
g.next = reserveShort // only a short grant leaves slots uncovered now
switch why {
case reserveInitial:
rd.r.assigns.initial.Add(1)
case reserveShort:
rd.r.assigns.short.Add(1)
case reserveCapacity:
rd.r.assigns.capacity.Add(1)
case reserveExpired:
rd.r.assigns.expired.Add(1)
}
}
g.mu.Unlock()
if err != nil {
return blobRange{}, 0, err
}
}
}
// Put stores object i under key in its group's range and binds key to it.
func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error {
if i < 0 || i >= rd.n {
return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n)
}
name, err := rd.r.ownKeyName(key)
if err != nil {
return err
}
if rd.r.knownKey(key) {
return storage.ErrChunkKeyExists
}
g := rd.groups[i%len(rd.groups)]
s := i / len(rd.groups)
for {
if err := ctx.Err(); err != nil {
return err
}
rng, off, err := rd.slot(ctx, g, s)
if err != nil {
return err
}
if dl, ok := rng.sendDeadline(); ok && !time.Now().Before(dl) {
// Never sent: the unsent slots take a fresh range.
if !g.retire(rng, s, reserveExpired) {
return fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i)
}
continue
}
fid, err := rng.fid(off)
if err != nil {
return err
}
err = rd.rb.putRange(ctx, rng, off, data)
if errors.Is(err, errRangeRefused) {
if !g.retire(rng, s, reserveCapacity) {
return fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err)
}
continue
}
if err != nil {
return err
}
return rd.r.bindKey(ctx, key, name, fid, data, "")
}
}
+1 -27
View File
@@ -1,9 +1,7 @@
package chunkstore
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -219,33 +217,9 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
}
u := "http://" + ar.Location.Url + "/" + ar.FileId
if ar.GetFsync() {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/octet-stream")
if ar.GetAuth() != "" {
req.Header.Set("Authorization", "BEARER "+ar.Auth)
}
resp, err := c.http.Do(req)
if err != nil {
return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body)))
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error)
}
return ar.FileId, nil
}
@@ -0,0 +1,196 @@
package chunkstore
// Batch assign: one AssignVolume(Count = n) reserves n consecutive needle ids
// on one volume. They are addressed in SeaweedFS's native form: offset 0 is
// the base fid, offset i is "<base>_<i>". The volume server adds i to the
// needle key and checks the assign's token against the base fid, so every
// offset carries the base's token and shares its cookie. Never write such an
// id as a different fid (key+i): that one has no token.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
const (
// maxRangeCount bounds one reservation.
maxRangeCount = 1 << 16
// jwtSendSkew: an upload is not sent within this much of its token's
// stated expiry.
jwtSendSkew = 2 * time.Second
)
var (
// errRangeRefused: the volume refused the write before appending it
// (read-only or full). Nothing was stored; a fresh range may take it.
errRangeRefused = errors.New("chunkstore: volume refused the write before append")
// errRangeAuth: the volume rejected the upload's token. Terminal.
errRangeAuth = errors.New("chunkstore: volume rejected the upload token")
)
// blobRange is one batch reservation: count ids starting at base, on the
// volume server at url, with the assign's token and fsync policy.
type blobRange struct {
base string
count int
url string
auth string
fsync bool
}
// fid returns the native id of offset i.
func (r blobRange) fid(i int) (string, error) {
if i < 0 || i >= r.count {
return "", fmt.Errorf("chunkstore: offset %d outside a range of %d ids", i, r.count)
}
if i == 0 {
return r.base, nil
}
return r.base + "_" + strconv.Itoa(i), nil
}
// sendDeadline is the last time an upload with this range's token may be
// sent: the token's stated expiry less jwtSendSkew. The claim is read, not
// verified: it only ever stops an upload, it never authorizes one. A token
// without a readable expiry gives no deadline.
func (r blobRange) sendDeadline() (time.Time, bool) {
parts := strings.Split(r.auth, ".")
if len(parts) != 3 {
return time.Time{}, false
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}, false
}
var claims struct {
Exp *int64 `json:"exp"`
}
if json.Unmarshal(payload, &claims) != nil || claims.Exp == nil {
return time.Time{}, false
}
return time.Unix(*claims.Exp, 0).Add(-jwtSendSkew), true
}
// rangeBlobs is the optional batch capability of a blob store.
type rangeBlobs interface {
reserve(ctx context.Context, n int, objSize uint64) (blobRange, error)
putRange(ctx context.Context, r blobRange, i int, data []byte) error
}
var _ rangeBlobs = (*SWFS)(nil)
// validBaseFid checks "<vid>,<key><cookie>": a decimal volume id, then hex
// with at least a cookie's 8 digits after a key, and no offset suffix.
func validBaseFid(fid string) error {
vid, kc, ok := strings.Cut(fid, ",")
if !ok || vid == "" {
return fmt.Errorf("chunkstore: assign fid %q has no volume id", fid)
}
if _, err := strconv.ParseUint(vid, 10, 32); err != nil {
return fmt.Errorf("chunkstore: assign fid %q: volume id: %v", fid, err)
}
if len(kc) <= 8 {
return fmt.Errorf("chunkstore: assign fid %q: no key before the cookie", fid)
}
for _, c := range kc {
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return fmt.Errorf("chunkstore: assign fid %q: not a plain hex key and cookie", fid)
}
}
return nil
}
// reserve asks for n ids of objSize bytes each (the master counts
// ExpectedDataSize per id). A shorter valid grant is returned as is; the
// caller reserves the rest.
func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) {
if n <= 0 || n > maxRangeCount {
return blobRange{}, fmt.Errorf("chunkstore: reserve %d ids: want 1..%d", n, maxRangeCount)
}
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
Count: int32(n),
Collection: c.cfg.Collection,
Replication: c.cfg.Replication,
Path: c.cfg.AssignPath,
ExpectedDataSize: objSize,
})
if err != nil {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %w", n, err)
}
if ar.GetError() != "" {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError())
}
if ar.GetLocation().GetUrl() == "" {
return blobRange{}, fmt.Errorf("chunkstore: assign %d returned no location", n)
}
if err := validBaseFid(ar.GetFileId()); err != nil {
return blobRange{}, err
}
count := int(ar.GetCount())
if count <= 0 || count > n {
return blobRange{}, fmt.Errorf("chunkstore: assign %d returned %d ids", n, count)
}
return blobRange{base: ar.FileId, count: count, url: ar.Location.Url, auth: ar.GetAuth(), fsync: ar.GetFsync()}, nil
}
// putRange uploads data as offset i of r. A refusal before append is
// errRangeRefused, a rejected token errRangeAuth; any other failure is
// returned as is (the caller retries the same offset).
func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
fid, err := r.fid(i)
if err != nil {
return err
}
return c.upload(ctx, r.url, fid, r.auth, r.fsync, data)
}
// upload POSTs data raw to fid on the volume server at host.
func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, data []byte) error {
u := "http://" + host + "/" + fid
if fsync {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/octet-stream")
if auth != "" {
req.Header.Set("Authorization", "BEARER "+auth)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("chunkstore: upload %s: %w", fid, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body)))
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errors.Join(errRangeAuth, err)
case resp.StatusCode == http.StatusConflict,
resp.Header.Get("X-Seaweed-Write-Outcome") == "refused-before-append":
return errors.Join(errRangeRefused, err)
}
return err
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return fmt.Errorf("chunkstore: upload %s: %s", fid, ur.Error)
}
return nil
}
@@ -51,6 +51,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
var once sync.Once
var intent string
var intentErr error
put := l.beginPutRound(len(batch))
err := l.uploadBatch(ctx, len(batch), func(ctx context.Context, i int) error {
c, err := read(ctx, batch[i])
if err != nil {
@@ -69,7 +70,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, intentErr)
}
c.intent = intent
if err := l.putCaptured(ctx, c.key, c.data); err != nil {
if err := l.putCapturedWith(ctx, c.key, c.data, func(ctx context.Context) error { return put(ctx, i, c.key, c.data) }); err != nil {
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
}
+2 -1
View File
@@ -959,9 +959,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
intents = append(intents, id)
}
payloadStart := time.Now()
put := l.beginPutRound(len(uploads))
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.putCaptured(ctx, u.key, u.c.data)
return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) })
}); err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
@@ -0,0 +1,30 @@
package storage
import "context"
// ChunkPutRounds is an optional ChunkRemote capability: the objects of one
// upload round share remote reservations (batch assign) instead of taking
// one each. The round belongs to the cut or staging round that begins it and
// ends with it; it starts no goroutine of its own, so joining the round's
// workers joins every call it made.
type ChunkPutRounds interface {
BeginPutRound(n, objSize int) ChunkPutRound
}
// ChunkPutRound stores object i (0 <= i < n) of its round under key, with
// Put's rules: a bound key is never rebound (ErrChunkKeyExists). A failed Put
// may be retried with the same i and bytes.
type ChunkPutRound interface {
Put(ctx context.Context, i int, key string, data []byte) error
}
// beginPutRound returns the put for a round of n objects: the remote's
// round when it has one, otherwise one Put per object.
func (l *chunkLayerImpl) beginPutRound(n int) func(ctx context.Context, i int, key string, data []byte) error {
if rounds, ok := l.remote.(ChunkPutRounds); ok && n > 0 {
return rounds.BeginPutRound(n, int(uint64(l.blockSize)*l.chunkBlocks)).Put
}
return func(ctx context.Context, _ int, key string, data []byte) error {
return l.remote.Put(ctx, key, data)
}
}
+7 -1
View File
@@ -14,6 +14,12 @@ import (
// Keep the point and frozen buffer through transient failures until the cut
// context ends (deadline, Close or window abort), never a fresh point.
func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error {
return l.putCapturedWith(ctx, key, data, func(ctx context.Context) error { return l.remote.Put(ctx, key, data) })
}
// putCapturedWith is putCaptured over put, one object's slot in an upload
// round: every retry sends through the same put.
func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data []byte, put func(context.Context) error) error {
// The per-object retry deadline also bounds a contextless cut. It retains
// the same point and buffer through a remote outage, never re-reads live data.
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -24,7 +30,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt
if err := ctx.Err(); err != nil {
return errors.Join(lastErr, err)
}
err := l.remote.Put(ctx, key, data)
err := put(ctx)
if err == nil {
return nil
}