devbox/internal/daemon/backoff.go
shoemoney 38766fdcd5 feat(M7): SSE reconnect backoff + share-name validation 🛡️
- daemon: exponential backoff (1s→30s) + ±25% jitter on SSE reconnect so a fleet
  that drops together doesn't reconnect in lockstep; a long-lived stream resets it
- hub: ValidateShareName rejects path separators, traversal, control/non-ASCII
  chars, reserved Windows device names (CON/NUL/COM1…), and case-clashes with an
  existing share (Foo vs foo would collide on case-insensitive filesystems)
- tests for both
2026-06-23 01:26:04 -05:00

34 lines
823 B
Go

package daemon
import (
"math/rand"
"time"
)
// Reconnect backoff bounds: start at 1s, double to a 30s ceiling.
const (
backoffBase = 1 * time.Second
backoffMax = 30 * time.Second
)
// nextBackoff returns the next clean (un-jittered) backoff: base, then doubling
// up to backoffMax. Pass the previous clean value; pass <=0 to (re)start at base.
func nextBackoff(prev time.Duration) time.Duration {
switch {
case prev <= 0:
return backoffBase
case prev*2 >= backoffMax:
return backoffMax
default:
return prev * 2
}
}
// jittered spreads a backoff by ±25% so a fleet that all lost the hub at once
// doesn't reconnect in lockstep (thundering herd). Returns 0 unchanged.
func jittered(d time.Duration) time.Duration {
if d <= 0 {
return 0
}
return d + time.Duration(rand.Int63n(int64(d/2))) - d/4
}