diff --git a/docs/development.md b/docs/development.md index f87d3ff..7bb4238 100644 --- a/docs/development.md +++ b/docs/development.md @@ -71,7 +71,7 @@ cargo test devices:: queue_items podcast_relay queue_persistence node --test tests/player_queue_sources.test.cjs # Migrated disposable PostgreSQL (start the server against it once): FURU_DEVICE_SYNC_TEST_DATABASE_URL=postgresql://... \ - cargo test postgres_podcast_relay_gating_and_peer_versions -- --ignored + cargo test devices::postgres_tests -- --ignored FURU_METADATA_FIX_TEST_DATABASE_URL=postgresql://... \ cargo test undo_accepts_playback_archives_written_before_the_typed_queue -- --ignored ``` diff --git a/src/federation/devices/postgres_tests.rs b/src/federation/devices/postgres_tests.rs index 5bdfdc6..4d50f56 100644 --- a/src/federation/devices/postgres_tests.rs +++ b/src/federation/devices/postgres_tests.rs @@ -319,6 +319,156 @@ async fn postgres_podcast_relay_gating_and_peer_versions() { cleanup(&pool, user_id).await; } +#[tokio::test] +#[ignore = "requires a migrated disposable database in FURU_DEVICE_SYNC_TEST_DATABASE_URL"] +async fn postgres_unknown_episode_position_and_rollback_cleanup() { + let pool = sqlx::PgPool::connect(&std::env::var("FURU_DEVICE_SYNC_TEST_DATABASE_URL").unwrap()) + .await + .unwrap(); + let user_id = 8_000_000_000 + i64::from(rand_suffix()); + cleanup(&pool, user_id).await; + let tui = format!("tui_{user_id}"); + ensure_identity(&pool, user_id, "tester").await.unwrap(); + apply_device_profile( + &pool, + user_id, + &profile(&tui, 4), + VersionReport::SelfReported(Some(4)), + true, + ) + .await + .unwrap(); + + // The TUI left the episode at 1200 s (generation 9; queue items saw 7). + let episode = test_episode(); + let hub = Arc::new(PlayerDeviceHub::default()); + apply_ops( + &pool, + Arc::clone(&hub), + user_id, + vec![op( + &tui, + 1, + 10, + SyncOpPayload::PodcastProgressSet { + episode_id: episode.episode_id.clone(), + podcast_id: episode.podcast_id.clone(), + position_ms: 1_200_000, + status: ProgressStatus::InProgress, + generation: 9, + session_id: "s9".into(), + episode: None, + }, + )], + ) + .await + .unwrap(); + + // The web player reached the episode by Next and does not know where it + // was left; it hands playback to the TUI. + let song = serde_json::json!({ + "id": 77, "title": "Library song", "content_id": format!("b3:{}", "4".repeat(64)), + "duration_seconds": 300.0, + }); + let item = crate::player::queue_items::external_track_json( + &PlaybackTrack::podcast_episode(episode.clone()), + 1, + None, + ); + let browser = serde_json::json!({ + "tracks": [song.clone(), item.clone()], "index": 1, "track": item.clone(), + "position_seconds": 0.0, "paused": true, "position_unknown": true, + }); + record_web_active_transfer(&pool, user_id, &tui, None, browser) + .await + .unwrap(); + let sent: serde_json::Value = sqlx::query_scalar( + "SELECT payload_json FROM furumusic__fed_sync_ops + WHERE user_id = $1 AND kind = 'playback_command' ORDER BY seq DESC LIMIT 1", + ) + .bind(user_id) + .fetch_one(&pool) + .await + .unwrap(); + let SyncOpPayload::PlaybackCommand { + command: PlaybackCommand::ActiveChanged { state, .. }, + .. + } = serde_json::from_value(sent).unwrap() + else { + panic!("expected ActiveChanged"); + }; + assert_eq!(state.position_secs, 1200.0, "never 0"); + assert_eq!( + state.queue[1] + .podcast_episode_ref() + .unwrap() + .progress_generation, + Some(9) + ); + + // Remote Next onto the episode while the TUI plays the song. + let current = serde_json::json!({ + "tracks": [song, item], "index": 0, "track": song, + "position_seconds": 200.0, "paused": false, + }); + let next = record_web_playback_command( + &pool, + user_id, + &tui, + "next", + serde_json::json!({}), + Some(current), + ) + .await + .unwrap(); + assert_eq!(next["index"], 1); + assert_eq!(next["position_seconds"], 1200.0); + assert!( + next.get(crate::player::queue_items::POSITION_UNKNOWN_KEY) + .is_none() + ); + + // Rollback to 0.12: its types fail on the relayed podcast operation, and + // parse everything once the documented cleanup ran. + let parse_like_0_12 = |rows: Vec| { + rows.into_iter() + .map(serde_json::from_value::) + .collect::, _>>() + }; + let rows = || async { + sqlx::query_scalar::<_, serde_json::Value>( + "SELECT payload_json FROM furumusic__fed_sync_ops WHERE user_id = $1", + ) + .bind(user_id) + .fetch_all(&pool) + .await + .unwrap() + }; + assert!(parse_like_0_12(rows().await).is_err()); + sqlx::query(&format!( + "{} AND user_id = $1", + crate::music::db_migrations::DELETE_PODCAST_SYNC_OPS_SQL + )) + .bind(user_id) + .execute(&pool) + .await + .unwrap(); + let remaining = parse_like_0_12(rows().await).unwrap(); + // The playback commands (with the episode's `source`) stay readable. + assert_eq!( + remaining + .iter() + .filter(|payload| matches!( + payload, + super::wire_compat_tests::legacy::SyncOpPayload::PlaybackCommand { .. } + )) + .count(), + 2 + ); + + cleanup(&pool, user_id).await; +} + fn rand_suffix() -> u32 { u32::from_le_bytes( blake3::hash(random_hex(8).as_bytes()).as_bytes()[..4] diff --git a/src/federation/devices/wire_compat_tests.rs b/src/federation/devices/wire_compat_tests.rs index 176967a..36f7ac8 100644 --- a/src/federation/devices/wire_compat_tests.rs +++ b/src/federation/devices/wire_compat_tests.rs @@ -8,7 +8,7 @@ use super::*; /// Private wire types of furumi-web 0.12.4 (`src/federation/devices.rs`), /// copied verbatim apart from visibility and `PartialEq`. #[allow(dead_code)] -mod legacy { +pub(super) mod legacy { use music_dht::device_sync::ListenEvent; use music_dht::playback::CommandStamp; use serde::{Deserialize, Serialize}; diff --git a/src/music/mod.rs b/src/music/mod.rs index fcd4de3..8295f96 100644 --- a/src/music/mod.rs +++ b/src/music/mod.rs @@ -2908,15 +2908,19 @@ pub mod db_migrations { Ok(()) } + /// Removes the operations a 0.12.x release cannot parse: the podcast + /// kinds relayed since device-sync protocol 4. Ends with its `WHERE` + /// clause, so tests can narrow it to one user. + pub(crate) const DELETE_PODCAST_SYNC_OPS_SQL: &str = + "DELETE FROM furumusic__fed_sync_ops WHERE kind LIKE 'podcast\\_%'"; + // Release 0.12.x parses every unacknowledged operation it sends to a // peer and fails the whole batch on an unknown kind, so the podcast // operations relayed by 0.13 must go before it runs again (see // docs/administration.md, "Rolling back to 0.12"). #[cot::db::migrations::migration_op] async fn drop_fed_podcast_relay(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> { - ctx.db - .raw("DELETE FROM furumusic__fed_sync_ops WHERE kind LIKE 'podcast\\_%'") - .await?; + ctx.db.raw(DELETE_PODCAST_SYNC_OPS_SQL).await?; ctx.db .raw("DROP TABLE IF EXISTS furumusic__fed_podcast_relay") .await?;