Files
seaweedfs/seaweed-block/core/frontend/write_budget.go
T

78 lines
2.5 KiB
Go

package frontend
import (
"context"
"errors"
"time"
)
const WriteCommandBudget = 4 * time.Second
// WithWriteBudget preserves an earlier caller deadline, including time spent
// queued before dispatch. A zero arrival denotes a direct backend call.
func WithWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
if arrival.IsZero() {
arrival = time.Now()
}
deadline := arrival.Add(WriteCommandBudget)
if prior, ok := ctx.Deadline(); ok && !deadline.Before(prior) {
return ctx, func() {}
}
return context.WithDeadline(ctx, deadline)
}
// IsWriteDeadline recognizes only an expired caller's pure deadline cause.
// Joined physical/unknown errors retain their terminal classification.
func IsWriteDeadline(ctx context.Context, err error) bool {
return ctx.Err() == context.DeadlineExceeded && deadlineCausesOnly(err)
}
func deadlineCausesOnly(err error) bool {
if err == context.DeadlineExceeded {
return true
}
if err == nil {
return false
}
if joined, ok := err.(interface{ Unwrap() []error }); ok {
causes := joined.Unwrap()
if len(causes) == 0 {
return false
}
for _, cause := range causes {
if !deadlineCausesOnly(cause) {
return false
}
}
return true
}
return deadlineCausesOnly(errors.Unwrap(err))
}
// WithBackendWriteBudget lets a durable backend apply its command-wide WAL
// hold policy before installing a legacy internal deadline. Earlier caller
// deadlines and cancellation are always retained.
func WithBackendWriteBudget(ctx context.Context, arrival time.Time, b Backend) (context.Context, context.CancelFunc) {
if budget, ok := b.(interface {
WriteCommandContext(context.Context, time.Time) (context.Context, context.CancelFunc)
}); ok {
return budget.WriteCommandContext(ctx, arrival)
}
return WithWriteBudget(ctx, arrival)
}
type legacyWriteBudgetKey struct{}
// WithLegacyWriteBudget keeps final-error device bridges outside the retryable
// WAL hold policy until their device timeout and no-retry policy are wired.
func WithLegacyWriteBudget(ctx context.Context, arrival time.Time) (context.Context, context.CancelFunc) {
ctx = context.WithValue(ctx, legacyWriteBudgetKey{}, true)
return WithWriteBudget(ctx, arrival)
}
// UsesLegacyWriteBudget reports an explicit transport choice; backends must not
// replace it with the retryable-protocol WAL hold policy.
func UsesLegacyWriteBudget(ctx context.Context) bool {
legacy, _ := ctx.Value(legacyWriteBudgetKey{}).(bool)
return legacy
}