sonos-sdk-stream 0.5.1

Internal event streaming and subscription management for sonos-sdk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Polling task scheduler and management
//!
//! This module provides intelligent polling task management with support for
//! adaptive intervals, graceful shutdown, and coordination with the event system.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::{mpsc, RwLock};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};

use crate::error::{PollingError, PollingResult};
use crate::events::types::{EnrichedEvent, EventSource};
use crate::polling::strategies::DeviceStatePoller;
use crate::registry::{RegistrationId, SpeakerServicePair};

/// A single polling task with state management
#[derive(Debug)]
pub struct PollingTask {
    /// Registration ID this task is polling for
    registration_id: RegistrationId,

    /// Speaker/service pair being polled
    speaker_service_pair: SpeakerServicePair,

    /// Current polling interval
    current_interval: Duration,

    /// Task handle for the background polling loop
    task_handle: JoinHandle<()>,

    /// Shutdown signal for graceful termination
    shutdown_signal: Arc<AtomicBool>,

    /// When this task was started
    started_at: SystemTime,

    /// Number of consecutive errors
    error_count: Arc<RwLock<u32>>,

    /// Total number of polls performed
    poll_count: Arc<RwLock<u64>>,
}

impl PollingTask {
    /// Create and start a new polling task
    pub fn start(
        registration_id: RegistrationId,
        speaker_service_pair: SpeakerServicePair,
        initial_interval: Duration,
        max_interval: Duration,
        adaptive_polling: bool,
        device_poller: Arc<DeviceStatePoller>,
        event_sender: mpsc::UnboundedSender<EnrichedEvent>,
    ) -> Self {
        let shutdown_signal = Arc::new(AtomicBool::new(false));
        let error_count = Arc::new(RwLock::new(0));
        let poll_count = Arc::new(RwLock::new(0));

        // Clone for the task
        let task_registration_id = registration_id;
        let task_pair = speaker_service_pair.clone();
        let task_shutdown_signal = Arc::clone(&shutdown_signal);
        let task_error_count = Arc::clone(&error_count);
        let task_poll_count = Arc::clone(&poll_count);

        let task_handle = tokio::spawn(async move {
            Self::polling_loop(
                task_registration_id,
                task_pair,
                initial_interval,
                max_interval,
                adaptive_polling,
                device_poller,
                event_sender,
                task_shutdown_signal,
                task_error_count,
                task_poll_count,
            )
            .await;
        });

        Self {
            registration_id,
            speaker_service_pair,
            current_interval: initial_interval,
            task_handle,
            shutdown_signal,
            started_at: SystemTime::now(),
            error_count,
            poll_count,
        }
    }

    /// Main polling loop
    #[allow(clippy::too_many_arguments)]
    async fn polling_loop(
        registration_id: RegistrationId,
        pair: SpeakerServicePair,
        mut current_interval: Duration,
        max_interval: Duration,
        adaptive_polling: bool,
        device_poller: Arc<DeviceStatePoller>,
        event_sender: mpsc::UnboundedSender<EnrichedEvent>,
        shutdown_signal: Arc<AtomicBool>,
        error_count: Arc<RwLock<u32>>,
        poll_count: Arc<RwLock<u64>>,
    ) {
        info!(
            speaker_ip = %pair.speaker_ip,
            service = ?pair.service,
            ?current_interval,
            "Starting polling task"
        );

        // Track last state locally within the loop
        let mut last_state: Option<String> = None;

        loop {
            // Check for shutdown signal
            if shutdown_signal.load(Ordering::Relaxed) {
                info!(
                    speaker_ip = %pair.speaker_ip,
                    service = ?pair.service,
                    "Polling task shutting down"
                );
                break;
            }

            // Sleep for the current interval
            tokio::time::sleep(current_interval).await;

            // Increment poll count
            {
                let mut count = poll_count.write().await;
                *count += 1;
            }

            // Poll the device state
            match device_poller.poll_device_state(&pair).await {
                Ok(current_state) => {
                    // Reset error count on success
                    {
                        let mut errors = error_count.write().await;
                        *errors = 0;
                    }

                    // Check for state changes (compare without cloning)
                    let state_changed = last_state.as_deref() != Some(current_state.as_str());

                    if state_changed {
                        last_state = Some(current_state.clone());
                    }

                    if state_changed {
                        debug!(
                            speaker_ip = %pair.speaker_ip,
                            service = ?pair.service,
                            "State change detected"
                        );

                        // Convert JSON snapshot to EventData and emit full-state event
                        match device_poller.state_to_event_data(&pair.service, &current_state) {
                            Ok(event_data) => {
                                let enriched_event = EnrichedEvent::new(
                                    registration_id,
                                    pair.speaker_ip,
                                    pair.service,
                                    EventSource::PollingDetection {
                                        poll_interval: current_interval,
                                    },
                                    event_data,
                                );

                                if event_sender.send(enriched_event).is_err() {
                                    error!(
                                        speaker_ip = %pair.speaker_ip,
                                        service = ?pair.service,
                                        "Failed to send polling event — channel closed"
                                    );
                                    return;
                                }
                            }
                            Err(e) => {
                                warn!(
                                    speaker_ip = %pair.speaker_ip,
                                    service = ?pair.service,
                                    error = %e,
                                    "Failed to convert state to event data"
                                );
                            }
                        }

                        // Adjust interval if adaptive polling is enabled
                        if adaptive_polling {
                            current_interval = Self::calculate_adaptive_interval(
                                current_interval,
                                max_interval,
                                SystemTime::now(),
                            );
                        }
                    }
                }
                Err(e) => {
                    // Increment error count
                    let error_count_value = {
                        let mut errors = error_count.write().await;
                        *errors += 1;
                        *errors
                    };

                    warn!(
                        speaker_ip = %pair.speaker_ip,
                        service = ?pair.service,
                        attempt = error_count_value,
                        error = %e,
                        "Polling error"
                    );

                    // Use exponential backoff for errors
                    if error_count_value >= 5 {
                        error!(
                            speaker_ip = %pair.speaker_ip,
                            service = ?pair.service,
                            "Too many consecutive errors, stopping polling"
                        );
                        break;
                    }

                    // Exponential backoff up to max interval
                    let backoff_interval = current_interval * (2_u32.pow(error_count_value.min(6)));
                    let capped_interval = backoff_interval.min(max_interval);
                    tokio::time::sleep(capped_interval).await;
                }
            }
        }

        info!(
            speaker_ip = %pair.speaker_ip,
            service = ?pair.service,
            "Polling task ended"
        );
    }

    /// Calculate adaptive polling interval based on recent activity
    fn calculate_adaptive_interval(
        current_interval: Duration,
        max_interval: Duration,
        last_change_time: SystemTime,
    ) -> Duration {
        let time_since_change = SystemTime::now()
            .duration_since(last_change_time)
            .unwrap_or(Duration::ZERO);

        if time_since_change < Duration::from_secs(30) {
            // Recent activity - poll faster
            (current_interval / 2).max(Duration::from_secs(2))
        } else if time_since_change > Duration::from_secs(300) {
            // No recent activity - poll slower
            (current_interval * 2).min(max_interval)
        } else {
            current_interval
        }
    }

    /// Get the registration ID for this task
    pub fn registration_id(&self) -> RegistrationId {
        self.registration_id
    }

    /// Get the speaker/service pair for this task
    pub fn speaker_service_pair(&self) -> &SpeakerServicePair {
        &self.speaker_service_pair
    }

    /// Get the current polling interval
    pub fn current_interval(&self) -> Duration {
        self.current_interval
    }

    /// Check if the task is still running
    pub fn is_running(&self) -> bool {
        !self.task_handle.is_finished()
    }

    /// Get task statistics
    pub async fn stats(&self) -> PollingTaskStats {
        let error_count = *self.error_count.read().await;
        let poll_count = *self.poll_count.read().await;

        PollingTaskStats {
            registration_id: self.registration_id,
            speaker_service_pair: self.speaker_service_pair.clone(),
            current_interval: self.current_interval,
            started_at: self.started_at,
            error_count,
            poll_count,
            is_running: self.is_running(),
        }
    }

    /// Request graceful shutdown of this polling task
    pub async fn shutdown(self) -> PollingResult<()> {
        // Signal shutdown
        self.shutdown_signal.store(true, Ordering::Relaxed);

        // Wait for task to complete
        match self.task_handle.await {
            Ok(()) => Ok(()),
            Err(e) => Err(PollingError::TaskSpawn(format!(
                "Failed to await task completion: {e}"
            ))),
        }
    }
}

/// Statistics for a polling task
#[derive(Debug, Clone)]
pub struct PollingTaskStats {
    pub registration_id: RegistrationId,
    pub speaker_service_pair: SpeakerServicePair,
    pub current_interval: Duration,
    pub started_at: SystemTime,
    pub error_count: u32,
    pub poll_count: u64,
    pub is_running: bool,
}

/// Manages multiple polling tasks
pub struct PollingScheduler {
    /// Active polling tasks indexed by registration ID
    active_tasks: Arc<RwLock<HashMap<RegistrationId, PollingTask>>>,

    /// Device state poller for making actual polling requests
    device_poller: Arc<DeviceStatePoller>,

    /// Event sender for emitting synthetic events
    event_sender: mpsc::UnboundedSender<EnrichedEvent>,

    /// Base polling interval
    base_interval: Duration,

    /// Maximum polling interval for adaptive polling
    max_interval: Duration,

    /// Whether to use adaptive polling intervals
    adaptive_polling: bool,

    /// Maximum number of concurrent polling tasks
    max_concurrent_tasks: usize,
}

impl PollingScheduler {
    /// Create a new polling scheduler
    pub fn new(
        event_sender: mpsc::UnboundedSender<EnrichedEvent>,
        base_interval: Duration,
        max_interval: Duration,
        adaptive_polling: bool,
        max_concurrent_tasks: usize,
    ) -> Self {
        Self {
            active_tasks: Arc::new(RwLock::new(HashMap::new())),
            device_poller: Arc::new(DeviceStatePoller::new()),
            event_sender,
            base_interval,
            max_interval,
            adaptive_polling,
            max_concurrent_tasks,
        }
    }

    /// Start polling for a speaker/service pair
    pub async fn start_polling(
        &self,
        registration_id: RegistrationId,
        pair: SpeakerServicePair,
    ) -> PollingResult<()> {
        let mut tasks = self.active_tasks.write().await;

        // Check if already polling
        if tasks.contains_key(&registration_id) {
            return Ok(()); // Already polling
        }

        // Check concurrent task limit
        if tasks.len() >= self.max_concurrent_tasks {
            return Err(PollingError::TooManyErrors {
                error_count: tasks.len() as u32,
            });
        }

        // Start new polling task
        let task = PollingTask::start(
            registration_id,
            pair.clone(),
            self.base_interval,
            self.max_interval,
            self.adaptive_polling,
            Arc::clone(&self.device_poller),
            self.event_sender.clone(),
        );

        tasks.insert(registration_id, task);

        info!(
            speaker_ip = %pair.speaker_ip,
            service = ?pair.service,
            "Started polling"
        );

        Ok(())
    }

    /// Stop polling for a registration ID
    pub async fn stop_polling(&self, registration_id: RegistrationId) -> PollingResult<()> {
        let mut tasks = self.active_tasks.write().await;

        if let Some(task) = tasks.remove(&registration_id) {
            let pair = task.speaker_service_pair().clone();
            // Shutdown happens when task is dropped, but we can explicitly shut it down
            task.shutdown().await?;

            info!(
                speaker_ip = %pair.speaker_ip,
                service = ?pair.service,
                "Stopped polling"
            );
        }

        Ok(())
    }

    /// Check if a registration is currently being polled
    pub async fn is_polling(&self, registration_id: RegistrationId) -> bool {
        let tasks = self.active_tasks.read().await;
        tasks.contains_key(&registration_id)
    }

    /// Get statistics for all active polling tasks
    pub async fn stats(&self) -> PollingSchedulerStats {
        let tasks = self.active_tasks.read().await;
        let total_tasks = tasks.len();

        let mut task_stats = Vec::new();
        for task in tasks.values() {
            task_stats.push(task.stats().await);
        }

        PollingSchedulerStats {
            total_active_tasks: total_tasks,
            max_concurrent_tasks: self.max_concurrent_tasks,
            base_interval: self.base_interval,
            max_interval: self.max_interval,
            adaptive_polling: self.adaptive_polling,
            task_stats,
        }
    }

    /// Shutdown all polling tasks
    pub async fn shutdown_all(&self) -> PollingResult<()> {
        let mut tasks = self.active_tasks.write().await;

        for (registration_id, task) in tasks.drain() {
            match task.shutdown().await {
                Ok(()) => {
                    debug!(%registration_id, "Shutdown polling task");
                }
                Err(e) => {
                    error!(%registration_id, error = %e, "Failed to shutdown polling task");
                }
            }
        }

        Ok(())
    }
}

/// Statistics for the polling scheduler
#[derive(Debug)]
pub struct PollingSchedulerStats {
    pub total_active_tasks: usize,
    pub max_concurrent_tasks: usize,
    pub base_interval: Duration,
    pub max_interval: Duration,
    pub adaptive_polling: bool,
    pub task_stats: Vec<PollingTaskStats>,
}

impl std::fmt::Display for PollingSchedulerStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Polling Scheduler Stats:")?;
        writeln!(
            f,
            "  Active tasks: {}/{}",
            self.total_active_tasks, self.max_concurrent_tasks
        )?;
        writeln!(f, "  Base interval: {:?}", self.base_interval)?;
        writeln!(f, "  Max interval: {:?}", self.max_interval)?;
        writeln!(f, "  Adaptive polling: {}", self.adaptive_polling)?;

        if !self.task_stats.is_empty() {
            writeln!(f, "  Task details:")?;
            for stat in &self.task_stats {
                writeln!(
                    f,
                    "    {}: {} {:?} (interval: {:?}, polls: {}, errors: {})",
                    stat.registration_id,
                    stat.speaker_service_pair.speaker_ip,
                    stat.speaker_service_pair.service,
                    stat.current_interval,
                    stat.poll_count,
                    stat.error_count
                )?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::sync::mpsc;

    #[tokio::test]
    async fn test_polling_scheduler_creation() {
        let (event_sender, _event_receiver) = mpsc::unbounded_channel();
        let scheduler = PollingScheduler::new(
            event_sender,
            Duration::from_secs(5),
            Duration::from_secs(30),
            true,
            10,
        );

        let stats = scheduler.stats().await;
        assert_eq!(stats.total_active_tasks, 0);
        assert_eq!(stats.max_concurrent_tasks, 10);
        assert!(stats.adaptive_polling);
    }

    #[tokio::test]
    async fn test_polling_task_lifecycle() {
        let (event_sender, _event_receiver) = mpsc::unbounded_channel();
        let scheduler = PollingScheduler::new(
            event_sender,
            Duration::from_millis(100), // Fast polling for testing
            Duration::from_secs(1),
            false,
            5,
        );

        let registration_id = RegistrationId::new(1);
        let pair = SpeakerServicePair::new(
            "192.168.1.100".parse().unwrap(),
            sonos_api::Service::AVTransport,
        );

        // Start polling
        scheduler
            .start_polling(registration_id, pair.clone())
            .await
            .unwrap();
        assert!(scheduler.is_polling(registration_id).await);

        // Stop polling
        scheduler.stop_polling(registration_id).await.unwrap();
        assert!(!scheduler.is_polling(registration_id).await);
    }

    #[test]
    fn test_adaptive_interval_calculation() {
        let current = Duration::from_secs(5);
        let max = Duration::from_secs(30);
        let recent_change = SystemTime::now() - Duration::from_secs(10);

        let new_interval = PollingTask::calculate_adaptive_interval(current, max, recent_change);
        // Should decrease interval for recent activity
        assert!(new_interval <= current);

        let old_change = SystemTime::now() - Duration::from_secs(400);
        let new_interval = PollingTask::calculate_adaptive_interval(current, max, old_change);
        // Should increase interval for old activity
        assert!(new_interval >= current);
    }
}