package hostlimit import ( "context" "errors" "fmt" "hash/fnv" "os" "sync" "time" ) // fetchRetry is how often a waiting fetch tries the slots again while every // one is held. const fetchRetry = 20 * time.Millisecond // fetchSlot is the slot a key's tries start from: its hash, modulo the slot // count, so concurrent fetches spread over the slots. func fetchSlot(key string, n int) int { h := fnv.New32a() _, _ = h.Write([]byte(key)) return int(h.Sum32() % uint32(n)) } // HoldFetch holds one of the host's FetchSlots fetch slots (files fetch-0 .. // fetch-(N-1) in the pool, so the cap is per host and a slot dies with its // holder) for one chunk transfer; release gives it back. It never refuses for // want of a slot: // // 1. a limiter's first fetch checks the host's configuration under // configuration.lock, publishing it when absent, as a cut admission does: // ErrConfig when another process uses other flags; // 2. it takes a free slot without waiting, trying from key's hash slot; // 3. with every slot held, it waits for its limiter's turn (one fetch per // limiter polls; blockvolume makes one limiter per process) and then // tries every slot each fetchRetry. The waiting is unordered, so other // fetches can take a freed slot first; it ends with ctx's error once ctx // ends, after any file-system step in progress (a configuration check // can add up to its bounded guard wait, guardWait); // 4. a slot taken when ctx has already ended is given back, and ctx's error // returned. // // Every lock try is non-blocking, so a wait that ends leaves no lock request, // descriptor or goroutine behind. func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) { if err := ctx.Err(); err != nil { return nil, err } if err := l.checkFetchConfig(ctx); err != nil { return nil, err } home := fetchSlot(key, l.cfg.FetchSlots) f, err := l.tryFetch(home) if f == nil && err == nil { f, err = l.waitFetch(ctx, home) } if err != nil { return nil, err } if l.testFetchLocked != nil { l.testFetchLocked() } if err := ctx.Err(); err != nil { _ = f.Close() return nil, err } return releaseFetch(f), nil } // checkFetchConfig checks the host's configuration once per limiter. A // configuration lock held past its bound by another admission is waited out // within ctx; a mismatch is ErrConfig. func (l *Limiter) checkFetchConfig(ctx context.Context) error { if l.fetchChecked.Load() { return nil } if err := l.checkPoolDir(); err != nil { return err } for { guard, err := l.configGuard() if err == nil { _ = guard.Close() l.fetchChecked.Store(true) return nil } if !errors.Is(err, ErrSlotsHeld) { return err } if err := sleepCtx(ctx, fetchRetry); err != nil { return err } } } // tryFetch takes a free fetch slot without waiting, trying from home; nil // when every slot is held. func (l *Limiter) tryFetch(home int) (*os.File, error) { n := l.cfg.FetchSlots for k := 0; k < n; k++ { f, err := l.poolFile(fmt.Sprintf("fetch-%d", (home+k)%n)) if err != nil { return nil, err } err = tryLock(f) if err == nil { return f, nil } _ = f.Close() if !errors.Is(err, ErrBusy) { return nil, err } } return nil, nil } // waitFetch waits for a fetch slot while every one is held: it takes its // limiter's turn, so one fetch per limiter polls, and tries every slot each // fetchRetry until one is free or ctx ends. func (l *Limiter) waitFetch(ctx context.Context, home int) (*os.File, error) { select { case l.fetchTurn <- struct{}{}: case <-ctx.Done(): return nil, ctx.Err() } defer func() { <-l.fetchTurn }() for { f, err := l.tryFetch(home) if f != nil || err != nil { return f, err } if err := sleepCtx(ctx, fetchRetry); err != nil { return nil, err } } } // sleepCtx waits d, or until ctx ends (its error). func sleepCtx(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) defer t.Stop() select { case <-ctx.Done(): return ctx.Err() case <-t.C: return nil } } // releaseFetch gives a fetch slot back, once: closing the file releases its // lock. func releaseFetch(f *os.File) func() { var once sync.Once return func() { once.Do(func() { _ = f.Close() }) } }