mirror of
https://github.com/hanzoai/insights-go.git
synced 2026-09-30 22:46:12 +00:00
Rename Go package from posthog to insights across all 80+ files. Consumers now import as `insights "github.com/hanzoai/insights-go"` and use insights.Client, insights.Config, insights.Capture, etc. - Rename posthog.go -> insights.go, posthog_test.go -> insights_test.go - Update package declaration from posthog to insights in all .go files - Update SDKName from posthog-go to insights-go - Update DefaultEndpoint from app.posthog.com to insights.hanzo.ai - Update all FieldError/ConfigError type strings - Update User-Agent headers, log prefixes, comments, and docs - Update JSON test fixtures to match new SDK name - Update CLI, examples, extras, and sdk_compliance_adapter - Fix pre-existing go vet warnings (non-constant format strings)
87 lines
1.7 KiB
Go
87 lines
1.7 KiB
Go
package insights
|
|
|
|
import (
|
|
"math"
|
|
"math/rand"
|
|
"time"
|
|
)
|
|
|
|
type Backoff struct {
|
|
base time.Duration
|
|
factor uint8
|
|
jitter float64
|
|
cap time.Duration
|
|
}
|
|
|
|
// Creates a backo instance with the given parameters
|
|
func NewBackoff(base time.Duration, factor uint8, jitter float64, cap time.Duration) *Backoff {
|
|
return &Backoff{base, factor, jitter, cap}
|
|
}
|
|
|
|
// Creates a backoff instance with the following defaults:
|
|
//
|
|
// base: 100 milliseconds
|
|
// factor: 2
|
|
// jitter: 0
|
|
// cap: 10 seconds
|
|
func DefaultBackoff() *Backoff {
|
|
return NewBackoff(time.Millisecond*100, 2, 0, time.Second*10)
|
|
}
|
|
|
|
// Duration returns the backoff interval for the given attempt.
|
|
func (b *Backoff) Duration(attempt int) time.Duration {
|
|
duration := float64(b.base) * math.Pow(float64(b.factor), float64(attempt))
|
|
|
|
if b.jitter != 0 {
|
|
random := rand.Float64()
|
|
deviation := math.Floor(random * b.jitter * duration)
|
|
if (int(math.Floor(random*10)) & 1) == 0 {
|
|
duration = duration - deviation
|
|
} else {
|
|
duration = duration + deviation
|
|
}
|
|
}
|
|
|
|
duration = math.Min(float64(duration), float64(b.cap))
|
|
return time.Duration(duration)
|
|
}
|
|
|
|
// Sleep pauses the current goroutine for the backoff interval for the given attempt.
|
|
func (b *Backoff) Sleep(attempt int) {
|
|
duration := b.Duration(attempt)
|
|
time.Sleep(duration)
|
|
}
|
|
|
|
type Ticker struct {
|
|
done chan struct{}
|
|
C <-chan time.Time
|
|
}
|
|
|
|
func (b *Backoff) NewTicker() *Ticker {
|
|
c := make(chan time.Time, 1)
|
|
ticker := &Ticker{
|
|
done: make(chan struct{}, 1),
|
|
C: c,
|
|
}
|
|
|
|
go func() {
|
|
for i := 0; ; i++ {
|
|
timer := time.NewTimer(b.Duration(i))
|
|
select {
|
|
case t := <-timer.C:
|
|
c <- t
|
|
case <-ticker.done:
|
|
timer.Stop()
|
|
close(c)
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
return ticker
|
|
}
|
|
|
|
func (t *Ticker) Stop() {
|
|
t.done <- struct{}{}
|
|
}
|