xonecas.io
6119
My

mysis / files

mysis / internal / features / autoplay.go

6.5 KB
1package features
2
3import (
4	"context"
5	"fmt"
6	"sync"
7	"time"
8
9	"github.com/rs/zerolog/log"
10	"github.com/xonecas/mysis/internal/constants"
11)
12
13const (
14	// maxConsecutiveErrors is the threshold for circuit breaker.
15	// After this many consecutive errors, autoplay will stop.
16	maxConsecutiveErrors = 3
17)
18
19// AutoplayStatus represents the current state of autoplay.
20type AutoplayStatus struct {
21	Enabled  bool
22	Message  string
23	Interval time.Duration
24}
25
26// AutoplayCallbacks defines the callback functions for autoplay events.
27// These allow display-specific implementations to handle events differently.
28type AutoplayCallbacks struct {
29	// OnStarted is called when autoplay starts.
30	OnStarted func(message string, interval time.Duration)
31
32	// OnStopped is called when autoplay stops.
33	OnStopped func()
34
35	// OnTurn is called before sending each autoplay message.
36	// Should return an error if the turn should not be processed.
37	OnTurn func(ctx context.Context, message string) error
38
39	// OnError is called when an error occurs during autoplay.
40	OnError func(err error)
41}
42
43// Service manages autoplay functionality in a display-agnostic way.
44// It handles the timing, state management, and loop control for autoplay,
45// while delegating display-specific concerns to callbacks.
46type Service struct {
47	enabled           bool
48	message           string
49	interval          time.Duration
50	cancel            context.CancelFunc
51	mu                sync.Mutex
52	callbacks         AutoplayCallbacks
53	consecutiveErrors int // P3: Track consecutive failures for circuit breaker
54}
55
56// NewAutoplayService creates a new autoplay service with the given callbacks.
57func NewAutoplayService(callbacks AutoplayCallbacks) *Service {
58	return &Service{
59		interval:  constants.AutoplayInterval,
60		callbacks: callbacks,
61	}
62}
63
64// Start begins autoplay with the given message.
65// Returns an error if autoplay is already running or if inputs are invalid.
66func (s *Service) Start(ctx context.Context, message string) error {
67	// P2: Validate inputs
68	if ctx == nil {
69		return fmt.Errorf("context cannot be nil")
70	}
71	if message == "" {
72		return fmt.Errorf("message cannot be empty")
73	}
74
75	s.mu.Lock()
76	if s.enabled {
77		s.mu.Unlock()
78		return fmt.Errorf("autoplay already running")
79	}
80
81	s.enabled = true
82	s.message = message
83	s.consecutiveErrors = 0 // P3: Reset error counter on start
84
85	// P1: Use Background context for autoplay loop independence
86	// The autoplay loop needs to run independently of the caller's context.
87	// If we used the passed ctx and it gets canceled, the autoplay loop would stop unexpectedly.
88	// Instead, we create our own context from Background that we control via Stop().
89	autoplayCtx, cancel := context.WithCancel(context.Background())
90	s.cancel = cancel
91	s.mu.Unlock()
92
93	// Notify via callback
94	if s.callbacks.OnStarted != nil {
95		s.callbacks.OnStarted(message, s.interval)
96	}
97
98	log.Info().
99		Str("message", message).
100		Dur("interval", s.interval).
101		Msg("Autoplay started")
102
103	// Start autoplay loop in background
104	go s.runLoop(autoplayCtx)
105
106	return nil
107}
108
109// Stop stops the autoplay loop.
110// Returns an error if autoplay is not running.
111func (s *Service) Stop() error {
112	s.mu.Lock()
113	if !s.enabled {
114		s.mu.Unlock()
115		return fmt.Errorf("autoplay not active")
116	}
117
118	s.enabled = false
119	if s.cancel != nil {
120		s.cancel()
121		s.cancel = nil
122	}
123	s.mu.Unlock()
124
125	log.Info().Msg("Autoplay stopped")
126	return nil
127}
128
129// Status returns the current autoplay status.
130func (s *Service) Status() AutoplayStatus {
131	s.mu.Lock()
132	defer s.mu.Unlock()
133
134	return AutoplayStatus{
135		Enabled:  s.enabled,
136		Message:  s.message,
137		Interval: s.interval,
138	}
139}
140
141// runLoop is the main autoplay loop that runs in a background goroutine.
142func (s *Service) runLoop(ctx context.Context) {
143	log.Debug().Msg("Autoplay goroutine started")
144
145	defer func() {
146		// Normal cleanup
147		s.mu.Lock()
148		s.enabled = false
149		s.cancel = nil
150		s.mu.Unlock()
151
152		// Notify via callback
153		if s.callbacks.OnStopped != nil {
154			s.callbacks.OnStopped()
155		}
156
157		log.Debug().Msg("Autoplay goroutine exiting")
158	}()
159
160	// Send first message immediately
161	log.Debug().Msg("Sending first autoplay message")
162	if err := s.sendMessage(ctx); err != nil {
163		log.Error().Err(err).Msg("Autoplay failed to send first message")
164		s.mu.Lock()
165		s.consecutiveErrors++
166		consecutiveErrors := s.consecutiveErrors
167		s.mu.Unlock()
168
169		if s.callbacks.OnError != nil {
170			s.callbacks.OnError(err)
171		}
172
173		// P3: Circuit breaker - stop if too many consecutive errors
174		if consecutiveErrors >= maxConsecutiveErrors {
175			log.Warn().Int("consecutive_errors", consecutiveErrors).Msg("Circuit breaker triggered - stopping autoplay")
176			return
177		}
178		return
179	}
180	// Reset error counter on success
181	s.mu.Lock()
182	s.consecutiveErrors = 0
183	s.mu.Unlock()
184	log.Debug().Msg("First autoplay message sent successfully")
185
186	// Check if canceled during first message processing
187	select {
188	case <-ctx.Done():
189		return
190	default:
191	}
192
193	// Then wait and send subsequent messages
194	ticker := time.NewTicker(s.interval)
195	defer ticker.Stop()
196
197	for {
198		select {
199		case <-ctx.Done():
200			return
201		case <-ticker.C:
202			s.mu.Lock()
203			enabled := s.enabled
204			s.mu.Unlock()
205
206			if !enabled {
207				return
208			}
209
210			if err := s.sendMessage(ctx); err != nil {
211				log.Warn().Err(err).Msg("Autoplay turn failed")
212				s.mu.Lock()
213				s.consecutiveErrors++
214				consecutiveErrors := s.consecutiveErrors
215				s.mu.Unlock()
216
217				if s.callbacks.OnError != nil {
218					s.callbacks.OnError(err)
219				}
220
221				// P3: Circuit breaker - stop if too many consecutive errors
222				if consecutiveErrors >= maxConsecutiveErrors {
223					log.Warn().Int("consecutive_errors", consecutiveErrors).Msg("Circuit breaker triggered - stopping autoplay")
224					return
225				}
226			} else {
227				// Reset error counter on success
228				s.mu.Lock()
229				s.consecutiveErrors = 0
230				s.mu.Unlock()
231			}
232
233			// Check if canceled immediately after processing turn
234			select {
235			case <-ctx.Done():
236				return
237			default:
238			}
239		}
240	}
241}
242
243// sendMessage sends a single autoplay message by calling the OnTurn callback.
244func (s *Service) sendMessage(ctx context.Context) error {
245	log.Debug().Msg("sendAutoplayMessage called")
246
247	s.mu.Lock()
248	enabled := s.enabled
249	message := s.message
250	s.mu.Unlock()
251
252	log.Debug().Bool("enabled", enabled).Str("message", message).Msg("Autoplay state")
253
254	if !enabled {
255		return fmt.Errorf("autoplay disabled")
256	}
257
258	// Call the OnTurn callback to process the turn
259	if s.callbacks.OnTurn == nil {
260		return fmt.Errorf("no OnTurn callback configured")
261	}
262
263	if err := s.callbacks.OnTurn(ctx, message); err != nil {
264		return fmt.Errorf("autoplay turn failed: %w", err)
265	}
266
267	log.Debug().Msg("Autoplay message sent successfully")
268	return nil
269}