Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 75 additions & 26 deletions internal/beep/beep.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package beep

import (
"fmt"
"io"
"os"
"sync"
"time"
Expand All @@ -12,70 +13,118 @@ 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
}

// Toggle switches beep sound on/off and returns the new state
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)
Expand Down
100 changes: 100 additions & 0 deletions internal/beep/beep_test.go
Original file line number Diff line number Diff line change
@@ -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")
Expand All @@ -19,6 +23,7 @@ func TestNewBeeper(t *testing.T) {

func TestToggle(t *testing.T) {
beeper := NewBeeper()
defer beeper.Close()

initialState := beeper.IsEnabled()
beeper.Toggle()
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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())
}
}
5 changes: 5 additions & 0 deletions internal/beep/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
11 changes: 6 additions & 5 deletions internal/beep/notifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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")
}
Expand All @@ -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)
Expand All @@ -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")
}
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions internal/command/mping.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading