diff --git a/internal/beep/beep.go b/internal/beep/beep.go index e0e6252..adf9fc5 100644 --- a/internal/beep/beep.go +++ b/internal/beep/beep.go @@ -2,6 +2,7 @@ package beep import ( "fmt" + "io" "os" "sync" "time" @@ -12,54 +13,102 @@ const ( DefaultDebounceInterval = 500 * time.Millisecond ) -// Beeper manages beep sound playback with debouncing +// Beeper manages beep sound playback with debouncing. The zero value is +// ready to use (enabled, writing to os.Stdout, no debounce); use NewBeeper +// for the default debounce interval. Call Close to stop the worker goroutine. type Beeper struct { - enabled bool + disabled bool // inverted so that the zero value is enabled debounceTime time.Duration lastBeepTime time.Time mu sync.Mutex + out io.Writer + queue chan struct{} + stop chan struct{} + done chan struct{} + initOnce sync.Once + closeOnce sync.Once } // NewBeeper creates a new Beeper instance func NewBeeper() *Beeper { return &Beeper{ - enabled: true, // Default is ON debounceTime: DefaultDebounceInterval, + out: os.Stdout, } } -// Beep plays a beep sound if enabled and debounce time has passed -// This function is non-blocking and thread-safe -func (b *Beeper) Beep() { - go func() { +// init lazily prepares the queue and starts the worker, so that a zero-value +// Beeper works too. +func (b *Beeper) init() { + b.initOnce.Do(func() { b.mu.Lock() - defer b.mu.Unlock() + if b.out == nil { + b.out = os.Stdout + } + b.mu.Unlock() + b.queue = make(chan struct{}, 1) + b.stop = make(chan struct{}) + b.done = make(chan struct{}) + go b.worker() + }) +} - // Skip if disabled - if !b.enabled { +// Beep requests a beep sound. It never blocks: requests are handed to a +// single worker through a one-slot queue and extra requests are dropped. +func (b *Beeper) Beep() { + b.init() + select { + case b.queue <- struct{}{}: + default: // a beep is already pending + } +} + +// closeWait bounds how long Close waits for the worker to exit. +const closeWait = 200 * time.Millisecond + +// Close stops the worker goroutine and waits (up to closeWait) for it to +// exit. It is idempotent; Beep after Close is a harmless no-op. +func (b *Beeper) Close() { + b.init() + b.closeOnce.Do(func() { close(b.stop) }) + // Wait briefly for the worker; if it is stuck writing to a blocked + // terminal, don't hang the caller (e.g. app shutdown) on it. + select { + case <-b.done: + case <-time.After(closeWait): + } +} + +func (b *Beeper) worker() { + defer close(b.done) + for { + select { + case <-b.stop: return + case <-b.queue: } - - // Check debounce time + b.mu.Lock() now := time.Now() - if now.Sub(b.lastBeepTime) < b.debounceTime { - return // Skip if within debounce period + play := !b.disabled && now.Sub(b.lastBeepTime) >= b.debounceTime + if play { + b.lastBeepTime = now } - - // Play beep sound - if err := b.playBeep(); err != nil { + out := b.out + b.mu.Unlock() + if !play { + continue + } + // Write outside the lock so a blocked stdout cannot freeze Toggle + if err := playBeep(out); err != nil { // Log error but don't propagate - // This ensures beep failures don't affect main processing fmt.Fprintf(os.Stderr, "beep: failed to play sound: %v\n", err) } - - b.lastBeepTime = now - }() + } } // playBeep outputs the system bell character -func (b *Beeper) playBeep() error { - _, err := fmt.Print("\a") +func playBeep(out io.Writer) error { + _, err := fmt.Fprint(out, "\a") return err } @@ -67,15 +116,15 @@ func (b *Beeper) playBeep() error { func (b *Beeper) Toggle() bool { b.mu.Lock() defer b.mu.Unlock() - b.enabled = !b.enabled - return b.enabled + b.disabled = !b.disabled + return !b.disabled } // IsEnabled returns current beep sound state func (b *Beeper) IsEnabled() bool { b.mu.Lock() defer b.mu.Unlock() - return b.enabled + return !b.disabled } // GetLastBeepTime returns the last beep time (for testing) diff --git a/internal/beep/beep_test.go b/internal/beep/beep_test.go index 8e5e8ae..710e7f8 100644 --- a/internal/beep/beep_test.go +++ b/internal/beep/beep_test.go @@ -1,12 +1,16 @@ package beep import ( + "bytes" + "runtime" + "sync" "testing" "time" ) func TestNewBeeper(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() if !beeper.IsEnabled() { t.Error("Expected beeper to be enabled by default") @@ -19,6 +23,7 @@ func TestNewBeeper(t *testing.T) { func TestToggle(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() initialState := beeper.IsEnabled() beeper.Toggle() @@ -36,6 +41,7 @@ func TestToggle(t *testing.T) { func TestDebounce(t *testing.T) { debounceInterval := 100 * time.Millisecond beeper := NewBeeper() + defer beeper.Close() beeper.debounceTime = debounceInterval // First beep should work @@ -67,6 +73,7 @@ func TestDebounce(t *testing.T) { func TestBeepWhenDisabled(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() beeper.Toggle() // disable // Beep should not update lastBeepTime when disabled @@ -80,6 +87,7 @@ func TestBeepWhenDisabled(t *testing.T) { func TestConcurrentAccess(t *testing.T) { beeper := NewBeeper() + defer beeper.Close() done := make(chan bool) // Test concurrent beep calls @@ -106,3 +114,95 @@ func TestConcurrentAccess(t *testing.T) { // If we get here without deadlock or panic, the test passes } + +type blockingWriter struct{ release chan struct{} } + +func (w *blockingWriter) Write(p []byte) (int, error) { + <-w.release + return len(p), nil +} + +func TestBeepDoesNotBlockWhenOutputBlocked(t *testing.T) { + w := &blockingWriter{release: make(chan struct{})} + b := NewBeeper() + // Close waits for the worker, so release the writer first (LIFO defers) + defer b.Close() + defer close(w.release) + b.out = w + b.debounceTime = 0 + before := runtime.NumGoroutine() + for i := 0; i < 200; i++ { + b.Beep() + } + time.Sleep(50 * time.Millisecond) + done := make(chan struct{}) + go func() { b.Toggle(); b.IsEnabled(); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Toggle/IsEnabled blocked by a stuck stdout") + } + if n := runtime.NumGoroutine() - before; n > 5 { + t.Errorf("goroutines piled up: +%d", n) + } +} + +func TestCloseIdempotentAndStopsWorker(t *testing.T) { + before := runtime.NumGoroutine() + b := NewBeeper() + b.Beep() + b.Close() + b.Close() // second call must not panic or block + b.Beep() // no-op after Close + time.Sleep(20 * time.Millisecond) + if n := runtime.NumGoroutine(); n > before { + t.Errorf("worker goroutine leaked: %d > %d", n, before) + } +} + +func TestCloseWithoutBeep(t *testing.T) { + b := NewBeeper() + b.Close() + b.Close() +} + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuf) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +func TestZeroValueBeeperWorks(t *testing.T) { + var b Beeper + defer b.Close() + if !b.IsEnabled() { + t.Error("zero value should be enabled") + } + b.Beep() // must not panic with nil out; writes to os.Stdout + time.Sleep(20 * time.Millisecond) + if b.GetLastBeepTime().IsZero() { + t.Error("zero-value Beeper dropped the beep") + } +} + +func TestZeroValueBeeperWritesToOut(t *testing.T) { + buf := &syncBuf{} + b := &Beeper{out: buf} + defer b.Close() + b.Beep() + time.Sleep(20 * time.Millisecond) + if buf.String() != "\a" { + t.Errorf("out = %q, want bell", buf.String()) + } +} diff --git a/internal/beep/notifier.go b/internal/beep/notifier.go index c466e9c..3ef223b 100644 --- a/internal/beep/notifier.go +++ b/internal/beep/notifier.go @@ -34,6 +34,11 @@ func (n *Notifier) OnFailure(name string) { n.beep() } +// Close stops the background beep worker. It is idempotent. +func (n *Notifier) Close() { + n.beeper.Close() +} + // Toggle switches the global beep on/off and returns the new state func (n *Notifier) Toggle() bool { return n.beeper.Toggle() diff --git a/internal/beep/notifier_test.go b/internal/beep/notifier_test.go index 5a402d6..bf41268 100644 --- a/internal/beep/notifier_test.go +++ b/internal/beep/notifier_test.go @@ -7,8 +7,9 @@ import ( ) // countingNotifier returns a Notifier whose bell only increments a counter -func countingNotifier(silenced ...string) (*Notifier, *atomic.Int32) { +func countingNotifier(t testing.TB, silenced ...string) (*Notifier, *atomic.Int32) { n := NewNotifier() + t.Cleanup(n.Close) for _, name := range silenced { n.ToggleSilence(name) } @@ -18,7 +19,7 @@ func countingNotifier(silenced ...string) (*Notifier, *atomic.Int32) { } func TestNotifierSilence(t *testing.T) { - n, _ := countingNotifier("quiet") + n, _ := countingNotifier(t, "quiet") if !n.IsSilenced("quiet") || n.IsSilenced("loud") { t.Error("initial silenced state wrong") } @@ -31,7 +32,7 @@ func TestNotifierSilence(t *testing.T) { } func TestNotifierOnFailureSkipsSilenced(t *testing.T) { - n, rang := countingNotifier("quiet") + n, rang := countingNotifier(t, "quiet") n.OnFailure("quiet") if got := rang.Load(); got != 0 { t.Errorf("silenced target rang %d times, want 0", got) @@ -43,7 +44,7 @@ func TestNotifierOnFailureSkipsSilenced(t *testing.T) { } func TestNotifierToggle(t *testing.T) { - n, _ := countingNotifier() + n, _ := countingNotifier(t) if !n.Enabled() { t.Fatal("beep should be enabled by default") } @@ -56,7 +57,7 @@ func TestNotifierToggle(t *testing.T) { } func TestNotifierConcurrent(t *testing.T) { - n, _ := countingNotifier() + n, _ := countingNotifier(t) var wg sync.WaitGroup for i := 0; i < 50; i++ { wg.Add(1) diff --git a/internal/command/mping.go b/internal/command/mping.go index b3b5b32..dc852ea 100644 --- a/internal/command/mping.go +++ b/internal/command/mping.go @@ -71,6 +71,7 @@ mping dns://8.8.8.8/google.com`, // The notifier rings the bell on failures unless the host was muted // with the "m" key in the TUI. notifier := beep.NewNotifier() + defer notifier.Close() sess, err := newSession(sessionParams{ Cfg: cfg, diff --git a/internal/stats/history.go b/internal/stats/history.go index 73d75bd..11e6a94 100644 --- a/internal/stats/history.go +++ b/internal/stats/history.go @@ -1,6 +1,7 @@ package stats import ( + "sort" "time" "github.com/servak/mping/internal/prober" @@ -25,6 +26,9 @@ type TargetHistory struct { // NewTargetHistory creates a new TargetHistory func NewTargetHistory(size int) *TargetHistory { + if size < 1 { + size = 1 + } return &TargetHistory{ entries: make([]HistoryEntry, size), size: size, @@ -33,8 +37,17 @@ func NewTargetHistory(size int) *TargetHistory { } } -// AddEntry adds a new history entry +// AddEntry adds a new history entry. Entries are kept ordered by Timestamp +// (send time), so a late result for an older probe is inserted before newer +// ones instead of being appended at the newest end. func (th *TargetHistory) AddEntry(entry HistoryEntry) { + if th.count > 0 { + newest := th.entries[(th.index-1+th.size)%th.size] + if entry.Timestamp.Before(newest.Timestamp) { + th.insertOrdered(entry) + return + } + } th.entries[th.index] = entry th.index = (th.index + 1) % th.size if th.count < th.size { @@ -42,6 +55,34 @@ func (th *TargetHistory) AddEntry(entry HistoryEntry) { } } +// insertOrdered inserts an entry that is older than the newest one at its +// chronological position, dropping the oldest entry if the buffer is full. +func (th *TargetHistory) insertOrdered(entry HistoryEntry) { + // at returns the i-th entry counting from the oldest + at := func(i int) int { return (th.index - th.count + i + th.size*2) % th.size } + // position (from the oldest) after any entries with an equal timestamp + pos := sort.Search(th.count, func(i int) bool { return th.entries[at(i)].Timestamp.After(entry.Timestamp) }) + if th.count == th.size { + // Full: drop the oldest by shifting the older part one slot back, + // then place the entry at pos-1 (an entry older than all is dropped). + if pos == 0 { + return + } + for i := 0; i < pos-1; i++ { + th.entries[at(i)] = th.entries[at(i+1)] + } + th.entries[at(pos-1)] = entry + return + } + // Not full: shift the newer part one slot forward, then insert. + for i := th.count; i > pos; i-- { + th.entries[at(i)] = th.entries[at(i-1)] + } + th.entries[at(pos)] = entry + th.count++ + th.index = (th.index + 1) % th.size +} + // GetRecentEntries retrieves the latest n entries (newest first) func (th *TargetHistory) GetRecentEntries(n int) []HistoryEntry { if n <= 0 || th.count == 0 { diff --git a/internal/stats/manager.go b/internal/stats/manager.go index fd1ea59..b622c42 100644 --- a/internal/stats/manager.go +++ b/internal/stats/manager.go @@ -1,7 +1,8 @@ package stats import ( - "sort" + "slices" + "strings" "sync" "time" @@ -97,6 +98,10 @@ func (mm *metricsManager) SuccessWithDetails(host string, rtt time.Duration, sen m := mm.getMetrics(host) mm.mu.Lock() + if sentTime.Before(m.resetAt) { + mm.mu.Unlock() + return // probe sent before the last reset + } m.Success(rtt, sentTime) if m.history != nil { m.history.AddEntry(HistoryEntry{ @@ -115,6 +120,10 @@ func (mm *metricsManager) Failed(host string, sentTime time.Time, msg string) { m := mm.getMetrics(host) mm.mu.Lock() + if sentTime.Before(m.resetAt) { + mm.mu.Unlock() + return // probe sent before the last reset + } name := m.Name m.Fail(sentTime, msg) if m.history != nil { @@ -134,11 +143,16 @@ func (mm *metricsManager) Failed(host string, sentTime time.Time, msg string) { } } -func (mm *metricsManager) Sent(host string) { +// Sent counts a sent probe. Probes sent before the last reset are dropped, +// like their results, so a SENT event queued before a reset cannot inflate +// Total afterwards. +func (mm *metricsManager) Sent(host string, sentTime time.Time) { m := mm.getMetrics(host) mm.mu.Lock() - m.Sent() + if !sentTime.Before(m.resetAt) { + m.Sent() + } mm.mu.Unlock() } @@ -154,7 +168,7 @@ func (mm *metricsManager) Subscribe(res <-chan *prober.Event) <-chan struct{} { case prober.REGISTER: mm.autoRegister(r.Key, r.DisplayName, string(r.ProbeType)) case prober.SENT: - mm.Sent(r.Key) + mm.Sent(r.Key, r.SentTime) case prober.SUCCESS: mm.SuccessWithDetails(r.Key, r.Rtt, r.SentTime, r.Details) case prober.TIMEOUT: @@ -196,16 +210,15 @@ func (mm *metricsManager) SortBy(k Key, ascending bool) []Metrics { mm.mu.Lock() defer mm.mu.Unlock() now := time.Now() - var res []Metrics - for _, m := range mm.metrics { - res = append(res, m.settledSnapshot(now)) + type item struct { + key string + m Metrics } - - if k != Host { - sort.SliceStable(res, func(i, j int) bool { - return res[i].GetName() < res[j].GetName() - }) + items := make([]item, 0, len(mm.metrics)) + for key, m := range mm.metrics { + items = append(items, item{key, m.settledSnapshot(now)}) } + // less must be a strict ordering: descending order swaps the operands // instead of negating the result, which would make equal elements // "less" than each other and reorder them on every call. @@ -230,16 +243,34 @@ func (mm *metricsManager) SortBy(k Key, ascending bool) []Metrics { } return false } - sort.SliceStable(res, func(i, j int) bool { + // One sort: primary key, then display name, then key as tie-breakers + slices.SortFunc(items, func(a, b item) int { // Unmeasured RTTs (zero) always go last, whatever the direction - if zi, zj := rttFor(k, res[i]) == 0, rttFor(k, res[j]) == 0; zi != zj { - return zj + if za, zb := rttFor(k, a.m) == 0, rttFor(k, b.m) == 0; za != zb { + if zb { + return -1 + } + return 1 + } + x, y := a.m, b.m + if !ascending { + x, y = y, x } - if ascending { - return less(res[i], res[j]) + if less(x, y) { + return -1 } - return less(res[j], res[i]) + if less(y, x) { + return 1 + } + if c := strings.Compare(a.m.GetName(), b.m.GetName()); c != 0 { + return c + } + return strings.Compare(a.key, b.key) }) + res := make([]Metrics, len(items)) + for i, it := range items { + res[i] = it.m + } return res } diff --git a/internal/stats/metric.go b/internal/stats/metric.go index 6bf6fb6..8842935 100644 --- a/internal/stats/metric.go +++ b/internal/stats/metric.go @@ -56,16 +56,21 @@ type metrics struct { LastFailDetail string history *TargetHistory // 履歴情報 outage *outageTracker + resetAt time.Time // results of probes sent before this are stale } func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { m.Successful++ - m.LastSuccTime = sentTime - m.LastRTT = rtt + // Newest-or-equal send time wins (same tie rule as Fail), so a late + // result of an older probe overwrites neither the time nor the RTT. + if !sentTime.Before(m.LastSuccTime) { + m.LastSuccTime = sentTime + m.LastRTT = rtt + } m.TotalRTT += rtt m.sumSquaredRTT += float64(rtt) * float64(rtt) m.AverageRTT = m.TotalRTT / time.Duration(m.Successful) - if m.MinimumRTT == 0 || rtt < m.MinimumRTT { + if m.Successful == 1 || rtt < m.MinimumRTT { m.MinimumRTT = rtt } if rtt > m.MaximumRTT { @@ -76,8 +81,12 @@ func (m *metrics) Success(rtt time.Duration, sentTime time.Time) { func (m *metrics) Fail(sentTime time.Time, msg string) { m.Failed++ - m.LastFailTime = sentTime - m.LastFailDetail = msg + // Newest-or-equal send time wins (same tie rule as Success); a late + // result of an older probe must not overwrite newer failure info. + if !sentTime.Before(m.LastFailTime) { + m.LastFailTime = sentTime + m.LastFailDetail = msg + } m.loss() } @@ -90,6 +99,7 @@ func (m *metrics) Sent() { } func (m *metrics) Reset() { + m.resetAt = time.Now() m.Total = 0 m.Successful = 0 m.Failed = 0 diff --git a/internal/stats/regression_test.go b/internal/stats/regression_test.go new file mode 100644 index 0000000..30eb019 --- /dev/null +++ b/internal/stats/regression_test.go @@ -0,0 +1,229 @@ +package stats + +import ( + "slices" + "testing" + "time" +) + +func TestResetDropsStaleResults(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + sent := time.Now().Add(-time.Second) + mm.Sent("a", time.Now()) + time.Sleep(2 * time.Millisecond) + mm.ResetAllMetrics() + mm.SuccessWithDetails("a", time.Millisecond, sent, nil) + mm.Failed("a", sent, "late") + m := mm.GetMetrics("a") + if m.GetTotal() != 0 || m.GetSuccessful() != 0 || m.GetFailed() != 0 { + t.Errorf("stale results counted: %d/%d/%d", m.GetTotal(), m.GetSuccessful(), m.GetFailed()) + } + if len(m.GetRecentHistory(10)) != 0 { + t.Error("stale result entered history") + } + mm.SuccessWithDetails("a", time.Millisecond, time.Now(), nil) + if mm.GetMetrics("a").GetSuccessful() != 1 { + t.Error("fresh result after reset must be counted") + } +} + +func TestHistoryOrderedBySentTime(t *testing.T) { + h := NewTargetHistory(5) + base := time.Now().Add(-time.Minute) + h.AddEntry(HistoryEntry{Timestamp: base.Add(2 * time.Second), Success: true}) + h.AddEntry(HistoryEntry{Timestamp: base, Success: false}) // late timeout of older probe + if got := h.GetConsecutiveSuccesses(); got != 1 { + t.Errorf("consecutive successes = %d, want 1", got) + } + if got := h.GetConsecutiveFailures(); got != 0 { + t.Errorf("consecutive failures = %d, want 0", got) + } + e := h.GetRecentEntries(2) + if !e[0].Timestamp.After(e[1].Timestamp) { + t.Error("entries not newest-first by sent time") + } + // full buffer: insertion keeps order and size + for i := 3; i < 8; i++ { + h.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second), Success: true}) + } + h.AddEntry(HistoryEntry{Timestamp: base.Add(4500 * time.Millisecond), Success: false}) + e = h.GetRecentEntries(10) + if len(e) != 5 { + t.Fatalf("len = %d", len(e)) + } + for i := 1; i < len(e); i++ { + if e[i].Timestamp.After(e[i-1].Timestamp) { + t.Errorf("order broken at %d", i) + } + } +} + +func TestLastTimesKeepNewest(t *testing.T) { + m := newMetrics("a", 5, 0) + t1 := time.Now() + t0 := t1.Add(-time.Second) + m.Success(time.Millisecond, t1) + m.Success(time.Millisecond, t0) + if !m.LastSuccTime.Equal(t1) { + t.Error("LastSuccTime overwritten by older result") + } + m.Fail(t1, "new") + m.Fail(t0, "old") + if !m.LastFailTime.Equal(t1) || m.LastFailDetail != "new" { + t.Error("LastFailTime/Detail overwritten by older result") + } +} + +func TestMinimumRTTZeroSample(t *testing.T) { + m := newMetrics("a", 5, 0) + m.Success(0, time.Now()) + m.Success(5*time.Millisecond, time.Now()) + if m.MinimumRTT != 0 { + t.Errorf("MinimumRTT = %v, want 0", m.MinimumRTT) + } +} + +func TestSortDeterministicTies(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + for _, k := range []string{"k3", "k1", "k2", "k5", "k4"} { + mm.autoRegister(k, "same", "") + } + var first []string + // order must follow key order for equal names/values + mm.metrics["k1"].ProbeType = "p1" + mm.metrics["k2"].ProbeType = "p2" + mm.metrics["k3"].ProbeType = "p3" + mm.metrics["k4"].ProbeType = "p4" + mm.metrics["k5"].ProbeType = "p5" + for i := 0; i < 30; i++ { + var got []string + for _, r := range mm.SortBy(Sent, i%2 == 0) { + got = append(got, r.GetProbeType()) + } + if first == nil { + first = got + } + want := []string{"p1", "p2", "p3", "p4", "p5"} + for j := range want { + if got[j] != want[j] { + t.Fatalf("iteration %d: got %v, want %v", i, got, want) + } + } + } +} + +func TestNewMetricsZeroHistorySize(t *testing.T) { + m := NewMetrics("a", 0) + h := NewTargetHistory(-1) + h.AddEntry(HistoryEntry{Timestamp: time.Now()}) + if len(h.GetRecentEntries(5)) != 1 { + t.Error("expected one entry") + } + _ = m +} + +func TestSentProcessedAfterResetIsDropped(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + sent := time.Now() + time.Sleep(2 * time.Millisecond) + mm.getMetrics("h") + mm.ResetAllMetrics() + // SENT and its result were queued before the reset, processed after it + mm.Sent("h", sent) + mm.SuccessWithDetails("h", time.Millisecond, sent, nil) + m := mm.GetMetrics("h") + if m.GetTotal() != 0 || m.GetSuccessful() != 0 || m.GetFailed() != 0 { + t.Errorf("stale SENT counted: %d/%d/%d", m.GetTotal(), m.GetSuccessful(), m.GetFailed()) + } + mm.Sent("h", time.Now()) + if mm.GetMetrics("h").GetTotal() != 1 { + t.Error("fresh SENT after reset must be counted") + } +} + +func TestLastRTTKeepsNewest(t *testing.T) { + m := newMetrics("x", 10, 0) + now := time.Now() + m.Success(5*time.Millisecond, now) + m.Success(500*time.Millisecond, now.Add(-time.Second)) + if m.LastRTT != 5*time.Millisecond { + t.Errorf("LastRTT = %v, want 5ms", m.LastRTT) + } + // equal send time: newest-or-equal wins, for success and failure alike + m.Success(7*time.Millisecond, now) + if m.LastRTT != 7*time.Millisecond { + t.Errorf("LastRTT = %v, want 7ms on tie", m.LastRTT) + } + m.Fail(now, "a") + m.Fail(now, "b") + if m.LastFailDetail != "b" { + t.Errorf("LastFailDetail = %q, want b on tie", m.LastFailDetail) + } +} + +func TestInsertOrderedNoAllocAndOrder(t *testing.T) { + for _, size := range []int{1, 2, 3, 5, 8} { + base := time.Now() + h := NewTargetHistory(size) + added := 0 + // pseudo-random out-of-order timestamps, wrapping the ring several times + for i := 0; i < 40; i++ { + ts := base.Add(time.Duration((i*7)%13) * time.Second) + h.AddEntry(HistoryEntry{Timestamp: ts}) + added++ + e := h.GetRecentEntries(size) + for j := 1; j < len(e); j++ { + if e[j].Timestamp.After(e[j-1].Timestamp) { + t.Fatalf("size %d step %d: order broken", size, i) + } + } + if want := min(added, size); len(e) != want { + t.Fatalf("size %d step %d: len %d want %d", size, i, len(e), want) + } + } + } + h := NewTargetHistory(100) + base := time.Now() + for i := 0; i < 100; i++ { + h.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second)}) + } + allocs := testing.AllocsPerRun(100, func() { + h.AddEntry(HistoryEntry{Timestamp: base.Add(50*time.Second + time.Millisecond)}) + }) + if allocs != 0 { + t.Errorf("late insert allocated %v times", allocs) + } +} + +func TestInsertOrderedFullOlderThanAll(t *testing.T) { + th := NewTargetHistory(3) + base := time.Now() + for i := 1; i <= 3; i++ { + th.AddEntry(HistoryEntry{Timestamp: base.Add(time.Duration(i) * time.Second), RTT: time.Duration(i)}) + } + th.AddEntry(HistoryEntry{Timestamp: base, RTT: 99}) // older than all: dropped + th.AddEntry(HistoryEntry{Timestamp: base.Add(1500 * time.Millisecond), RTT: 15}) + var got []time.Duration + for _, e := range th.GetRecentEntries(3) { + got = append(got, e.RTT) + } + if !slices.Equal(got, []time.Duration{3, 2, 15}) { + t.Errorf("got %v, want [3 2 15]", got) + } +} + +func TestSortByTieBreakNameThenKey(t *testing.T) { + mm := NewMetricsManager().(*metricsManager) + mm.autoRegister("k2", "b", "p2") + mm.autoRegister("k1", "b", "p1") + mm.autoRegister("k3", "a", "p3") + for _, asc := range []bool{true, false} { + var got []string + for _, r := range mm.SortBy(Sent, asc) { + got = append(got, r.GetProbeType()) + } + if !slices.Equal(got, []string{"p3", "p1", "p2"}) { + t.Errorf("asc=%v got %v", asc, got) + } + } +}