//! Version gating and lossless queue bridge (device-sync protocol v4). use super::*; use crate::player::queue_items::{self, test_episode}; use music_dht::podcast::{ EpisodeId, FeedUrl, ListenSession, PodcastId, PodcastMeta, ProgressStatus, }; const CONTENT_ID: &str = "b3:2222222222222222222222222222222222222222222222222222222222222222"; fn podcast_id() -> PodcastId { PodcastId::from_feed_url(&FeedUrl::parse("https://podcasts.example/feed.xml").unwrap()) } fn episode_id() -> EpisodeId { EpisodeId::from_guid(&podcast_id(), "ep-1").unwrap() } fn music_track(id: i64) -> PlaybackTrack { let mut track = PlaybackTrack::private_placeholder(); track.source = None; track.id = id; track.title = format!("Song {id}"); track } fn state(queue: Vec) -> PlaybackStateWire { PlaybackStateWire { queue, queue_pos: 0, playing: true, paused: false, idle_since_ms: None, position_secs: 12.5, volume: 70, shuffle: false, repeat: PlaybackRepeat::Off, playback_rate: None, } } fn podcast_state() -> PlaybackStateWire { state(vec![ music_track(1), PlaybackTrack::podcast_episode(test_episode()), ]) } /// One payload of every operation kind (music-only playback commands). fn every_payload(playback: PlaybackStateWire) -> Vec { let session = ListenSession { session_id: "s1".into(), episode_id: episode_id(), podcast_id: podcast_id(), device_id: "tui_a".into(), started_at_ms: 1, ended_at_ms: 2, start_position_ms: 0, end_position_ms: 1, listened_ms: 1, completed: false, }; let meta: PodcastMeta = serde_json::from_value(serde_json::json!({ "feed_url": "https://podcasts.example/feed.xml", "title": "Cast" })) .unwrap(); vec![ SyncOpPayload::TrackLikeSet { content_id: CONTENT_ID.into(), liked: true, fed: None, }, SyncOpPayload::PlaylistCreated { playlist_id: "p".into(), title: "t".into(), }, SyncOpPayload::PlaylistRenamed { playlist_id: "p".into(), title: "t".into(), }, SyncOpPayload::PlaylistDeleted { playlist_id: "p".into(), }, SyncOpPayload::PlaylistTrackAdded { playlist_id: "p".into(), content_id: CONTENT_ID.into(), position: 0, fed: None, }, SyncOpPayload::PlaylistTrackRemoved { playlist_id: "p".into(), content_id: CONTENT_ID.into(), }, SyncOpPayload::DeviceProfileSet { name: "n".into(), client_version: "v".into(), endpoint_ticket: "t".into(), endpoint_id: "e".into(), protocol_version: Some(4), }, SyncOpPayload::DeviceTrusted { target_device_id: "d".into(), }, SyncOpPayload::DeviceRevoked { target_device_id: "d".into(), target_max_seq_seen: 1, }, SyncOpPayload::PlaybackCommand { target_device_id: "d".into(), command: PlaybackCommand::SetState { state: playback, seek: false, }, authority: None, }, SyncOpPayload::ListenRecorded { event: ListenEvent { listen_id: "l".into(), content_id: CONTENT_ID.into(), started_at_ms: 1, listened_ms: 1, track_duration_ms: None, ended_reason: ListenEndReason::Finished, track: ListenTrackMetadata { title: "t".into(), artist_names: vec!["a".into()], featured_artist_names: vec![], release_title: None, }, }, }, SyncOpPayload::PodcastSubscriptionSet { podcast_id: podcast_id(), subscribed: true, podcast: meta, feed_aliases: vec![], generation: 1, }, SyncOpPayload::PodcastShareSet { podcast_id: podcast_id(), shared: false, generation: 1, }, SyncOpPayload::PodcastFeedAliasesAdded { podcast_id: podcast_id(), feed_aliases: vec![FeedUrl::parse("https://podcasts.example/new.xml").unwrap()], }, SyncOpPayload::PodcastProgressSet { episode_id: episode_id(), podcast_id: podcast_id(), position_ms: 1, status: ProgressStatus::InProgress, generation: 1, session_id: "s1".into(), episode: None, }, SyncOpPayload::PodcastListenRecorded { session, episode: None, }, ] } #[test] fn stored_kind_is_the_wire_tag() { for payload in every_payload(state(vec![])) { let value = serde_json::to_value(&payload).unwrap(); assert_eq!(payload_kind(&payload), value["kind"].as_str().unwrap()); } } #[test] fn op_gating_matrix_matches_the_shared_helper() { // The SQL kind filter must hide exactly what `op_allowed_for_peer` // rejects (playback commands are content-dependent and checked in Rust). for version in 1..=PROTOCOL_VERSION { let hidden = op_kinds_hidden_from(version); for payload in every_payload(state(vec![music_track(1)])) { let kind = payload_kind(&payload); assert_eq!( hidden.contains(&kind), !op_allowed_for_peer(&payload, version), "{kind} for v{version}" ); } } assert!( op_kinds_hidden_from(3) .iter() .all(|kind| kind.starts_with("podcast_")) ); assert_eq!(op_kinds_hidden_from(3).len(), 5); assert!(op_kinds_hidden_from(4).is_empty()); } #[test] fn playback_gating_matrix() { let music = state(vec![music_track(1), music_track(2)]); let podcasts = podcast_state(); let private = state(vec![PlaybackTrack::private_placeholder()]); for version in 1..=PROTOCOL_VERSION { let v4 = version >= 4; // Snapshots and handoffs. assert!(playback_allowed_for_peer(&music, version)); assert_eq!(playback_allowed_for_peer(&podcasts, version), v4); assert_eq!(playback_allowed_for_peer(&private, version), v4); // Commands from the peer. assert!(playback_command_allowed_from_peer(&music, version)); assert_eq!(playback_command_allowed_from_peer(&podcasts, version), v4); // Stamped playback command operations. let command = |state: &PlaybackStateWire| SyncOpPayload::PlaybackCommand { target_device_id: "d".into(), command: PlaybackCommand::ActiveChanged { active_device_id: "d".into(), active_device_name: "D".into(), state: state.clone(), }, authority: None, }; assert!(op_allowed_for_peer(&command(&music), version)); assert_eq!(op_allowed_for_peer(&command(&podcasts), version), v4); } } #[test] fn browser_state_gating_sees_podcast_items() { let with_podcast = serde_json::json!({ "tracks": [ {"id": 5, "title": "Library song"}, queue_items::external_track_json(&PlaybackTrack::podcast_episode(test_episode()), 1, None), ], "index": 0, }); let shadow = browser_state_shadow(&with_podcast); assert!(!playback_command_allowed_from_peer(&shadow, 3)); assert!(playback_command_allowed_from_peer(&shadow, 4)); let music_only = serde_json::json!({"tracks": [{"id": 5}], "index": 0}); assert!(playback_command_allowed_from_peer( &browser_state_shadow(&music_only), 3 )); } #[test] fn relayed_versions_never_downgrade_and_self_reports_replace() { let profile = |id: &str, version: u16| DeviceProfileWire { device_id: id.into(), name: "D".into(), client_version: "x".into(), protocol_version: version, endpoint_id: String::new(), endpoint_ticket: String::new(), revoked: false, revoke_cutoff_seq: None, updated_at_ms: 0, }; // A v3 relay lists every device with its own constant. let relayed = VersionReport::for_listed(&profile("tui_b", 3), Some("tui_a")); assert_eq!(relayed, VersionReport::Relayed(3)); assert_eq!(relayed.resolve(Some(4)), 4); assert_eq!(relayed.resolve(None), 3); assert_eq!(VersionReport::Relayed(4).resolve(Some(3)), 4); // The sender's own entry is a self-report and may lower the version. let own = VersionReport::for_listed(&profile("tui_a", 3), Some("tui_a")); assert_eq!(own, VersionReport::SelfReported(Some(3))); assert_eq!(own.resolve(Some(4)), 3); // Profiles without a version (pending pairing, pre-v4 DeviceProfileSet) // keep the stored value, or the unreported version 1. assert_eq!(VersionReport::SelfReported(None).resolve(Some(4)), 4); assert_eq!(VersionReport::SelfReported(None).resolve(None), 1); } #[test] fn podcast_snapshot_sections_are_bounded_per_message() { let mut snapshot = SyncSnapshot::default(); let progress = music_dht::podcast::ProgressRecord { episode_id: episode_id(), podcast_id: podcast_id(), position_ms: 1, status: ProgressStatus::InProgress, generation: 1, session_id: "s".into(), hlc_ms: 1, device_id: "tui_a".into(), op_id: "tui_a:1".into(), }; snapshot.podcast_progress = vec![progress; 10]; // Large other parts leave (almost) no budget for podcast sections. let big_title = "x".repeat(music_dht::device_sync::MAX_SYNC_LINE - 16 * 1024); let mut message = WireMessage::Hello { group_id: "g".into(), profile: DeviceProfileWire { device_id: "web".into(), name: big_title, client_version: String::new(), protocol_version: PROTOCOL_VERSION, endpoint_id: String::new(), endpoint_ticket: String::new(), revoked: false, revoke_cutoff_seq: None, updated_at_ms: 0, }, devices: vec![], vector: BTreeMap::new(), ops: vec![], snapshot: snapshot.clone(), playback: None, }; fit_podcast_snapshot(&mut message); let WireMessage::Hello { snapshot: fitted, .. } = &message else { unreachable!() }; assert!(fitted.podcast_progress.is_empty()); let mut small = WireMessage::SyncResponse { accepted: true, error: None, devices: vec![], vector: BTreeMap::new(), ops: vec![], snapshot, playback: None, }; fit_podcast_snapshot(&mut small); let WireMessage::SyncResponse { snapshot, .. } = &small else { unreachable!() }; assert_eq!(snapshot.podcast_progress.len(), 10); } /// Pool that is never connected: the bridge paths under test resolve /// podcast items, placeholders and inline content ids without queries. fn offline_pool() -> sqlx::PgPool { sqlx::postgres::PgPoolOptions::new() .connect_lazy("postgres://offline@127.0.0.1:1/offline") .unwrap() } #[tokio::test] async fn podcast_queue_survives_server_browser_server_round_trip() { let pool = offline_pool(); let mut other = test_episode(); other.episode_title = "Episode 43".into(); other.episode_id = EpisodeId::from_guid(&other.podcast_id, "episode-43").unwrap(); let mut unresolved = music_track(0); unresolved.title = "Remote song".into(); let queue = vec![ PlaybackTrack::podcast_episode(test_episode()), PlaybackTrack::private_placeholder(), unresolved, PlaybackTrack::podcast_episode(other), ]; let mut incoming = state(queue.clone()); incoming.queue_pos = 3; incoming.paused = true; // peer -> server -> browser let payload = web_playback_payload(&pool, &incoming).await.unwrap(); let tracks = payload["tracks"].as_array().unwrap(); assert_eq!(tracks.len(), 4, "no item is dropped"); assert_eq!(payload["index"], 3); assert_eq!(tracks[0]["source"]["kind"], "podcast_episode"); assert_eq!(tracks[0]["unavailable"], true); assert_eq!(tracks[1]["source"]["kind"], "private"); // The browser keeps its queue and sends it back (plus a library track // it added at the end, with its content id inline). let mut browser: serde_json::Value = serde_json::from_str(&payload.to_string()).unwrap(); browser["tracks"] .as_array_mut() .unwrap() .push(serde_json::json!({ "id": 77, "title": "Library song", "content_id": CONTENT_ID, "duration_seconds": 100.0, "artists": [{"id": 1, "name": "A"}], "release_id": 9, "release_title": "Album", })); // browser -> server -> peer let outgoing = playback_state_from_browser_json(&pool, browser) .await .unwrap(); assert_eq!(outgoing.queue[..4], queue[..]); assert_eq!(outgoing.queue_pos, 3); assert!(outgoing.paused); let library = &outgoing.queue[4]; assert_eq!(library.id, 77); assert_eq!(library.content_id.as_deref(), Some(CONTENT_ID)); assert_eq!(library.source, None); // Library music keeps the v3 shape. assert!(!serde_json::to_string(library).unwrap().contains("source")); // Peers below v4 get no playback snapshot with these items. assert!(!playback_allowed_for_peer(&outgoing, 3)); assert!(playback_allowed_for_peer(&outgoing, 4)); } #[tokio::test] async fn malformed_browser_items_keep_the_position_on_its_item() { let pool = offline_pool(); let browser = serde_json::json!({ "tracks": [ {"title": "no id"}, {"id": 5, "content_id": CONTENT_ID}, {"id": 6, "content_id": CONTENT_ID}, ], "index": 2, "track": {"id": 6}, }); let wire = playback_state_from_browser_json(&pool, browser) .await .unwrap(); assert_eq!(wire.queue.len(), 2); assert_eq!(wire.queue[wire.queue_pos].id, 6); }