package main
import (
"context"
"math/rand/v2"
"time"
)
// bootWarmSpread is the window over which a restart's per-repository
// warms are spread. Every repository warmed at once after a restart and
// filled the store-subprocess gate before the first request arrived
// (#481). A var so tests run unspread.
var bootWarmSpread = 3 * time.Minute
// bootGate holds one repository's boot warms back until a start time
// chosen once, at random, inside the spread. After that time passes it
// costs nothing.
type bootGate struct {
at time.Time
now func() time.Time
nap func(ctx context.Context, d time.Duration) bool
}
// newBootGate picks the start time: now plus jitter(spread), none when
// the spread is zero. jitter, now and nap are injected for tests.
func newBootGate(spread time.Duration, jitter func(time.Duration) time.Duration,
now func() time.Time, nap func(context.Context, time.Duration) bool) *bootGate {
g := &bootGate{at: now(), now: now, nap: nap}
if spread > 0 {
g.at = g.at.Add(jitter(spread))
}
return g
}
func randomJitter(spread time.Duration) time.Duration { return rand.N(spread) }
func sleepCtx(ctx context.Context, d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return true
case <-ctx.Done():
return false
}
}
// productionBootGate is the gate a served repository gets.
func productionBootGate() *bootGate {
return newBootGate(bootWarmSpread, randomJitter, time.Now, sleepCtx)
}
// wait blocks until the gate's start time; false means ctx ended first.
// A nil gate never waits.
func (g *bootGate) wait(ctx context.Context) bool {
if g == nil {
return ctx.Err() == nil
}
if d := g.at.Sub(g.now()); d > 0 {
return g.nap(ctx, d)
}
return ctx.Err() == nil
}