From 4d6a1513d9f8f0f726bab0c09d17ac14dd5e1b7b Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 26 Nov 2026 17:46:47 +0200 Subject: [PATCH] Publish matched import entries into private playlists over Device Sync Each source playlist gets an ordinary private playlist, created with its PlaylistCreated operation in one transaction even when nothing matched. Matched entries follow in source order, at most 200 per transaction: the playlist row, the item register, the existing PlaylistTrackAdded operation and a receipt are written together, so fed_sync_ops serves as the outbox and an interrupted batch leaves nothing behind. Locks are taken in a fixed order (per-user advisory lock, import lease, playlist, fed-device identity, registers). Registers are only inserted; an item the playlist has or had, a removal committed to the journal but not yet applied, a repeat or a receipt keep the publisher from adding it again. A deleted target pauses publication until POST .../playlists/{pid}/recreate; POST .../resync retries unmatched entries and appends new matches at the end. Before each batch the outgoing Device Sync line is measured by serializing the same parts the exchange sends. Tracks and new playlists are published while the music snapshot stays within library_import_sync_budget (2 MiB) and the whole line within 7 MiB; the rest waits as deferred_sync_limit. Device Sync gets local helpers only: create_owned_playlist_tx is extracted from the playlist handler, append_in_transaction takes an explicit position, the two operations have in-transaction variants on append_local_op, and applying a playlist item writes its register under an atomic last-writer-wins condition and its playlist row in the same transaction, so concurrent operations cannot make them diverge. The protocol and its formats are unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/administration.md | 19 + docs/development.md | 12 + src/config.rs | 8 + src/federation/devices.rs | 246 ++++- src/import_playlists.rs | 34 +- src/library_import/handlers.rs | 103 +- src/library_import/job.rs | 53 +- src/library_import/mod.rs | 1 + src/library_import/publisher.rs | 1050 +++++++++++++++++++++ src/library_import/store.rs | 461 +++++++++ src/library_import/tests.rs | 62 +- src/library_import/tests/publisher.rs | 1260 +++++++++++++++++++++++++ src/player/mod.rs | 52 +- 13 files changed, 3316 insertions(+), 45 deletions(-) create mode 100644 src/library_import/publisher.rs create mode 100644 src/library_import/tests/publisher.rs diff --git a/docs/administration.md b/docs/administration.md index 5490bd4..9fff163 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -150,6 +150,25 @@ Doubtful entries keep up to five candidates. The import page lets the owner pick one; the choice is checked against the stored candidates and published like an automatic match. +Each source playlist becomes an ordinary private playlist, created even when +nothing matched; Liked Songs becomes "Liked Songs (Spotify)". Matches are added +in source order without repeats and reach paired devices through the usual +Device Sync operations; unmatched entries stay in the import. Every added track +is recorded together with its playlist row and its sync operation in one +transaction, so an interrupted import never leaves half of it behind. **Retry +unmatched** searches again and appends new matches at the end. Tracks the user +added or removed in the playlist, on any device, are left as they are, and a +deleted target playlist pauses publication until the owner asks to recreate it. + +Device Sync sends every playlist item in each exchange and receivers reject +lines over 8 MiB, so the import limits its share. Before each batch it measures +the line the server would send: tracks are published while the music part of +the sync snapshot stays within **2 MiB** and the whole line within 7 MiB; new +playlists count as well. Set `FURU_LIBRARY_IMPORT_SYNC_BUDGET` (bytes) to change +the 2 MiB budget. Tracks beyond it wait as "deferred" and are published by a +later **Retry unmatched** when there is room again. About 3,000 federated +tracks take 1.6 MiB. + ## Federation Federation is optional. Independent Furumusic and Furumi players that use the diff --git a/docs/development.md b/docs/development.md index 4dfcd9b..c702da0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -169,6 +169,18 @@ pass, a stopped node, manual choices with tampered candidates, and cancellation that leaves no catalogue request running. The database needs the `pg_trgm` extension; the tests install it into `public`. +The publisher tests (`src/library_import/tests/publisher.rs`) run against the +Device Sync tables of the same schema. They cover source order, repeats, empty +playlists, a second pass that adds nothing, Resync appending at the end, tracks +removed by the user or by a committed but not yet applied operation, deleted +target playlists and recreation, an entry failing after its operation was +recorded, registers written concurrently, deletions from the web and from +another device during a batch, older operations that arrive during a batch, +concurrent operations that must keep registers and playlist rows consistent, +two imports of one user publishing in turn, and the Device Sync budget for +tracks and playlists. `library_import_measures_the_outgoing_device_sync_line` +prints the measured line for 3,200 published tracks with `--nocapture`. + `cargo test federation::client` checks bounded artist catalogue lookups without a database: at most 16 owners and the given number of parallel requests, timeouts, errors, oversized catalogues, and that dropping a lookup stops its search and diff --git a/src/config.rs b/src/config.rs index 84eb246..46b5356 100644 --- a/src/config.rs +++ b/src/config.rs @@ -153,6 +153,7 @@ pub struct ConfigSources { pub youtube_cookie_id: ConfigSource, pub spotify_client_id: ConfigSource, pub spotify_redirect_uri: ConfigSource, + pub library_import_sync_budget: ConfigSource, } impl Default for ConfigSources { @@ -198,6 +199,7 @@ impl Default for ConfigSources { youtube_cookie_id: ConfigSource::Default, spotify_client_id: ConfigSource::Default, spotify_redirect_uri: ConfigSource::Default, + library_import_sync_budget: ConfigSource::Default, } } } @@ -425,6 +427,9 @@ pub struct AppConfig { /// Redirect URI registered in the Spotify application. Empty means /// `/api/imports/providers/spotify/callback`. pub spotify_redirect_uri: String, + /// Bytes of the Device Sync music snapshot up to which a library import + /// publishes tracks; the rest waits as `deferred_sync_limit`. + pub library_import_sync_budget: u64, } impl Default for AppConfig { @@ -473,6 +478,7 @@ impl Default for AppConfig { youtube_cookie_id: String::new(), spotify_client_id: String::new(), spotify_redirect_uri: String::new(), + library_import_sync_budget: 2 * 1024 * 1024, } } } @@ -519,6 +525,7 @@ impl_env_overrides!( youtube_cookie_id, spotify_client_id, spotify_redirect_uri, + library_import_sync_budget, ); impl AppConfig { @@ -666,6 +673,7 @@ impl AppConfig { apply_db_field!(youtube_cookie_id); apply_db_field!(spotify_client_id); apply_db_field!(spotify_redirect_uri); + apply_db_field!(library_import_sync_budget); } pub fn parsed_download_proxies(&self) -> anyhow::Result> { diff --git a/src/federation/devices.rs b/src/federation/devices.rs index eddb3a6..3c75451 100644 --- a/src/federation/devices.rs +++ b/src/federation/devices.rs @@ -1903,6 +1903,208 @@ pub(crate) async fn record_podcast_op( Ok(()) } +/// Device id of the user's web fed-device, created on first use. Callers +/// that record operations inside their own transaction read it beforehand. +pub(crate) async fn local_device_id(pool: &sqlx::PgPool, user_id: i64) -> Result { + Ok(ensure_identity(pool, user_id, "").await?.device_id) +} + +/// Sync id of a playlist created by [`record_playlist_created_in_tx`]. +pub(crate) fn local_playlist_sync_id_for(user_id: i64, playlist_id: i64) -> String { + format!("webpl_{user_id}_{playlist_id}") +} + +/// `PlaylistCreated` for a playlist inserted in the caller's transaction, +/// with the playlist register written in the same transaction; the same state +/// that `record_playlist_created` reaches after its own commit. Returns the +/// sync id. +pub(crate) async fn record_playlist_created_in_tx( + conn: &mut sqlx::PgConnection, + user_id: i64, + device_id: &str, + playlist_id: i64, + title: &str, +) -> Result { + let sync_id = local_playlist_sync_id_for(user_id, playlist_id); + let op = append_local_op( + &mut *conn, + user_id, + device_id.to_string(), + SyncOpPayload::PlaylistCreated { + playlist_id: sync_id.clone(), + title: title.to_string(), + }, + ) + .await?; + sqlx::query( + "INSERT INTO furumusic__fed_state_playlist + (user_id, playlist_id, local_playlist_id, title, deleted, hlc_ms, op_id) + VALUES ($1, $2, $3, $4, false, $5, $6) + ON CONFLICT (user_id, playlist_id) DO UPDATE SET + local_playlist_id = EXCLUDED.local_playlist_id, + title = EXCLUDED.title, + deleted = false, + hlc_ms = EXCLUDED.hlc_ms, + op_id = EXCLUDED.op_id", + ) + .bind(user_id) + .bind(&sync_id) + .bind(playlist_id) + .bind(title) + .bind(op.hlc_ms) + .bind(&op.op_id) + .execute(&mut *conn) + .await?; + Ok(sync_id) +} + +/// `PlaylistTrackAdded` in the caller's transaction, with the item register. +/// The register is only inserted, never overwritten: when a row for this +/// `content_id` exists (a concurrent operation was applied meanwhile) the +/// result is `None` and the caller must roll back, which also drops the +/// operation. Otherwise returns the operation id. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn record_playlist_track_added_in_tx( + conn: &mut sqlx::PgConnection, + user_id: i64, + device_id: &str, + sync_id: &str, + content_id: &str, + position: i64, + fed: &SyncedFedTrack, + local_track_id: Option, +) -> Result> { + let content_id = + music_dht::normalize_content_id(content_id).context("invalid track content id")?; + let op = append_local_op( + &mut *conn, + user_id, + device_id.to_string(), + SyncOpPayload::PlaylistTrackAdded { + playlist_id: sync_id.to_string(), + content_id: content_id.clone(), + position, + fed: Some(fed.clone()), + }, + ) + .await?; + let inserted = sqlx::query( + "INSERT INTO furumusic__fed_state_playlist_item + (user_id, playlist_id, content_id, present, position, hlc_ms, op_id, + local_track_id, fed_json) + VALUES ($1, $2, $3, true, $4, $5, $6, $7, $8) + ON CONFLICT (user_id, playlist_id, content_id) DO NOTHING", + ) + .bind(user_id) + .bind(sync_id) + .bind(&content_id) + .bind(position) + .bind(op.hlc_ms) + .bind(&op.op_id) + .bind(local_track_id) + .bind(serde_json::to_value(fed)?) + .execute(&mut *conn) + .await? + .rows_affected(); + Ok((inserted == 1).then_some(op.op_id)) +} + +/// Size of the Device Sync line the web player would send now. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct OutgoingSyncSize { + /// Longest `Hello` line over the trusted devices, newline included. + pub full_line: u64, + /// Serialized snapshot without its podcast sections. + pub music_snapshot: u64, +} + +/// Measures the outgoing Device Sync line by serializing the same parts that +/// `sync_device` sends, with the same `serde_json::to_vec` as `write_msg`: +/// for every trusted device its snapshot, pending operations and playback, +/// plus the device profiles and the vector. Without devices a virtual peer of +/// the current protocol version stands in. Nothing is written except the +/// periodic local seed that every snapshot runs; playback coordination, +/// which has side effects and stays small, is left out. +pub(crate) async fn outgoing_sync_line_size( + pool: &sqlx::PgPool, + user_id: i64, +) -> Result { + let identity = ensure_identity(pool, user_id, "").await?; + let snapshot = snapshot(pool, user_id).await?; + let mut music = snapshot.clone(); + music.strip_podcast_state(); + let music_snapshot = serde_json::to_vec(&music)?.len() as u64; + let devices = device_profiles(pool, user_id).await?; + let profile = devices + .iter() + .find(|device| device.device_id == identity.device_id) + .cloned() + .map(|mut profile| { + profile.client_version = CLIENT_VERSION.to_string(); + profile.protocol_version = PROTOCOL_VERSION; + profile + }) + .unwrap_or_else(|| DeviceProfileWire { + device_id: identity.device_id.clone(), + name: identity.name.clone(), + client_version: CLIENT_VERSION.to_string(), + protocol_version: PROTOCOL_VERSION, + endpoint_id: String::new(), + endpoint_ticket: String::new(), + revoked: false, + revoke_cutoff_seq: None, + updated_at_ms: now_ms(), + }); + let vector = vector(pool, user_id).await?; + let state = PlayerDeviceHub::shared() + .playback_state_json_for_commands(user_id) + .unwrap_or_else(|| serde_json::json!({})); + let playback = PlaybackSnapshot { + device_id: identity.device_id.clone(), + device_name: identity.name.clone(), + active: false, + updated_at_ms: now_ms(), + state: playback_state_from_browser_json(pool, state).await?, + coordination: None, + }; + let mut peers = Vec::new(); + for device in active_remote_devices(pool, user_id).await? { + let version = peer_protocol_version(pool, user_id, &device.device_id).await?; + peers.push((device.device_id, version)); + } + if peers.is_empty() { + peers.push((String::new(), PROTOCOL_VERSION)); + } + let mut full_line = 0; + for (device_id, version) in peers { + let message = WireMessage::Hello { + group_id: identity.group_id.clone(), + profile: profile.clone(), + devices: devices.clone(), + vector: vector.clone(), + ops: ops_for_peer_version(pool, user_id, &device_id, version).await?, + snapshot: snapshot.for_peer(version), + playback: music_dht::device_sync::playback_allowed_for_peer(&playback.state, version) + .then(|| playback.clone()), + }; + full_line = full_line.max(serde_json::to_vec(&message)?.len() as u64 + 1); + } + Ok(OutgoingSyncSize { + full_line, + music_snapshot, + }) +} + +/// Applies operations received from a paired device, as an exchange does. +#[cfg(test)] +pub(crate) async fn apply_received_ops( + pool: &sqlx::PgPool, + user_id: i64, + ops: Vec, +) -> Result<()> { + apply_ops(pool, Arc::new(PlayerDeviceHub::default()), user_id, ops).await +} + async fn apply_ops( pool: &sqlx::PgPool, hub: Arc, @@ -2400,7 +2602,13 @@ async fn apply_playlist_item_state( local_playlist_id_by_sync_id(pool, user_id, playlist_id).await? }; let fed_json = fed.cloned().map(serde_json::to_value).transpose()?; - sqlx::query( + // The register and the materialized row change in one transaction. The + // conditional upsert keeps last-writer-wins atomic: it locks the register + // row, so a concurrent write of the same item (another operation or the + // library import publisher) waits and is then compared with this one. + // `playlist_track` follows in the same order as the register. + let mut tx = pool.begin().await?; + let changed = sqlx::query( "INSERT INTO furumusic__fed_state_playlist_item (user_id, playlist_id, content_id, present, position, hlc_ms, op_id, local_track_id, fed_json) @@ -2411,7 +2619,10 @@ async fn apply_playlist_item_state( hlc_ms = EXCLUDED.hlc_ms, op_id = EXCLUDED.op_id, local_track_id = EXCLUDED.local_track_id, - fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_playlist_item.fed_json)", + fed_json = COALESCE(EXCLUDED.fed_json, furumusic__fed_state_playlist_item.fed_json) + WHERE (furumusic__fed_state_playlist_item.hlc_ms, + furumusic__fed_state_playlist_item.op_id COLLATE \"C\") + < (EXCLUDED.hlc_ms, EXCLUDED.op_id COLLATE \"C\")", ) .bind(user_id) .bind(playlist_id) @@ -2422,8 +2633,13 @@ async fn apply_playlist_item_state( .bind(op_id) .bind(local_track_id) .bind(fed_json) - .execute(pool) - .await?; + .execute(&mut *tx) + .await? + .rows_affected(); + if changed == 0 { + tx.rollback().await?; + return Ok(false); + } if let (Some(local_playlist_id), Some(track_id)) = (local_playlist_id, local_track_id) { if present { let exists: Option = sqlx::query_scalar( @@ -2433,7 +2649,7 @@ async fn apply_playlist_item_state( ) .bind(local_playlist_id) .bind(track_id) - .fetch_optional(pool) + .fetch_optional(&mut *tx) .await?; if exists.is_none() { sqlx::query( @@ -2446,7 +2662,7 @@ async fn apply_playlist_item_state( .bind(position as i32) .bind(iso_from_ms(hlc_ms)) .bind(user_id) - .execute(pool) + .execute(&mut *tx) .await?; } else { sqlx::query( @@ -2457,7 +2673,7 @@ async fn apply_playlist_item_state( .bind(local_playlist_id) .bind(track_id) .bind(position as i32) - .execute(pool) + .execute(&mut *tx) .await?; } } else { @@ -2467,10 +2683,11 @@ async fn apply_playlist_item_state( ) .bind(local_playlist_id) .bind(track_id) - .execute(pool) + .execute(&mut *tx) .await?; } } + tx.commit().await?; Ok(true) } @@ -4011,7 +4228,7 @@ async fn track_content_id(pool: &sqlx::PgPool, track_id: i64) -> Result Result> { let peer_version = peer_protocol_version(pool, user_id, peer_device_id).await?; + ops_for_peer_version(pool, user_id, peer_device_id, peer_version).await +} + +async fn ops_for_peer_version( + pool: &sqlx::PgPool, + user_id: i64, + peer_device_id: &str, + peer_version: u16, +) -> Result> { let rows = sqlx::query( "SELECT o.op_id, o.origin_device_id, o.seq, o.hlc_ms, o.payload_json FROM furumusic__fed_sync_ops o @@ -4857,6 +5083,8 @@ fn payload_kind(payload: &SyncOpPayload) -> &'static str { async fn write_msg(stream: &mut ByteStream, message: &WireMessage) -> Result<()> { let mut payload = serde_json::to_vec(message)?; payload.push(b'\n'); + // Compared with `outgoing_sync_line_size`, which measures the same line. + tracing::debug!(bytes = payload.len(), "device sync line written"); stream.send.write_all(&payload).await?; Ok(()) } diff --git a/src/import_playlists.rs b/src/import_playlists.rs index efc866d..8cc158b 100644 --- a/src/import_playlists.rs +++ b/src/import_playlists.rs @@ -86,7 +86,8 @@ pub async fn reconcile(pool: &PgPool, user_id: Option) -> anyhow::Result<() } let mut added = Vec::new(); for track_id in track_ids { - if append_in_transaction(&mut transaction, user_id, playlist_id, track_id).await? { + if append_in_transaction(&mut transaction, user_id, playlist_id, track_id, None).await? + { added.push(track_id); } } @@ -109,7 +110,8 @@ pub(crate) async fn append_track_to_target_playlist( track_id: i64, ) -> anyhow::Result { let mut transaction = pool.begin().await?; - let added = append_in_transaction(&mut transaction, user_id, playlist_id, track_id).await?; + let added = + append_in_transaction(&mut transaction, user_id, playlist_id, track_id, None).await?; transaction.commit().await?; if added { record_added(pool, user_id, playlist_id, &[track_id]).await; @@ -117,11 +119,16 @@ pub(crate) async fn append_track_to_target_playlist( Ok(added) } -async fn append_in_transaction( +/// Appends a track the playlist does not contain yet, under the playlist's +/// row lock. `position` places it explicitly; `None` appends after the last +/// track. Returns `false` when the playlist is gone or not the user's, or +/// already contains the track. +pub(crate) async fn append_in_transaction( transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>, user_id: i64, playlist_id: i64, track_id: i64, + position: Option, ) -> anyhow::Result { let playlist: Option = sqlx::query_scalar( r#"SELECT id FROM furumusic__playlist @@ -150,14 +157,19 @@ async fn append_in_transaction( return Ok(false); } - let position: i64 = sqlx::query_scalar( - r#"SELECT COALESCE(MAX(position), -1)::bigint + 1 - FROM furumusic__playlist_track WHERE playlist_id = $1"#, - ) - .bind(playlist_id) - .fetch_one(&mut **transaction) - .await?; - let position = i32::try_from(position).context("target playlist has too many tracks")?; + let position = match position { + Some(position) => position, + None => { + let position: i64 = sqlx::query_scalar( + r#"SELECT COALESCE(MAX(position), -1)::bigint + 1 + FROM furumusic__playlist_track WHERE playlist_id = $1"#, + ) + .bind(playlist_id) + .fetch_one(&mut **transaction) + .await?; + i32::try_from(position).context("target playlist has too many tracks")? + } + }; let now = now_string(); sqlx::query( r#"INSERT INTO furumusic__playlist_track diff --git a/src/library_import/handlers.rs b/src/library_import/handlers.rs index 8a9e931..a1965be 100644 --- a/src/library_import/handlers.rs +++ b/src/library_import/handlers.rs @@ -29,7 +29,7 @@ use super::providers::spotify_api::{self, AuthState, AuthStateError, SpotifyClie use super::providers::{Connection, FetchError, TokenVault}; use super::store::{ self, CancelOutcome, ChooseOutcome, CreateImportError, DeleteOutcome, ItemFilter, NewImport, - NewPlaylist, ReauthOutcome, ReauthTarget, + NewPlaylist, ReauthOutcome, ReauthTarget, RecreateOutcome, ResyncOutcome, }; use crate::auth; use crate::config::AppConfig; @@ -150,6 +150,70 @@ async fn choose(services: &Services, user_id: i64, path: &ItemPath, request: Req } } +/// `POST /api/imports/{id}/resync`. +#[derive(Debug, Default, Deserialize)] +struct ResyncRequest { + /// Replaces the consent to federated search when given. + #[serde(default)] + federated_search: Option, +} + +async fn resync( + services: &Services, + user_id: i64, + path: &ImportPath, + request: Request, +) -> Response { + let Some(import_id) = import_id(path) else { + return not_found(); + }; + let body: ResyncRequest = match read_json(request).await { + Ok(body) => body, + Err(rejection) => return rejection.respond(), + }; + let pool = services.pool().await?; + match store::request_resync(&pool, user_id, import_id, body.federated_search).await { + Ok(ResyncOutcome::Queued) => { + services.start_worker().await; + ok(json!({ "status": "queued" })) + } + Ok(ResyncOutcome::NotFinished) => error( + StatusCode::CONFLICT, + "the import is still running; wait for it to finish", + ), + Ok(ResyncOutcome::NotFound) => not_found(), + Err(error) => storage_error(&error), + } +} + +#[derive(Deserialize)] +struct PlaylistPath { + id: String, + playlist_id: String, +} + +async fn recreate(services: &Services, user_id: i64, path: &PlaylistPath) -> Response { + let (Some(import_id), Some(playlist_id)) = + (positive_id(&path.id), positive_id(&path.playlist_id)) + else { + return not_found(); + }; + let pool = services.pool().await?; + match store::recreate_target(&pool, user_id, import_id, playlist_id).await { + Ok(RecreateOutcome::Requested { queued }) => { + if queued { + services.start_worker().await; + } + ok(json!({ "status": "requested" })) + } + Ok(RecreateOutcome::TargetExists) => { + error(StatusCode::CONFLICT, "the target playlist still exists") + } + Ok(RecreateOutcome::NotFound) => error(StatusCode::NOT_FOUND, "playlist not found"), + Err(error) => storage_error(&error), + } +} + #[derive(Default, Deserialize)] struct ItemsQuery { status: Option, @@ -1179,6 +1243,37 @@ impl App for ImportApp { }, ) }; + let resync_route = { + let services = services.clone(); + post( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path, + request: Request| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + resync(&services, user.id, &path, request).await + } + }, + ) + }; + let recreate_route = { + let services = services.clone(); + post( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + Path(path): Path| { + let services = services.clone(); + async move { + let user = require_user!(auth_ctx, session, db); + recreate(&services, user.id, &path).await + } + }, + ) + }; let cancel = post( move |auth_ctx: auth::AuthContext, session: Session, @@ -1228,6 +1323,12 @@ impl App for ImportApp { Route::with_handler_and_name("/{id}", detail, "library_import"), Route::with_handler_and_name("/{id}/items", items, "library_import_items"), Route::with_handler_and_name("/{id}/cancel", cancel, "library_import_cancel"), + Route::with_handler_and_name("/{id}/resync", resync_route, "library_import_resync"), + Route::with_handler_and_name( + "/{id}/playlists/{playlist_id}/recreate", + recreate_route, + "library_import_playlist_recreate", + ), Route::with_handler_and_name( "/{id}/items/{item_id}/match", choose_route, diff --git a/src/library_import/job.rs b/src/library_import/job.rs index 2c91c59..3649299 100644 --- a/src/library_import/job.rs +++ b/src/library_import/job.rs @@ -16,6 +16,7 @@ use sqlx::PgPool; use super::model::Phase; use super::model::ResolutionStatus; use super::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault}; +use super::publisher::{Progress, Publisher, Step}; use super::resolver::{ FEDERATION_BUDGET, FEDERATION_UNAVAILABLE, FederationAccess, GroupOutcome, NetworkSearch, NodeFederation, Resolver, @@ -300,7 +301,11 @@ impl Worker { return Ok(Some(stop)); } } - Phase::Publish => self.publish(import, log).await?, + Phase::Publish => { + if let Some(stop) = self.publish(import, heartbeat, log).await? { + return Ok(Some(stop)); + } + } } store::refresh_statistics(&mut *self.pool.acquire().await?, import.id).await?; } @@ -623,9 +628,49 @@ impl Worker { } } - /// Adds matched entries to the target playlists. - async fn publish(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> { - Ok(()) + /// Adds matched entries to the target playlists, creating each target on + /// the first pass. Cancellation and lease loss are checked between + /// batches; a committed batch stays published. + async fn publish( + &self, + import: &ClaimedImport, + heartbeat: &Heartbeat, + log: &mut JobLog, + ) -> Result> { + let mut publisher = Publisher::new(&self.pool, import, self.run_id, &self.config).await?; + for target in store::publish_targets(&self.pool, import.id).await? { + let mut progress = Progress::new(target); + loop { + if heartbeat.lost() { + return Ok(Some(Stop::LeaseLost)); + } + match store::control(&self.pool, import.id, self.run_id).await? { + Control::Continue => {} + Control::Cancel => return Ok(Some(Stop::Cancelled)), + Control::LeaseLost => return Ok(Some(Stop::LeaseLost)), + } + match publisher.step(&mut progress).await? { + Step::More => {} + Step::Finished => break, + Step::LeaseLost => return Ok(Some(Stop::LeaseLost)), + } + } + } + let report = publisher.report; + log.info(&format!( + "Library import {}: published {} entries into {} new playlists ({} already present, {} repeated, {} deferred by the Device Sync budget, {} without content id, {} failed; {} playlists paused, {} not created within the budget)", + import.id, + report.published, + report.created, + report.already_present, + report.duplicate, + report.deferred, + report.no_content_id, + report.failed, + report.paused_playlists, + report.deferred_playlists + )); + Ok(None) } } diff --git a/src/library_import/mod.rs b/src/library_import/mod.rs index ecd6b9b..b02c461 100644 --- a/src/library_import/mod.rs +++ b/src/library_import/mod.rs @@ -15,6 +15,7 @@ pub mod matcher; #[allow(dead_code)] pub mod model; pub mod providers; +pub mod publisher; pub mod resolver; #[allow(dead_code)] pub mod store; diff --git a/src/library_import/publisher.rs b/src/library_import/publisher.rs new file mode 100644 index 0000000..a870b5f --- /dev/null +++ b/src/library_import/publisher.rs @@ -0,0 +1,1050 @@ +//! Publisher: adds matched entries to ordinary private playlists (plan §7). +//! +//! Every source playlist gets one target playlist, created on its first pass +//! even without matches. Matched entries are added in source order, without +//! repeats, in batches of up to [`BATCH`] entries. One transaction per batch +//! writes the playlist rows, the item registers, the existing Device Sync +//! operations (`furumusic__fed_sync_ops` serves as the outbox: the sender only +//! takes committed operations) and the receipts, so an interrupted batch +//! leaves nothing behind. +//! +//! Lock order inside a batch: per-user advisory lock → import row (lease) → +//! target playlist row → fed-device identity row → item registers. Other +//! writers never nest these locks in another order, so there is no wait cycle. +//! Network access and hashing happen before the transaction. +//! +//! Before each batch the outgoing Device Sync line is measured +//! ([`devices::outgoing_sync_line_size`]); entries that would push the music +//! snapshot over the configured budget or the whole line over +//! [`HARD_LINE_LIMIT`] wait as `deferred_sync_limit`, and so does a whole +//! playlist whose own snapshot entry does not fit. + +use std::collections::{HashMap, HashSet}; + +use anyhow::{Context, Result}; +use music_dht::device_sync::{ + SnapshotPlaylist, SnapshotPlaylistItem, SyncOpPayload, SyncOpWire, SyncedFedTrack, +}; +use sqlx::{PgConnection, PgPool, Row}; + +use super::model::{PlaylistKind, PublicationStatus}; +use super::store::{self, ClaimedImport, PublicationUpdate, PublishEntry, PublishTarget}; +use crate::config::AppConfig; +use crate::federation::devices::{self, OutgoingSyncSize}; + +/// Entries of one source playlist per transaction. +pub const BATCH: usize = 200; +/// Hard stop for the whole outgoing line: the receiver's 8 MiB `MAX_LINE` +/// minus 1 MiB for a growing playback queue and concurrent edits. +pub const HARD_LINE_LIMIT: u64 = 7 * 1024 * 1024; +/// Title length of `furumusic__playlist` (`LimitedString<255>`). +const MAX_TITLE_CHARS: usize = 255; +/// Repeats of a batch whose register was written concurrently. +const BATCH_RETRIES: usize = 3; +/// Row locks the batch waits for at most; other writers of the same user wait for the batch. +const LOCK_TIMEOUT: &str = "SET LOCAL lock_timeout = '5s'"; + +/// What happened during one publish phase, for the job log. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct PublishReport { + pub created: usize, + pub published: usize, + pub already_present: usize, + pub duplicate: usize, + pub deferred: usize, + pub no_content_id: usize, + pub failed: usize, + pub paused_playlists: usize, + pub deferred_playlists: usize, +} + +impl PublishReport { + fn count(&mut self, update: &PublicationUpdate) { + match update.status { + PublicationStatus::Published => self.published += 1, + PublicationStatus::AlreadyPresent => self.already_present += 1, + PublicationStatus::Duplicate => self.duplicate += 1, + PublicationStatus::DeferredSyncLimit => self.deferred += 1, + PublicationStatus::NoContentId => self.no_content_id += 1, + PublicationStatus::Failed => self.failed += 1, + _ => {} + } + } +} + +/// Result of one [`Publisher::step`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Step { + /// More work in this playlist; check cancellation and call again. + More, + /// The playlist needs nothing more in this pass. + Finished, + LeaseLost, +} + +/// Progress through one source playlist. +#[derive(Debug, Clone)] +pub struct Progress { + target: PublishTarget, + after_position: i32, +} + +impl Progress { + pub fn new(target: PublishTarget) -> Self { + Self { + target, + after_position: -1, + } + } +} + +pub struct Publisher<'a> { + pool: &'a PgPool, + import: &'a ClaimedImport, + run_id: i64, + storage_dir: String, + music_budget: u64, + device_id: String, + pub report: PublishReport, +} + +/// An entry checked before the transaction. +#[derive(Debug, Clone)] +struct Record { + item_id: i64, + prepared: Prepared, +} + +#[derive(Debug, Clone)] +enum Prepared { + Ready(Box), + /// Cannot be published in this pass. + Wait { + status: PublicationStatus, + content_id: Option, + }, +} + +#[derive(Debug, Clone)] +struct Ready { + content_id: String, + track_id: Option, + fed: SyncedFedTrack, + /// Serialized `SnapshotPlaylistItem`: stays in every snapshot. + snap_bytes: u64, + /// Serialized `SyncOpWire`: sent until every device has it. + op_bytes: u64, +} + +enum TxEnd { + Committed(Vec), + /// A register was written concurrently or the journal changed: run again. + Retry, + /// The target playlist is deleted. + Paused, + LeaseLost, +} + +enum BatchEnd { + Continue, + Paused, + LeaseLost, +} + +enum Created { + Target(i64), + Deferred, + /// The source playlist got a target meanwhile; the next pass uses it. + Skipped, + LeaseLost, +} + +impl<'a> Publisher<'a> { + pub async fn new( + pool: &'a PgPool, + import: &'a ClaimedImport, + run_id: i64, + config: &AppConfig, + ) -> Result { + Ok(Self { + pool, + import, + run_id, + storage_dir: config.agent_storage_dir.clone(), + music_budget: config.library_import_sync_budget, + device_id: devices::local_device_id(pool, import.user_id).await?, + report: PublishReport::default(), + }) + } + + /// Does the next piece of work for a source playlist: pauses it when its + /// target is deleted, creates the target, or publishes one batch. + pub async fn step(&mut self, progress: &mut Progress) -> Result { + let target = &progress.target; + if target.paused || (target.target_created && target.target_playlist_id.is_none()) { + return self.pause(target.id).await; + } + let target_id = match target.target_playlist_id { + Some(id) => id, + None => { + return Ok(match self.create_target(target).await? { + Created::Target(id) => { + self.report.created += 1; + progress.target.target_playlist_id = Some(id); + progress.target.target_created = true; + Step::More + } + Created::Deferred => { + self.report.deferred_playlists += 1; + Step::Finished + } + Created::Skipped => Step::Finished, + Created::LeaseLost => Step::LeaseLost, + }); + } + }; + let entries = store::publishable_entries( + self.pool, + progress.target.id, + progress.after_position, + BATCH, + ) + .await?; + let Some(last) = entries.last() else { + return Ok(Step::Finished); + }; + progress.after_position = last.position; + let source = progress.target.id; + match self.publish_batch(source, target_id, entries).await? { + BatchEnd::Continue => Ok(Step::More), + BatchEnd::Paused => self.pause(source).await, + BatchEnd::LeaseLost => Ok(Step::LeaseLost), + } + } + + async fn pause(&mut self, source: i64) -> Result { + if !store::pause_playlist(self.pool, self.import.id, self.run_id, source).await? { + return Ok(Step::LeaseLost); + } + self.report.paused_playlists += 1; + Ok(Step::Finished) + } + + fn user_id(&self) -> i64 { + self.import.user_id + } + + /// Takes the per-user publication lock and measures the outgoing line. + /// Publications of one user's imports run strictly one after another, so + /// the measurement stays valid until the commit. Row locks follow and + /// are bounded by the lock timeout. + async fn begin( + &self, + ) -> Result<(sqlx::Transaction<'static, sqlx::Postgres>, OutgoingSyncSize)> { + let mut tx = self.pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(format!("library-import-publish:{}", self.user_id())) + .execute(&mut *tx) + .await?; + sqlx::query(LOCK_TIMEOUT).execute(&mut *tx).await?; + let size = devices::outgoing_sync_line_size(self.pool, self.user_id()).await?; + Ok((tx, size)) + } + + /// Creates the target playlist with its `PlaylistCreated` operation in one + /// transaction, if its snapshot entry fits the budget. + async fn create_target(&self, source: &PublishTarget) -> Result { + let title = target_title(source, &self.import.provider); + let (snap, op) = playlist_costs(self.user_id(), &self.device_id, &title)?; + let (mut tx, size) = self.begin().await?; + if !store::hold_lease(&mut tx, self.import.id, self.run_id).await? { + return Ok(Created::LeaseLost); + } + if !store::lock_untargeted(&mut tx, source.id).await? { + return Ok(Created::Skipped); + } + if !fits(&size, self.music_budget, snap, snap + op) { + store::defer_playlist(&mut tx, source.id).await?; + tx.commit().await?; + return Ok(Created::Deferred); + } + let playlist_id = crate::player::create_owned_playlist_tx( + &mut tx, + self.user_id(), + &title, + source.description.as_deref(), + ) + .await?; + devices::record_playlist_created_in_tx( + &mut tx, + self.user_id(), + &self.device_id, + playlist_id, + &title, + ) + .await?; + store::set_target(&mut tx, source.id, playlist_id).await?; + tx.commit().await?; + Ok(Created::Target(playlist_id)) + } + + /// Publishes a batch in one transaction. When it fails, its entries are + /// published one by one; an entry that fails alone is marked failed and + /// tried again by the next pass. + async fn publish_batch( + &mut self, + source: i64, + target_id: i64, + entries: Vec, + ) -> Result { + let records = self.prepare(target_id, entries).await?; + let mut retries = 0; + loop { + match self.try_batch(source, target_id, &records).await { + Ok(TxEnd::Committed(updates)) => return self.committed(target_id, &updates).await, + Ok(TxEnd::Retry) if retries < BATCH_RETRIES => retries += 1, + Ok(TxEnd::Retry) => break, + Ok(TxEnd::Paused) => return self.paused(target_id).await, + Ok(TxEnd::LeaseLost) => return Ok(BatchEnd::LeaseLost), + Err(error) => { + tracing::warn!( + import_id = self.import.id, + entries = records.len(), + %error, + "library import publication batch failed; publishing its entries one by one" + ); + break; + } + } + } + for record in &records { + let mut retries = 0; + loop { + match self + .try_batch(source, target_id, std::slice::from_ref(record)) + .await + { + Ok(TxEnd::Committed(updates)) => { + match self.committed(target_id, &updates).await? { + BatchEnd::Continue => break, + end => return Ok(end), + } + } + Ok(TxEnd::Retry) if retries < BATCH_RETRIES => retries += 1, + Ok(TxEnd::Paused) => return self.paused(target_id).await, + Ok(TxEnd::LeaseLost) => return Ok(BatchEnd::LeaseLost), + outcome => { + if let Err(error) = outcome { + tracing::warn!( + import_id = self.import.id, + item_id = record.item_id, + %error, + "library import entry could not be published" + ); + } + let update = PublicationUpdate { + item_id: record.item_id, + status: PublicationStatus::Failed, + content_id: None, + failed: true, + }; + if !store::store_publication_owned( + self.pool, + self.import.id, + self.run_id, + std::slice::from_ref(&update), + ) + .await? + { + return Ok(BatchEnd::LeaseLost); + } + self.report.count(&update); + break; + } + } + } + } + Ok(BatchEnd::Continue) + } + + /// After a commit: a deletion from another device may have reached the + /// journal after the batch checked it. Its application removed the + /// playlist rows before our commit added new ones, so they are removed + /// here and publication pauses. + async fn committed( + &mut self, + target_id: i64, + updates: &[PublicationUpdate], + ) -> Result { + for update in updates { + self.report.count(update); + } + let mut conn = self.pool.acquire().await?; + let owned: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM furumusic__playlist WHERE id = $1 AND owner_id = $2)", + ) + .bind(target_id) + .bind(self.user_id()) + .fetch_one(&mut *conn) + .await?; + let deleted = match sync_state(&mut conn, self.user_id(), target_id).await? { + Some((_, deleted)) => deleted, + None => false, + }; + if owned && !deleted { + return Ok(BatchEnd::Continue); + } + drop(conn); + self.paused(target_id).await + } + + /// Removes rows left in a deleted target playlist. + async fn paused(&self, target_id: i64) -> Result { + sqlx::query("DELETE FROM furumusic__playlist_track WHERE playlist_id = $1") + .bind(target_id) + .execute(self.pool) + .await?; + Ok(BatchEnd::Paused) + } + + /// Checks entries and builds their Device Sync metadata outside the + /// transaction. A local match gets its content id from the cache or by + /// hashing its file. + async fn prepare(&self, target_id: i64, entries: Vec) -> Result> { + let sync_id = devices::local_playlist_sync_id_for(self.user_id(), target_id); + let track_ids: Vec = entries + .iter() + .filter(|entry| entry.origin.as_deref() == Some("local")) + .filter_map(|entry| entry.track_id) + .collect(); + let media: HashMap = sqlx::query( + "SELECT t.id, t.audio_file_id FROM furumusic__track t + JOIN furumusic__release r ON r.id = t.release_id + WHERE t.id = ANY($1) AND NOT t.is_hidden AND NOT r.is_hidden", + ) + .bind(&track_ids) + .fetch_all(self.pool) + .await? + .into_iter() + .map(|row| (row.get(0), row.get(1))) + .collect(); + let mut records = Vec::with_capacity(entries.len()); + for entry in entries { + let failed = Prepared::Wait { + status: PublicationStatus::Failed, + content_id: None, + }; + let prepared = match entry.origin.as_deref() { + Some("local") => match entry.track_id.and_then(|id| Some((id, *media.get(&id)?))) { + None => failed, + Some((track_id, media_file_id)) => self + .prepare_local(&sync_id, track_id, media_file_id) + .await + .unwrap_or_else(|error| { + tracing::warn!( + import_id = self.import.id, + item_id = entry.id, + %error, + "library import could not prepare a local match" + ); + failed + }), + }, + Some("federation") => self.prepare_federated(&sync_id, &entry).unwrap_or(failed), + _ => failed, + }; + records.push(Record { + item_id: entry.id, + prepared, + }); + } + Ok(records) + } + + async fn prepare_local( + &self, + sync_id: &str, + track_id: i64, + media_file_id: i64, + ) -> Result { + let Some(content_id) = + crate::federation::ensure_local_content_id(self.pool, &self.storage_dir, media_file_id) + .await? + else { + return Ok(Prepared::Wait { + status: PublicationStatus::NoContentId, + content_id: None, + }); + }; + let Some(fed) = + devices::synced_fed_track_for_track(self.pool, track_id, &content_id).await? + else { + return Ok(Prepared::Wait { + status: PublicationStatus::Failed, + content_id: Some(content_id), + }); + }; + self.ready(sync_id, content_id, Some(track_id), fed) + } + + fn prepare_federated(&self, sync_id: &str, entry: &PublishEntry) -> Option { + let content_id = music_dht::normalize_content_id(entry.content_id.as_deref()?)?; + let fed: SyncedFedTrack = serde_json::from_value(entry.fed.clone()?).ok()?; + let valid = music_dht::normalize_content_id(&fed.content_id).as_deref() + == Some(content_id.as_str()) + && !fed.title.trim().is_empty(); + valid + .then(|| self.ready(sync_id, content_id, None, fed).ok()) + .flatten() + } + + fn ready( + &self, + sync_id: &str, + content_id: String, + track_id: Option, + fed: SyncedFedTrack, + ) -> Result { + let (snap_bytes, op_bytes) = item_costs(&self.device_id, sync_id, &content_id, &fed)?; + Ok(Prepared::Ready(Box::new(Ready { + content_id, + track_id, + fed, + snap_bytes, + op_bytes, + }))) + } + + /// One publication transaction (plan §7.3, steps 1–7). Locks are + /// released right away when it ends without a commit. + async fn try_batch(&self, source: i64, target_id: i64, records: &[Record]) -> Result { + // 1. Per-user lock and measurement. + let (mut tx, size) = self.begin().await?; + match self + .batch_in(&mut tx, &size, source, target_id, records) + .await + { + Ok(TxEnd::Committed(updates)) => { + // 7. All or nothing; the sender takes the committed operations. + tx.commit().await?; + Ok(TxEnd::Committed(updates)) + } + Ok(end) => { + tx.rollback().await?; + Ok(end) + } + Err(error) => { + let _ = tx.rollback().await; + Err(error) + } + } + } + + async fn batch_in( + &self, + tx: &mut sqlx::Transaction<'static, sqlx::Postgres>, + size: &OutgoingSyncSize, + source: i64, + target_id: i64, + records: &[Record], + ) -> Result { + let user_id = self.user_id(); + // 1a. Lease. + if !store::hold_lease(&mut *tx, self.import.id, self.run_id).await? { + return Ok(TxEnd::LeaseLost); + } + // 2. Target playlist. + let owned: Option = sqlx::query_scalar( + "SELECT id FROM furumusic__playlist WHERE id = $1 AND owner_id = $2 FOR UPDATE", + ) + .bind(target_id) + .bind(user_id) + .fetch_optional(&mut **tx) + .await?; + if owned.is_none() { + return Ok(TxEnd::Paused); + } + // 3. Identity: local operations of the user, including a deletion of + // this playlist from the web, wait for the batch. + sqlx::query("SELECT 1 FROM furumusic__fed_device_identity WHERE user_id = $1 FOR UPDATE") + .bind(user_id) + .execute(&mut **tx) + .await?; + // 4. Deleted, or a committed deletion still waiting to be applied. + let (sync_id, deleted) = sync_state(&mut *tx, user_id, target_id) + .await? + .context("target playlist has no sync state")?; + if deleted { + return Ok(TxEnd::Paused); + } + // 5. What the playlist already has or had. + let content_ids: Vec = records + .iter() + .filter_map(|record| match &record.prepared { + Prepared::Ready(ready) => Some(ready.content_id.clone()), + Prepared::Wait { .. } => None, + }) + .collect(); + let registers = registers(&mut *tx, user_id, &sync_id, &content_ids).await?; + let removed = removed_in_journal(&mut *tx, user_id, &sync_id).await?; + let track_ids: Vec = records + .iter() + .filter_map(|record| match &record.prepared { + Prepared::Ready(ready) => ready.track_id, + Prepared::Wait { .. } => None, + }) + .collect(); + let present_tracks: HashMap = sqlx::query( + "SELECT track_id, MIN(position)::int8 FROM furumusic__playlist_track + WHERE playlist_id = $1 AND track_id = ANY($2) GROUP BY track_id", + ) + .bind(target_id) + .bind(&track_ids) + .fetch_all(&mut **tx) + .await? + .into_iter() + .map(|row| (row.get(0), row.get(1))) + .collect(); + let mut next: i64 = sqlx::query_scalar( + "SELECT GREATEST( + (SELECT COALESCE(MAX(position), -1)::int8 FROM furumusic__playlist_track + WHERE playlist_id = $1), + (SELECT COALESCE(MAX(position), -1) FROM furumusic__fed_state_playlist_item + WHERE user_id = $2 AND playlist_id = $3 AND present)) + 1", + ) + .bind(target_id) + .bind(user_id) + .bind(&sync_id) + .fetch_one(&mut **tx) + .await?; + let receipts = store::receipts(&mut *tx, target_id, &content_ids).await?; + #[cfg(test)] + hooks::run(hooks::Point::BeforeAdd).await; + + // 6. Entries in source order. + let mut given: HashMap = HashMap::new(); + let mut published = Vec::new(); + let mut updates = Vec::with_capacity(records.len()); + let (mut snap_total, mut line_total, mut exhausted) = (0u64, 0u64, false); + for record in records { + let ready = match &record.prepared { + Prepared::Ready(ready) => ready, + Prepared::Wait { status, content_id } => { + updates.push(PublicationUpdate { + item_id: record.item_id, + status: *status, + content_id: content_id.clone(), + failed: *status == PublicationStatus::Failed, + }); + continue; + } + }; + let content_id = ready.content_id.as_str(); + let verdict = |status| PublicationUpdate { + item_id: record.item_id, + status, + content_id: Some(content_id.to_owned()), + failed: false, + }; + if let Some(receipt) = receipts.get(content_id) { + updates.push(verdict(if receipt.item_id != record.item_id { + PublicationStatus::Duplicate + } else if receipt.published { + PublicationStatus::Published + } else { + PublicationStatus::AlreadyPresent + })); + continue; + } + if given.contains_key(content_id) { + updates.push(verdict(PublicationStatus::Duplicate)); + continue; + } + // Present or removed: what the user added or removed stays as it is. + let known = registers.get(content_id).copied().or_else(|| { + removed.contains(content_id).then_some(-1).or_else(|| { + ready + .track_id + .and_then(|id| present_tracks.get(&id).copied()) + }) + }); + if let Some(position) = known { + store::insert_receipt( + &mut *tx, + target_id, + content_id, + source, + record.item_id, + position, + None, + ) + .await?; + given.insert(content_id.to_owned(), record.item_id); + updates.push(verdict(PublicationStatus::AlreadyPresent)); + continue; + } + if exhausted + || !fits( + size, + self.music_budget, + snap_total + ready.snap_bytes, + line_total + ready.snap_bytes + ready.op_bytes, + ) + { + exhausted = true; + updates.push(verdict(PublicationStatus::DeferredSyncLimit)); + continue; + } + if let Some(track_id) = ready.track_id { + let position = + i32::try_from(next).context("target playlist has too many tracks")?; + if !crate::import_playlists::append_in_transaction( + tx, + user_id, + target_id, + track_id, + Some(position), + ) + .await? + { + // Added to the playlist meanwhile; the next attempt sees it. + return Ok(TxEnd::Retry); + } + } + let Some(op_id) = devices::record_playlist_track_added_in_tx( + &mut *tx, + user_id, + &self.device_id, + &sync_id, + content_id, + next, + &ready.fed, + ready.track_id, + ) + .await? + else { + // An operation for this item was applied meanwhile. + return Ok(TxEnd::Retry); + }; + #[cfg(test)] + if hooks::should_fail(content_id) { + anyhow::bail!("injected failure after the operation was recorded"); + } + store::insert_receipt( + &mut *tx, + target_id, + content_id, + source, + record.item_id, + next, + Some(&op_id), + ) + .await?; + given.insert(content_id.to_owned(), record.item_id); + published.push(content_id.to_owned()); + snap_total += ready.snap_bytes; + line_total += ready.snap_bytes + ready.op_bytes; + next += 1; + updates.push(verdict(PublicationStatus::Published)); + } + #[cfg(test)] + hooks::run(hooks::Point::BeforeCommit).await; + // A removal that reached the journal during the batch wins: the batch + // runs again and sees it. + if !published.is_empty() { + let removed_now = removed_in_journal(&mut *tx, user_id, &sync_id).await?; + if published + .iter() + .any(|content_id| removed_now.contains(content_id)) + { + return Ok(TxEnd::Retry); + } + } + store::store_publication(&mut *tx, &updates).await?; + Ok(TxEnd::Committed(updates)) + } +} + +/// Whether additions of `snap` snapshot bytes and `line` line bytes fit both limits. +fn fits(size: &OutgoingSyncSize, music_budget: u64, snap: u64, line: u64) -> bool { + size.music_snapshot + snap <= music_budget && size.full_line + line <= HARD_LINE_LIMIT +} + +/// Title of the target playlist: the source title, and the provider for favorites. +fn target_title(source: &PublishTarget, provider: &str) -> String { + let title = source.title.trim(); + let title = if title.is_empty() { + "Imported playlist" + } else { + title + }; + let title = match source.kind { + PlaylistKind::Favorites => { + let name = super::adapters::file_providers() + .into_iter() + .find(|info| info.id == provider) + .map_or(provider.to_owned(), |info| info.name.to_owned()); + format!("{title} ({name})") + } + PlaylistKind::Playlist => title.to_owned(), + }; + title.chars().take(MAX_TITLE_CHARS).collect() +} + +/// Placeholders for values assigned only inside the transaction; the +/// largest values keep the estimate on the safe side. +fn placeholder_op_id(device_id: &str) -> String { + format!("{device_id}:{}", i64::MAX) +} + +fn json_len(value: &T) -> Result { + // One more byte for the separator in the enclosing array. + Ok(serde_json::to_vec(value)?.len() as u64 + 1) +} + +/// Snapshot and operation bytes of a new playlist, items not included. +fn playlist_costs(user_id: i64, device_id: &str, title: &str) -> Result<(u64, u64)> { + let sync_id = devices::local_playlist_sync_id_for(user_id, i64::MAX); + let snapshot = SnapshotPlaylist { + playlist_id: sync_id.clone(), + title: title.to_owned(), + hlc_ms: i64::MAX, + op_id: placeholder_op_id(device_id), + items: Vec::new(), + }; + let op = SyncOpWire { + op_id: placeholder_op_id(device_id), + origin_device_id: device_id.to_owned(), + seq: i64::MAX, + hlc_ms: i64::MAX, + payload: SyncOpPayload::PlaylistCreated { + playlist_id: sync_id, + title: title.to_owned(), + }, + }; + Ok((json_len(&snapshot)?, json_len(&op)?)) +} + +/// Snapshot and operation bytes of one published track. +fn item_costs( + device_id: &str, + sync_id: &str, + content_id: &str, + fed: &SyncedFedTrack, +) -> Result<(u64, u64)> { + let position = i64::from(i32::MAX); + let item = SnapshotPlaylistItem { + content_id: content_id.to_owned(), + position, + hlc_ms: i64::MAX, + op_id: placeholder_op_id(device_id), + fed: Some(fed.clone()), + }; + let op = SyncOpWire { + op_id: placeholder_op_id(device_id), + origin_device_id: device_id.to_owned(), + seq: i64::MAX, + hlc_ms: i64::MAX, + payload: SyncOpPayload::PlaylistTrackAdded { + playlist_id: sync_id.to_owned(), + content_id: content_id.to_owned(), + position, + fed: Some(fed.clone()), + }, + }; + Ok((json_len(&item)?, json_len(&op)?)) +} + +/// Sync id of a target playlist and whether it is deleted: its register says +/// so, or a deletion that wins over the register is committed to the journal +/// and not applied yet. +async fn sync_state( + conn: &mut PgConnection, + user_id: i64, + target_id: i64, +) -> Result> { + let row = sqlx::query( + "SELECT s.playlist_id, + s.deleted OR EXISTS ( + SELECT 1 FROM furumusic__fed_sync_ops o + WHERE o.user_id = s.user_id AND o.tombstone AND o.kind = 'playlist_deleted' + AND o.payload_json->>'playlist_id' = s.playlist_id + AND (o.hlc_ms, o.op_id COLLATE \"C\") > (s.hlc_ms, s.op_id COLLATE \"C\")) + FROM furumusic__fed_state_playlist s + WHERE s.user_id = $1 AND s.local_playlist_id = $2", + ) + .bind(user_id) + .bind(target_id) + .fetch_optional(conn) + .await?; + Ok(row.map(|row| (row.get(0), row.get(1)))) +} + +/// Registers of the batch's content ids, locked; present or removed. +async fn registers( + conn: &mut PgConnection, + user_id: i64, + sync_id: &str, + content_ids: &[String], +) -> Result> { + Ok(sqlx::query( + "SELECT content_id, position FROM furumusic__fed_state_playlist_item + WHERE user_id = $1 AND playlist_id = $2 AND content_id = ANY($3) + ORDER BY content_id FOR UPDATE", + ) + .bind(user_id) + .bind(sync_id) + .bind(content_ids) + .fetch_all(conn) + .await? + .into_iter() + .map(|row| (row.get(0), row.get(1))) + .collect()) +} + +/// Content ids removed from the playlist by a committed operation, whether +/// or not the register shows it yet. +async fn removed_in_journal( + conn: &mut PgConnection, + user_id: i64, + sync_id: &str, +) -> Result> { + let rows: Vec> = sqlx::query_scalar( + "SELECT payload_json->>'content_id' FROM furumusic__fed_sync_ops + WHERE user_id = $1 AND tombstone AND kind = 'playlist_track_removed' + AND payload_json->>'playlist_id' = $2", + ) + .bind(user_id) + .bind(sync_id) + .fetch_all(conn) + .await?; + Ok(rows + .into_iter() + .flatten() + .filter_map(|content_id| music_dht::normalize_content_id(&content_id)) + .collect()) +} + +/// Test hooks: code that runs inside a publication transaction, and failures +/// injected after an operation was recorded. +#[cfg(test)] +pub(crate) mod hooks { + use std::sync::Mutex; + + use futures_util::future::BoxFuture; + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum Point { + /// After the registers are locked, before the first addition. + BeforeAdd, + /// After all additions, before the commit. + BeforeCommit, + } + + type Hook = Box BoxFuture<'static, ()> + Send>; + + static HOOKS: Mutex> = Mutex::new(Vec::new()); + static FAIL_AFTER_OP: Mutex> = Mutex::new(None); + + /// Runs `hook` once, in the next transaction that reaches `point`. + pub fn once(point: Point, hook: impl FnOnce() -> BoxFuture<'static, ()> + Send + 'static) { + HOOKS.lock().unwrap().push((point, Box::new(hook))); + } + + /// Fails every transaction right after it recorded the operation for `content_id`. + pub fn fail_after_op(content_id: Option) { + *FAIL_AFTER_OP.lock().unwrap() = content_id; + } + + pub fn clear() { + HOOKS.lock().unwrap().clear(); + fail_after_op(None); + } + + pub(super) async fn run(point: Point) { + let hook = { + let mut hooks = HOOKS.lock().unwrap(); + hooks + .iter() + .position(|(candidate, _)| *candidate == point) + .map(|index| hooks.remove(index).1) + }; + if let Some(hook) = hook { + hook().await; + } + } + + pub(super) fn should_fail(content_id: &str) -> bool { + FAIL_AFTER_OP.lock().unwrap().as_deref() == Some(content_id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fed(content_id: &str) -> SyncedFedTrack { + SyncedFedTrack { + item_id: "item-1".into(), + owner: "peer".into(), + title: "Title".into(), + artist_names: vec!["Artist".into()], + featured_artist_names: Vec::new(), + year: Some(2001), + duration_seconds: Some(200), + content_id: content_id.into(), + release_title: Some("Album".into()), + track_number: Some(1), + disc_number: Some(1), + } + } + + #[test] + fn costs_are_measured_on_the_serialized_wire_types() { + let content_id = format!("b3:{}", "a".repeat(64)); + let (snap, op) = + item_costs("web_device", "webpl_1_2", &content_id, &fed(&content_id)).unwrap(); + let item = SnapshotPlaylistItem { + content_id: content_id.clone(), + position: 7, + hlc_ms: 1_700_000_000_000, + op_id: "web_device:42".into(), + fed: Some(fed(&content_id)), + }; + // Placeholders only overestimate the real values. + assert!(snap > serde_json::to_vec(&item).unwrap().len() as u64); + assert!(op > snap); + let (snap, op) = playlist_costs(1, "web_device", "Road trip").unwrap(); + assert!(snap > 0 && op > 0); + } + + #[test] + fn budget_needs_both_the_music_budget_and_the_hard_stop() { + let size = OutgoingSyncSize { + full_line: 6 * 1024 * 1024, + music_snapshot: 1024 * 1024, + }; + assert!(fits(&size, 2 * 1024 * 1024, 1024, 2048)); + assert!(!fits(&size, 1024 * 1024, 1, 1)); + assert!(!fits(&size, 8 * 1024 * 1024, 1, 1024 * 1024 + 1)); + } + + #[test] + fn favorites_are_named_after_the_provider_and_titles_are_bounded() { + let mut source = PublishTarget { + id: 1, + kind: PlaylistKind::Favorites, + title: "Liked Songs".into(), + description: None, + target_playlist_id: None, + target_created: false, + paused: false, + }; + assert_eq!(target_title(&source, "spotify"), "Liked Songs (Spotify)"); + source.kind = PlaylistKind::Playlist; + source.title = "ж".repeat(300); + assert_eq!(target_title(&source, "spotify").chars().count(), 255); + source.title = " ".into(); + assert_eq!(target_title(&source, "spotify"), "Imported playlist"); + } +} diff --git a/src/library_import/store.rs b/src/library_import/store.rs index 8d22540..0746aea 100644 --- a/src/library_import/store.rs +++ b/src/library_import/store.rs @@ -1032,6 +1032,322 @@ pub async fn finish_deferred( Ok(true) } +// --------------------------------------------------------------------------- +// Worker: publication +// --------------------------------------------------------------------------- + +/// Publication states the publisher tries again on every pass. +const PUBLISHABLE: &str = "('pending', 'failed', 'deferred_sync_limit', 'no_content_id')"; + +/// A source playlist and its target, in import order. +#[derive(Debug, Clone)] +pub struct PublishTarget { + pub id: i64, + pub kind: PlaylistKind, + pub title: String, + pub description: Option, + pub target_playlist_id: Option, + /// The target was created once; without `target_playlist_id` it is deleted. + pub target_created: bool, + pub paused: bool, +} + +pub async fn publish_targets(pool: &PgPool, import_id: i64) -> sqlx::Result> { + let rows = sqlx::query( + "SELECT id, kind, source_title, source_description, target_playlist_id, + target_created_at IS NOT NULL, publication_paused + FROM furumusic__library_import_playlist WHERE import_id = $1 ORDER BY ordinal, id", + ) + .bind(import_id) + .fetch_all(pool) + .await?; + Ok(rows + .into_iter() + .map(|row| PublishTarget { + id: row.get(0), + kind: row.get::(1).parse().unwrap_or_default(), + title: row.get(2), + description: row.get(3), + target_playlist_id: row.get(4), + target_created: row.get(5), + paused: row.get(6), + }) + .collect()) +} + +/// A matched entry waiting for the publisher. +#[derive(Debug, Clone)] +pub struct PublishEntry { + pub id: i64, + pub position: i32, + pub origin: Option, + pub content_id: Option, + pub track_id: Option, + pub fed: Option, +} + +/// Matched entries of a source playlist that still wait for publication, +/// in source order after `after_position`. +pub async fn publishable_entries( + pool: &PgPool, + import_playlist_id: i64, + after_position: i32, + limit: usize, +) -> sqlx::Result> { + let rows = sqlx::query(&format!( + "SELECT id, source_position, match_origin, matched_content_id, matched_track_id, matched_fed + FROM furumusic__library_import_item + WHERE import_playlist_id = $1 AND resolution_status = 'matched' + AND publication_status IN {PUBLISHABLE} AND source_position > $2 + ORDER BY source_position LIMIT $3" + )) + .bind(import_playlist_id) + .bind(after_position) + .bind(i64::try_from(limit).unwrap_or(i64::MAX)) + .fetch_all(pool) + .await?; + Ok(rows + .into_iter() + .map(|row| PublishEntry { + id: row.get(0), + position: row.get(1), + origin: row.get(2), + content_id: row.get(3), + track_id: row.get(4), + fed: row.get(5), + }) + .collect()) +} + +/// Locks the import against owner changes for the rest of the transaction, +/// as long as `run_id` still holds the lease. +pub async fn hold_lease( + conn: &mut PgConnection, + import_id: i64, + run_id: i64, +) -> sqlx::Result { + Ok(sqlx::query_scalar::<_, i64>( + "SELECT id FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(conn) + .await? + .is_some()) +} + +/// Locks a source playlist that has no target yet; `false` once it has one. +pub async fn lock_untargeted( + conn: &mut PgConnection, + import_playlist_id: i64, +) -> sqlx::Result { + Ok(sqlx::query_scalar::<_, i64>( + "SELECT id FROM furumusic__library_import_playlist + WHERE id = $1 AND target_created_at IS NULL FOR UPDATE", + ) + .bind(import_playlist_id) + .fetch_optional(conn) + .await? + .is_some()) +} + +pub async fn set_target( + conn: &mut PgConnection, + import_playlist_id: i64, + target_playlist_id: i64, +) -> sqlx::Result<()> { + sqlx::query( + "UPDATE furumusic__library_import_playlist + SET target_playlist_id = $2, target_created_at = now(), publication_paused = false + WHERE id = $1", + ) + .bind(import_playlist_id) + .bind(target_playlist_id) + .execute(conn) + .await?; + Ok(()) +} + +/// Entries of a playlist whose target cannot be created within the Device +/// Sync budget wait for the next pass. +pub async fn defer_playlist(conn: &mut PgConnection, import_playlist_id: i64) -> sqlx::Result { + Ok(sqlx::query(&format!( + "UPDATE furumusic__library_import_item + SET publication_status = 'deferred_sync_limit', last_attempt_at = now() + WHERE import_playlist_id = $1 AND resolution_status = 'matched' + AND publication_status IN {PUBLISHABLE}" + )) + .bind(import_playlist_id) + .execute(conn) + .await? + .rows_affected()) +} + +/// Stops publication into a deleted target playlist: the playlist is marked +/// paused and its waiting entries `paused`, until `…/recreate`. `false` +/// without the lease. +pub async fn pause_playlist( + pool: &PgPool, + import_id: i64, + run_id: i64, + import_playlist_id: i64, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + if !hold_lease(&mut tx, import_id, run_id).await? { + return Ok(false); + } + sqlx::query( + "UPDATE furumusic__library_import_playlist SET publication_paused = true WHERE id = $1", + ) + .bind(import_playlist_id) + .execute(&mut *tx) + .await?; + sqlx::query(&format!( + "UPDATE furumusic__library_import_item + SET publication_status = 'paused', last_attempt_at = now() + WHERE import_playlist_id = $1 AND resolution_status = 'matched' + AND publication_status IN {PUBLISHABLE}" + )) + .bind(import_playlist_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(true) +} + +/// A receipt: `content_id` was given to a target playlist by `item_id`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Receipt { + pub item_id: i64, + pub published: bool, +} + +pub async fn receipts( + conn: &mut PgConnection, + target_playlist_id: i64, + content_ids: &[String], +) -> sqlx::Result> { + let rows = sqlx::query( + "SELECT content_id, item_id, state FROM furumusic__library_import_publication + WHERE target_playlist_id = $1 AND content_id = ANY($2)", + ) + .bind(target_playlist_id) + .bind(content_ids) + .fetch_all(conn) + .await?; + Ok(rows + .into_iter() + .map(|row| { + let state: String = row.get(2); + ( + row.get(0), + Receipt { + item_id: row.get(1), + published: state == "published", + }, + ) + }) + .collect()) +} + +/// Writes a receipt. `op_id` is set for a published track and `None` for +/// one that was in the playlist before (or removed from it by the user). +pub async fn insert_receipt( + conn: &mut PgConnection, + target_playlist_id: i64, + content_id: &str, + import_playlist_id: i64, + item_id: i64, + position: i64, + op_id: Option<&str>, +) -> sqlx::Result<()> { + sqlx::query( + "INSERT INTO furumusic__library_import_publication + (target_playlist_id, content_id, import_playlist_id, item_id, state, position, op_id) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (target_playlist_id, content_id) DO NOTHING", + ) + .bind(target_playlist_id) + .bind(content_id) + .bind(import_playlist_id) + .bind(item_id) + .bind(if op_id.is_some() { + "published" + } else { + "preexisting" + }) + .bind(position) + .bind(op_id) + .execute(conn) + .await?; + Ok(()) +} + +/// The publisher's verdict for one entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PublicationUpdate { + pub item_id: i64, + pub status: PublicationStatus, + /// Content id found for the entry, kept even when it waits. + pub content_id: Option, + /// A failed attempt counts towards `attempt_count`. + pub failed: bool, +} + +pub async fn store_publication( + conn: &mut PgConnection, + updates: &[PublicationUpdate], +) -> sqlx::Result<()> { + if updates.is_empty() { + return Ok(()); + } + let ids: Vec = updates.iter().map(|update| update.item_id).collect(); + let statuses: Vec<&str> = updates + .iter() + .map(|update| update.status.as_str()) + .collect(); + let content_ids: Vec> = updates + .iter() + .map(|update| update.content_id.as_deref()) + .collect(); + let failed: Vec = updates.iter().map(|update| update.failed).collect(); + sqlx::query( + "UPDATE furumusic__library_import_item i + SET publication_status = u.status, + matched_content_id = COALESCE(u.content_id, i.matched_content_id), + last_attempt_at = now(), + attempt_count = i.attempt_count + CASE WHEN u.failed THEN 1 ELSE 0 END + FROM UNNEST($1::int8[], $2::text[], $3::text[], $4::bool[]) + AS u(id, status, content_id, failed) + WHERE i.id = u.id", + ) + .bind(&ids) + .bind(&statuses) + .bind(&content_ids) + .bind(&failed) + .execute(conn) + .await?; + Ok(()) +} + +/// Stores verdicts outside a publication batch, e.g. entries whose own +/// transaction failed. `false` without the lease. +pub async fn store_publication_owned( + pool: &PgPool, + import_id: i64, + run_id: i64, + updates: &[PublicationUpdate], +) -> sqlx::Result { + let mut tx = pool.begin().await?; + if !hold_lease(&mut tx, import_id, run_id).await? { + return Ok(false); + } + store_publication(&mut tx, updates).await?; + tx.commit().await?; + Ok(true) +} + // --------------------------------------------------------------------------- // Owner requests // --------------------------------------------------------------------------- @@ -1392,6 +1708,151 @@ pub async fn choose_candidate( }) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResyncOutcome { + Queued, + /// The import is still queued, running or waiting for a sign-in. + NotFinished, + NotFound, +} + +/// `POST …/resync` (Retry unmatched): a finished import is queued again with +/// its unmatched, ambiguous and failed entries pending; matched entries keep +/// their state, and the publisher retries the ones still waiting. +/// `federated_search` replaces the consent when given. +pub async fn request_resync( + pool: &PgPool, + user_id: i64, + import_id: i64, + federated_search: Option, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let status: Option = sqlx::query_scalar( + "SELECT status FROM furumusic__library_import WHERE id = $1 AND user_id = $2 FOR UPDATE", + ) + .bind(import_id) + .bind(user_id) + .fetch_optional(&mut *tx) + .await?; + let outcome = match status.as_deref().map(str::parse::) { + None => ResyncOutcome::NotFound, + Some(Ok(ImportStatus::Done | ImportStatus::Cancelled | ImportStatus::Failed)) => { + sqlx::query( + "UPDATE furumusic__library_import + SET status = 'queued', phase = NULL, cancel_requested = false, + rerun_requested = false, error = NULL, + federated_search = COALESCE($2, federated_search), + last_resync_at = now(), updated_at = now() + WHERE id = $1", + ) + .bind(import_id) + .bind(federated_search) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE furumusic__library_import_item i + SET resolution_status = 'pending', resolution_note = NULL, + publication_status = 'not_ready' + FROM furumusic__library_import_playlist p + WHERE p.id = i.import_playlist_id AND p.import_id = $1 + AND i.resolution_status IN ('unmatched', 'ambiguous', 'failed')", + ) + .bind(import_id) + .execute(&mut *tx) + .await?; + refresh_statistics(&mut tx, import_id).await?; + ResyncOutcome::Queued + } + Some(_) => ResyncOutcome::NotFinished, + }; + tx.commit().await?; + Ok(outcome) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RecreateOutcome { + /// The publisher creates a new target on its next pass. `queued` when the + /// import waits for a worker again. + Requested { + queued: bool, + }, + /// The target playlist still exists and publication is not paused. + TargetExists, + NotFound, +} + +/// `POST …/playlists/{pid}/recreate`: after the target playlist was deleted, +/// the publisher creates a new one and publishes every matched entry of the +/// source playlist into it. Receipts of the old target stay as history. +/// Waits for a running publication batch, like cancellation. +pub async fn recreate_target( + pool: &PgPool, + user_id: i64, + import_id: i64, + import_playlist_id: i64, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let status: Option = sqlx::query_scalar( + "SELECT status FROM furumusic__library_import WHERE id = $1 AND user_id = $2 FOR UPDATE", + ) + .bind(import_id) + .bind(user_id) + .fetch_optional(&mut *tx) + .await?; + let Some(status) = status else { + return Ok(RecreateOutcome::NotFound); + }; + let row = sqlx::query( + "SELECT target_playlist_id IS NULL AND target_created_at IS NOT NULL, publication_paused + FROM furumusic__library_import_playlist WHERE id = $1 AND import_id = $2 FOR UPDATE", + ) + .bind(import_playlist_id) + .bind(import_id) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = row else { + return Ok(RecreateOutcome::NotFound); + }; + let (deleted, paused): (bool, bool) = (row.get(0), row.get(1)); + if !deleted && !paused { + return Ok(RecreateOutcome::TargetExists); + } + sqlx::query( + "UPDATE furumusic__library_import_playlist + SET target_playlist_id = NULL, target_created_at = NULL, publication_paused = false + WHERE id = $1", + ) + .bind(import_playlist_id) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE furumusic__library_import_item SET publication_status = 'pending' + WHERE import_playlist_id = $1 AND resolution_status = 'matched'", + ) + .bind(import_playlist_id) + .execute(&mut *tx) + .await?; + let queued = matches!( + status.parse::(), + Ok(ImportStatus::Done | ImportStatus::Cancelled | ImportStatus::Failed) + ); + sqlx::query( + "UPDATE furumusic__library_import + SET rerun_requested = true, + cancel_requested = CASE WHEN $2 THEN false ELSE cancel_requested END, + status = CASE WHEN $2 THEN 'queued' ELSE status END, + updated_at = now() + WHERE id = $1", + ) + .bind(import_id) + .bind(queued) + .execute(&mut *tx) + .await?; + refresh_statistics(&mut tx, import_id).await?; + tx.commit().await?; + Ok(RecreateOutcome::Requested { queued }) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CancelOutcome { /// The import had no worker and is cancelled now. diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs index 2e1cead..384c856 100644 --- a/src/library_import/tests.rs +++ b/src/library_import/tests.rs @@ -33,6 +33,8 @@ use crate::config::AppConfig; use crate::federation::client::{CatalogPeers, CatalogStream}; use crate::scheduler::JobLog; +mod publisher; + /// Workers share a process-wide slot counter, so database tests run one at a time. static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -73,7 +75,41 @@ impl Fixture { sqlx::raw_sql( "CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true); CREATE TABLE furumusic__user(id BIGINT PRIMARY KEY); - CREATE TABLE furumusic__playlist(id BIGSERIAL PRIMARY KEY, owner_id BIGINT NOT NULL, title TEXT NOT NULL); + CREATE TABLE furumusic__playlist(id BIGSERIAL PRIMARY KEY, owner_id BIGINT NOT NULL, + title VARCHAR(255) NOT NULL, description TEXT, is_public BOOLEAN NOT NULL DEFAULT false, + created_at VARCHAR(32) NOT NULL DEFAULT '', updated_at VARCHAR(32) NOT NULL DEFAULT ''); + CREATE TABLE furumusic__playlist_track(id BIGSERIAL PRIMARY KEY, playlist_id BIGINT NOT NULL, + track_id BIGINT NOT NULL, position INTEGER NOT NULL, added_at VARCHAR(32) NOT NULL, + added_by_user_id BIGINT NOT NULL); + CREATE TABLE furumusic__saved_playlist(id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, + playlist_id BIGINT NOT NULL, saved_at VARCHAR(32) NOT NULL DEFAULT ''); + -- Device Sync tables of the publisher, as in `src/music/mod.rs`. + CREATE TABLE furumusic__fed_device_identity(user_id BIGINT PRIMARY KEY, + device_id TEXT NOT NULL UNIQUE, group_id TEXT NOT NULL, device_name TEXT NOT NULL, + local_seq BIGINT NOT NULL DEFAULT 0, last_hlc_ms BIGINT NOT NULL DEFAULT 0, + local_seeded_at_ms BIGINT NOT NULL DEFAULT 0, last_sync TEXT, last_error TEXT, + playback_coordination_json JSONB, playback_config_json JSONB); + CREATE TABLE furumusic__fed_device(user_id BIGINT NOT NULL, device_id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT '', client_version TEXT NOT NULL DEFAULT '', + protocol_version INTEGER NOT NULL DEFAULT 1, endpoint_id TEXT NOT NULL DEFAULT '', + endpoint_ticket TEXT NOT NULL DEFAULT '', trusted_at_ms BIGINT, last_seen_ms BIGINT, + revoked_at_ms BIGINT, revoked_by TEXT, revoke_cutoff_seq BIGINT, + PRIMARY KEY (user_id, device_id)); + CREATE TABLE furumusic__fed_sync_ops(user_id BIGINT NOT NULL, op_id TEXT NOT NULL, + origin_device_id TEXT NOT NULL, seq BIGINT NOT NULL, kind TEXT NOT NULL, + payload_json JSONB NOT NULL, hlc_ms BIGINT NOT NULL, received_at_ms BIGINT NOT NULL, + tombstone BOOLEAN NOT NULL DEFAULT false, PRIMARY KEY (user_id, op_id)); + CREATE INDEX idx_fed_sync_ops_tombstone ON furumusic__fed_sync_ops (user_id, tombstone); + CREATE TABLE furumusic__fed_sync_vector(user_id BIGINT NOT NULL, device_id TEXT NOT NULL, + max_seq BIGINT NOT NULL, PRIMARY KEY (user_id, device_id)); + CREATE TABLE furumusic__fed_peer_ack(user_id BIGINT NOT NULL, peer_device_id TEXT NOT NULL, + origin_device_id TEXT NOT NULL, max_seq BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, + PRIMARY KEY (user_id, peer_device_id, origin_device_id)); + CREATE TABLE furumusic__fed_state_playlist(user_id BIGINT NOT NULL, playlist_id TEXT NOT NULL, + local_playlist_id BIGINT, title TEXT NOT NULL, deleted BOOLEAN NOT NULL DEFAULT false, + hlc_ms BIGINT NOT NULL, op_id TEXT NOT NULL, PRIMARY KEY (user_id, playlist_id)); + CREATE UNIQUE INDEX idx_fed_state_playlist_local ON furumusic__fed_state_playlist + (user_id, local_playlist_id) WHERE local_playlist_id IS NOT NULL; CREATE TABLE furumusic__job_run(id BIGINT PRIMARY KEY, status TEXT NOT NULL); INSERT INTO furumusic__user VALUES (1), (2); -- The library and federation tables the resolver reads. @@ -108,11 +144,21 @@ impl Fixture { hlc_ms BIGINT NOT NULL, op_id TEXT NOT NULL, local_track_id BIGINT, fed_json JSONB, PRIMARY KEY (user_id, playlist_id, content_id)); CREATE TABLE furumusic__track_content_alias(track_id BIGINT NOT NULL, content_id TEXT NOT NULL); - CREATE TABLE furumusic__user_liked_track(user_id BIGINT NOT NULL, track_id BIGINT NOT NULL);", + CREATE TABLE furumusic__user_liked_track(user_id BIGINT NOT NULL, track_id BIGINT NOT NULL, + created_at VARCHAR(32) NOT NULL DEFAULT '');", ) .execute(&pool) .await .unwrap(); + // Podcast state is part of every Device Sync snapshot. + for source in [ + include_str!("../podcasts/schema.sql"), + include_str!("../podcasts/sync_schema.sql"), + ] { + for statement in source.split(';').filter(|s| !s.trim().is_empty()) { + sqlx::query(statement).execute(&pool).await.unwrap(); + } + } // The migration must be repeatable after a partial upgrade. for _ in 0..2 { for statement in include_str!("schema.sql") @@ -1504,7 +1550,7 @@ async fn library_import_resolves_locally_without_the_network() { Some(1), None, None, - "pending".into(), + "published".into(), ), // Diacritics fold; the cached content id is used. ( @@ -1515,7 +1561,7 @@ async fn library_import_resolves_locally_without_the_network() { Some(2), None, None, - "pending".into(), + "published".into(), ), // A remaster on one side only is left to the user. ( @@ -1549,7 +1595,7 @@ async fn library_import_resolves_locally_without_the_network() { None, s("peer-b"), None, - "pending".into(), + "published".into(), ), // The web player's own metadata is not a federated source. ( @@ -1571,7 +1617,7 @@ async fn library_import_resolves_locally_without_the_network() { None, s("peer-c"), None, - "pending".into(), + "published".into(), ), // Another user's like is not used. ( @@ -2019,7 +2065,7 @@ async fn library_import_searches_peer_catalogues_and_takes_manual_choices() { None, s("0"), None, - "pending".into(), + "published".into(), ) }; let expected: Vec = vec![ @@ -2175,6 +2221,8 @@ async fn library_import_searches_peer_catalogues_and_takes_manual_choices() { assert_eq!(network.searches().len(), before); let items = resolved_items(pool, import_id).await; assert_eq!(items[1].0, "matched"); + // The manual choice is published by the same pass. + assert_eq!(items[1].7, "published"); assert_eq!(items[3].7, "no_content_id"); fixture.drop().await; diff --git a/src/library_import/tests/publisher.rs b/src/library_import/tests/publisher.rs new file mode 100644 index 0000000..3453e8a --- /dev/null +++ b/src/library_import/tests/publisher.rs @@ -0,0 +1,1260 @@ +//! PostgreSQL tests for the publisher: atomic batches, receipts, deleted +//! tracks and playlists, concurrent Device Sync operations and the budget. + +use std::sync::Mutex as StdMutex; + +use music_dht::device_sync::{SyncOpPayload, SyncOpWire}; +use tokio::task::JoinHandle; + +use super::*; +use crate::federation::devices; +use crate::library_import::publisher::hooks::{self, Point}; + +const USER: i64 = 1; +const REMOTE: &str = "tui_remote_a"; +const REMOTE_B: &str = "tui_remote_b"; + +fn cid(n: i64) -> String { + format!("b3:{n:064x}") +} + +/// Library tracks `1..=count` with content ids `cid(n)`; track and media ids are `1000 + n`. +async fn library(pool: &PgPool, count: i64) { + sqlx::raw_sql( + "INSERT INTO furumusic__artist VALUES (900, 'Library Artist', 'library artist', false); + INSERT INTO furumusic__release VALUES (900, 'Library Album', 2020, false); + INSERT INTO furumusic__release_artist VALUES (900, 900, 0);", + ) + .execute(pool) + .await + .unwrap(); + for n in 1..=count { + sqlx::query( + "INSERT INTO furumusic__media_file VALUES ($1, 'lib/' || $2 || '.flac', 'sha-lib-' || $2)", + ) + .bind(1000 + n) + .bind(n.to_string()) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO furumusic__track VALUES ($1, 'Library song ' || $2, 'library song ' || $2, + 900, $3, 1, 200.0, $1, false)", + ) + .bind(1000 + n) + .bind(n.to_string()) + .bind(i32::try_from(n).unwrap()) + .execute(pool) + .await + .unwrap(); + sqlx::query("INSERT INTO furumusic__track_artist VALUES ($1, 900, 'main', 0)") + .bind(1000 + n) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO furumusic__federation_content_id_cache + VALUES ($1, 'sha-lib-' || $2, $3, '2026-01-01T00:00:00Z')", + ) + .bind(1000 + n) + .bind(n.to_string()) + .bind(cid(n)) + .execute(pool) + .await + .unwrap(); + } +} + +/// Federated metadata of `cid(n)`, shaped like a peer catalogue track. +fn fed(n: i64) -> serde_json::Value { + json!({"item_id": format!("item-{n}"), "owner": "peer-a", + "title": format!("Federated song number {n}"), + "artist_names": ["Peer Artist", "Second Artist"], "featured_artist_names": ["Guest"], + "year": 2001, "duration_seconds": 215, "content_id": cid(n), + "release_title": "A Peer Album With A Longer Title", "track_number": n % 20 + 1, + "disc_number": 1}) +} + +#[derive(Debug, Clone, Copy)] +enum Entry { + Local(i64), + Fed(i64), + Unmatched, +} + +fn playlist_key(import_key: &str, index: usize) -> String { + format!("{import_key}-{index}") +} + +/// An import with one source playlist per `playlists` item, matched as +/// given: the resolver has nothing left to do. +async fn matched_import(pool: &PgPool, key: &str, playlists: &[(&str, Vec)]) -> i64 { + let new = new_import( + USER, + "spotify", + playlists + .iter() + .enumerate() + .map(|(index, (title, entries))| { + let tracks: Vec = (0..entries.len()) + .map(|position| { + track( + position as u32, + &format!("Source song {position}"), + "Source Artist", + "Source Album", + ) + }) + .collect(); + playlist(&playlist_key(key, index), title, &tracks) + }) + .collect(), + ); + let import_id = store::create_import(pool, &new).await.unwrap(); + for (index, (_, entries)) in playlists.iter().enumerate() { + for (position, entry) in entries.iter().enumerate() { + set_entry(pool, import_id, index, position, *entry).await; + } + } + import_id +} + +/// Sets the resolver's decision for an entry. +async fn set_entry(pool: &PgPool, import_id: i64, ordinal: usize, position: usize, entry: Entry) { + let (resolution, origin, track_id, content_id, fed_json, publication) = match entry { + Entry::Local(n) => ( + "matched", + Some("local"), + Some(1000 + n), + Some(cid(n)), + None, + "pending", + ), + Entry::Fed(n) => ( + "matched", + Some("federation"), + None, + Some(cid(n)), + Some(fed(n)), + "pending", + ), + Entry::Unmatched => ("unmatched", None, None, None, None, "not_ready"), + }; + sqlx::query( + "UPDATE furumusic__library_import_item i + SET resolution_status = $4, resolution_note = CASE WHEN $4 = 'unmatched' THEN 'not_found' END, + match_origin = $5, match_method = CASE WHEN $4 = 'matched' THEN 'auto' END, + matched_track_id = $6, matched_content_id = $7, matched_fed = $8, + publication_status = $9 + FROM furumusic__library_import_playlist p + WHERE p.id = i.import_playlist_id AND p.import_id = $1 AND p.ordinal = $2 + AND i.source_position = $3", + ) + .bind(import_id) + .bind(i32::try_from(ordinal).unwrap()) + .bind(i32::try_from(position).unwrap()) + .bind(resolution) + .bind(origin) + .bind(track_id) + .bind(content_id) + .bind(fed_json) + .bind(publication) + .execute(pool) + .await + .unwrap(); +} + +async fn publish_with(pool: &PgPool, run_id: i64, budget: Option) -> String { + let mut config = AppConfig::default(); + if let Some(budget) = budget { + config.library_import_sync_budget = budget; + } + let mut log = JobLog::new(); + job::run_worker(pool, Arc::new(config), run_id, &mut log) + .await + .unwrap(); + log.output() +} + +async fn publish(pool: &PgPool, run_id: i64) -> String { + publish_with(pool, run_id, None).await +} + +async fn resync(pool: &PgPool, import_id: i64) { + assert_eq!( + store::request_resync(pool, USER, import_id, None) + .await + .unwrap(), + store::ResyncOutcome::Queued + ); +} + +async fn target(pool: &PgPool, import_id: i64, ordinal: i32) -> Option { + sqlx::query_scalar( + "SELECT target_playlist_id FROM furumusic__library_import_playlist + WHERE import_id = $1 AND ordinal = $2", + ) + .bind(import_id) + .bind(ordinal) + .fetch_one(pool) + .await + .unwrap() +} + +async fn statuses(pool: &PgPool, import_id: i64) -> Vec { + sqlx::query_scalar( + "SELECT i.publication_status FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 ORDER BY p.ordinal, i.source_position", + ) + .bind(import_id) + .fetch_all(pool) + .await + .unwrap() +} + +/// `(track_id, position)` rows of a playlist in order. +async fn rows(pool: &PgPool, playlist_id: i64) -> Vec<(i64, i32)> { + sqlx::query_as( + "SELECT track_id, position FROM furumusic__playlist_track + WHERE playlist_id = $1 ORDER BY position, id", + ) + .bind(playlist_id) + .fetch_all(pool) + .await + .unwrap() +} + +/// `(present, position, op_id)` of an item register. +async fn register(pool: &PgPool, playlist_id: i64, n: i64) -> Option<(bool, i64, String)> { + sqlx::query_as( + "SELECT present, position, op_id FROM furumusic__fed_state_playlist_item + WHERE user_id = $1 AND playlist_id = $2 AND content_id = $3", + ) + .bind(USER) + .bind(devices::local_playlist_sync_id_for(USER, playlist_id)) + .bind(cid(n)) + .fetch_optional(pool) + .await + .unwrap() +} + +/// Operations of the web device of `kind`, optionally for one content id. +async fn own_ops(pool: &PgPool, kind: &str, content_id: Option<&str>) -> i64 { + let device = devices::local_device_id(pool, USER).await.unwrap(); + sqlx::query_scalar( + "SELECT count(*) FROM furumusic__fed_sync_ops + WHERE user_id = $1 AND origin_device_id = $2 AND kind = $3 + AND ($4::text IS NULL OR payload_json->>'content_id' = $4)", + ) + .bind(USER) + .bind(device) + .bind(kind) + .bind(content_id) + .fetch_one(pool) + .await + .unwrap() +} + +async fn receipts(pool: &PgPool, playlist_id: i64) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT content_id, state FROM furumusic__library_import_publication + WHERE target_playlist_id = $1 ORDER BY position, content_id", + ) + .bind(playlist_id) + .fetch_all(pool) + .await + .unwrap() +} + +async fn trust_remote(pool: &PgPool) { + for device in [REMOTE, REMOTE_B] { + sqlx::query( + "INSERT INTO furumusic__fed_device + (user_id, device_id, name, client_version, protocol_version, trusted_at_ms) + VALUES ($1, $2, 'TUI', '1.0', 4, 1)", + ) + .bind(USER) + .bind(device) + .execute(pool) + .await + .unwrap(); + } +} + +fn remote_op(device: &str, seq: i64, hlc_ms: i64, payload: SyncOpPayload) -> SyncOpWire { + SyncOpWire { + op_id: format!("{device}:{seq}"), + origin_device_id: device.to_owned(), + seq, + hlc_ms, + payload, + } +} + +fn removed(playlist_id: i64, n: i64) -> SyncOpPayload { + SyncOpPayload::PlaylistTrackRemoved { + playlist_id: devices::local_playlist_sync_id_for(USER, playlist_id), + content_id: cid(n), + } +} + +fn added(playlist_id: i64, n: i64, position: i64) -> SyncOpPayload { + SyncOpPayload::PlaylistTrackAdded { + playlist_id: devices::local_playlist_sync_id_for(USER, playlist_id), + content_id: cid(n), + position, + fed: None, + } +} + +async fn apply(pool: &PgPool, op: SyncOpWire) { + devices::apply_received_ops(pool, USER, vec![op]) + .await + .unwrap(); +} + +fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// Every register of a local track agrees with the playlist rows. +async fn assert_consistent(pool: &PgPool, playlist_id: i64) { + let rows: Vec<(String, bool, bool)> = sqlx::query_as( + "SELECT r.content_id, r.present, + EXISTS(SELECT 1 FROM furumusic__playlist_track pt + WHERE pt.playlist_id = $2 AND pt.track_id = r.local_track_id) + FROM furumusic__fed_state_playlist_item r + WHERE r.user_id = $1 AND r.playlist_id = $3 AND r.local_track_id IS NOT NULL", + ) + .bind(USER) + .bind(playlist_id) + .bind(devices::local_playlist_sync_id_for(USER, playlist_id)) + .fetch_all(pool) + .await + .unwrap(); + for (content_id, present, materialized) in rows { + assert_eq!( + present, materialized, + "register and playlist row of {content_id}" + ); + } +} + +/// A task started inside a publication transaction, awaited after it. +type Spawned = Arc>>>; + +async fn join(spawned: &Spawned) { + let handle = spawned.lock().unwrap().take().expect("hook ran"); + handle.await.unwrap(); +} + +async fn setup() -> (tokio::sync::MutexGuard<'static, ()>, Fixture) { + let serial = SERIAL.lock().await; + hooks::clear(); + let fixture = Fixture::new().await; + (serial, fixture) +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_publishes_matches_once_in_source_order() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 6).await; + let import_id = matched_import( + pool, + "order", + &[ + ( + "Road trip", + vec![ + Entry::Local(1), + Entry::Fed(50), + Entry::Local(2), + Entry::Local(1), + Entry::Fed(50), + Entry::Unmatched, + ], + ), + ("Empty", vec![Entry::Unmatched]), + ], + ) + .await; + sqlx::query("UPDATE furumusic__library_import_playlist SET source_description = 'From Spotify' WHERE import_id = $1 AND ordinal = 0") + .bind(import_id) + .execute(pool) + .await + .unwrap(); + let output = publish(pool, 801).await; + assert_eq!(fixture.status(import_id).await, "done", "{output}"); + assert!( + output.contains("published 3 entries into 2 new playlists"), + "{output}" + ); + assert_eq!( + statuses(pool, import_id).await, + [ + "published", + "published", + "published", + "duplicate", + "duplicate", + "not_ready", + "not_ready" + ] + ); + let road = target(pool, import_id, 0).await.unwrap(); + let empty = target(pool, import_id, 1).await.unwrap(); + // Both targets are ordinary private playlists; the empty one too. + let playlists: Vec<(i64, String, Option, bool)> = sqlx::query_as( + "SELECT id, title::text, description, is_public FROM furumusic__playlist ORDER BY id", + ) + .fetch_all(pool) + .await + .unwrap(); + assert_eq!( + playlists, + [ + (road, "Road trip".into(), Some("From Spotify".into()), false), + (empty, "Empty".into(), None, false) + ] + ); + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 2)]); + assert_eq!(register(pool, road, 1).await.unwrap().1, 0); + assert_eq!(register(pool, road, 50).await.unwrap().1, 1); + assert_eq!(register(pool, road, 2).await.unwrap().1, 2); + assert!(rows(pool, empty).await.is_empty()); + assert_eq!(own_ops(pool, "playlist_created", None).await, 2); + assert_eq!(own_ops(pool, "playlist_track_added", None).await, 3); + assert_eq!(receipts(pool, road).await.len(), 3); + // The operation of every receipt is the one in the register. + let linked: i64 = sqlx::query_scalar( + "SELECT count(*) FROM furumusic__library_import_publication p + JOIN furumusic__fed_state_playlist_item r + ON r.content_id = p.content_id AND r.op_id = p.op_id + WHERE p.target_playlist_id = $1", + ) + .bind(road) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(linked, 3); + + // Another pass adds nothing. + resync(pool, import_id).await; + publish(pool, 802).await; + assert_eq!(own_ops(pool, "playlist_created", None).await, 2); + assert_eq!(own_ops(pool, "playlist_track_added", None).await, 3); + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 2)]); + + // A new match found by Resync goes to the end; existing items keep their place. + set_entry(pool, import_id, 0, 5, Entry::Local(3)).await; + resync(pool, import_id).await; + publish(pool, 803).await; + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 2), (1003, 3)]); + assert_eq!(statuses(pool, import_id).await[5], "published"); + assert_eq!(own_ops(pool, "playlist_track_added", None).await, 4); + assert_consistent(pool, road).await; + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_never_restores_removed_tracks_or_deleted_playlists() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 4).await; + let import_id = matched_import( + pool, + "removed", + &[( + "Removed", + vec![ + Entry::Local(1), + Entry::Local(2), + Entry::Unmatched, + Entry::Unmatched, + ], + )], + ) + .await; + publish(pool, 811).await; + let road = target(pool, import_id, 0).await.unwrap(); + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 1)]); + + // The user removes a published track and adds one on their own. + sqlx::query("DELETE FROM furumusic__playlist_track WHERE playlist_id = $1 AND track_id = 1001") + .bind(road) + .execute(pool) + .await + .unwrap(); + devices::record_playlist_tracks_removed(pool, USER, road, &[cid(1)]) + .await + .unwrap(); + assert!( + crate::import_playlists::append_track_to_target_playlist(pool, USER, road, 1003) + .await + .unwrap() + ); + set_entry(pool, import_id, 0, 2, Entry::Local(3)).await; + resync(pool, import_id).await; + publish(pool, 812).await; + // The receipt keeps the removed track out; the user's own track stays theirs. + assert_eq!(rows(pool, road).await, [(1002, 1), (1003, 2)]); + assert_eq!( + statuses(pool, import_id).await, + ["published", "published", "already_present", "not_ready"] + ); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(1))).await, + 1 + ); + // Without its receipt the removed track is still recognised by its register. + sqlx::query( + "DELETE FROM furumusic__library_import_publication WHERE target_playlist_id = $1 AND content_id = $2", + ) + .bind(road) + .bind(cid(1)) + .execute(pool) + .await + .unwrap(); + sqlx::query("UPDATE furumusic__library_import_item SET publication_status = 'pending' WHERE source_position = 0") + .execute(pool) + .await + .unwrap(); + resync(pool, import_id).await; + publish(pool, 813).await; + assert_eq!(statuses(pool, import_id).await[0], "already_present"); + assert_eq!(rows(pool, road).await, [(1002, 1), (1003, 2)]); + assert!(!register(pool, road, 1).await.unwrap().0); + + // The user deletes the playlist: publication pauses and nothing is recreated. + devices::record_playlist_deleted(pool, USER, road) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist_track WHERE playlist_id = $1") + .bind(road) + .execute(pool) + .await + .unwrap(); + sqlx::query("DELETE FROM furumusic__playlist WHERE id = $1") + .bind(road) + .execute(pool) + .await + .unwrap(); + set_entry(pool, import_id, 0, 3, Entry::Local(4)).await; + resync(pool, import_id).await; + publish(pool, 814).await; + assert_eq!(fixture.status(import_id).await, "done"); + assert_eq!(statuses(pool, import_id).await[3], "paused"); + let playlists: i64 = sqlx::query_scalar("SELECT count(*) FROM furumusic__playlist") + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(playlists, 0); + let detail = store::get_import(pool, USER, import_id) + .await + .unwrap() + .unwrap(); + assert!(detail.source_playlists[0].target_deleted); + assert!(detail.source_playlists[0].publication_paused); + assert_eq!(own_ops(pool, "playlist_created", None).await, 1); + + // Recreate: a new target receives every matched entry; old receipts stay. + let source = detail.source_playlists[0].id; + assert_eq!( + store::recreate_target(pool, 2, import_id, source) + .await + .unwrap(), + store::RecreateOutcome::NotFound + ); + assert_eq!( + store::recreate_target(pool, USER, import_id, source) + .await + .unwrap(), + store::RecreateOutcome::Requested { queued: true } + ); + publish(pool, 815).await; + let recreated = target(pool, import_id, 0).await.unwrap(); + assert_ne!(recreated, road); + assert_eq!( + rows(pool, recreated).await, + [(1001, 0), (1002, 1), (1003, 2), (1004, 3)] + ); + assert_eq!(statuses(pool, import_id).await, ["published"; 4]); + assert_eq!(receipts(pool, road).await.len(), 3); + assert_eq!( + store::recreate_target(pool, USER, import_id, source) + .await + .unwrap(), + store::RecreateOutcome::TargetExists + ); + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_entry_failing_in_its_transaction_leaves_nothing_behind() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 3).await; + let import_id = matched_import( + pool, + "fault", + &[( + "Fault", + vec![Entry::Local(1), Entry::Fed(2), Entry::Local(3)], + )], + ) + .await; + // The second entry fails right after its operation was recorded. + hooks::fail_after_op(Some(cid(2))); + publish(pool, 821).await; + hooks::clear(); + assert_eq!(fixture.status(import_id).await, "done"); + let road = target(pool, import_id, 0).await.unwrap(); + assert_eq!( + statuses(pool, import_id).await, + ["published", "failed", "published"] + ); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 0 + ); + assert!(register(pool, road, 2).await.is_none()); + assert_eq!( + receipts(pool, road) + .await + .into_iter() + .map(|(content_id, _)| content_id) + .collect::>(), + [cid(1), cid(3)] + ); + let attempts: i32 = sqlx::query_scalar( + "SELECT attempt_count FROM furumusic__library_import_item WHERE source_position = 1", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(attempts, 1); + // The next pass publishes it after the others. + resync(pool, import_id).await; + publish(pool, 822).await; + assert_eq!(statuses(pool, import_id).await, ["published"; 3]); + assert_eq!(register(pool, road, 2).await.unwrap().1, 2); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 1 + ); + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_rolls_back_when_a_register_is_written_concurrently() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 3).await; + trust_remote(pool).await; + let import_id = matched_import( + pool, + "race", + &[("Race", vec![Entry::Local(1), Entry::Unmatched])], + ) + .await; + publish(pool, 831).await; + let road = target(pool, import_id, 0).await.unwrap(); + // Another device adds the next entry's track while the batch runs. + set_entry(pool, import_id, 0, 1, Entry::Local(2)).await; + let hook_pool = pool.clone(); + hooks::once(Point::BeforeAdd, move || { + Box::pin(async move { + apply( + &hook_pool, + remote_op(REMOTE, 1, now_ms() - 60_000, added(road, 2, 7)), + ) + .await; + }) + }); + resync(pool, import_id).await; + publish(pool, 832).await; + assert_eq!( + statuses(pool, import_id).await, + ["published", "already_present"] + ); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 0 + ); + let (present, position, op_id) = register(pool, road, 2).await.unwrap(); + assert!(present); + assert_eq!((position, op_id.as_str()), (7, "tui_remote_a:1")); + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 7)]); + assert_eq!( + receipts(pool, road).await, + [ + (cid(1), "published".to_owned()), + (cid(2), "preexisting".to_owned()) + ] + ); + assert_consistent(pool, road).await; + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_concurrent_playlist_deletions_win() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 6).await; + trust_remote(pool).await; + let import_id = matched_import( + pool, + "delete", + &[ + ("Web", vec![Entry::Local(1), Entry::Unmatched]), + ( + "Remote", + vec![Entry::Local(3), Entry::Unmatched, Entry::Unmatched], + ), + ], + ) + .await; + publish(pool, 841).await; + let web = target(pool, import_id, 0).await.unwrap(); + let remote = target(pool, import_id, 1).await.unwrap(); + + // Deleting from the web waits for the batch and then removes everything. + set_entry(pool, import_id, 0, 1, Entry::Local(2)).await; + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + devices::record_playlist_deleted(&task_pool, USER, web) + .await + .unwrap(); + for table in ["furumusic__playlist_track", "furumusic__saved_playlist"] { + sqlx::query(&format!("DELETE FROM {table} WHERE playlist_id = $1")) + .bind(web) + .execute(&task_pool) + .await + .unwrap(); + } + sqlx::query("DELETE FROM furumusic__playlist WHERE id = $1") + .bind(web) + .execute(&task_pool) + .await + .unwrap(); + }); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!(!handle.is_finished(), "the deletion waits for the batch"); + *slot.lock().unwrap() = Some(handle); + }) + }); + resync(pool, import_id).await; + publish(pool, 842).await; + join(&spawned).await; + assert!(rows(pool, web).await.is_empty()); + let (added_seq, deleted_seq): (i64, i64) = sqlx::query_as( + "SELECT max(seq) FILTER (WHERE kind = 'playlist_track_added'), + max(seq) FILTER (WHERE kind = 'playlist_deleted') + FROM furumusic__fed_sync_ops WHERE user_id = $1", + ) + .bind(USER) + .fetch_one(pool) + .await + .unwrap(); + assert!( + deleted_seq > added_seq, + "the deletion is ordered after the batch" + ); + let deleted: bool = sqlx::query_scalar( + "SELECT deleted FROM furumusic__fed_state_playlist WHERE local_playlist_id = $1", + ) + .bind(web) + .fetch_one(pool) + .await + .unwrap(); + assert!(deleted); + + // A deletion from another device applied during the batch: no rows stay + // behind without their playlist, and publication pauses. + set_entry(pool, import_id, 1, 1, Entry::Local(4)).await; + set_entry(pool, import_id, 1, 2, Entry::Local(5)).await; + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + let payload = SyncOpPayload::PlaylistDeleted { + playlist_id: devices::local_playlist_sync_id_for(USER, remote), + }; + apply(&task_pool, remote_op(REMOTE, 1, now_ms() + 60_000, payload)).await; + }); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!( + !handle.is_finished(), + "the deletion waits for the playlist lock" + ); + *slot.lock().unwrap() = Some(handle); + }) + }); + resync(pool, import_id).await; + publish(pool, 843).await; + join(&spawned).await; + let orphans: i64 = sqlx::query_scalar( + "SELECT count(*) FROM furumusic__playlist_track pt + WHERE NOT EXISTS (SELECT 1 FROM furumusic__playlist p WHERE p.id = pt.playlist_id)", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(orphans, 0); + let paused: Vec = sqlx::query_scalar( + "SELECT publication_paused FROM furumusic__library_import_playlist + WHERE import_id = $1 ORDER BY ordinal", + ) + .bind(import_id) + .fetch_all(pool) + .await + .unwrap(); + assert_eq!(paused, [true, true]); + assert_eq!( + target(pool, import_id, 1).await, + None, + "the playlist is deleted" + ); + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_register_survives_an_older_concurrent_operation() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 2).await; + trust_remote(pool).await; + let import_id = matched_import( + pool, + "stale", + &[("Stale", vec![Entry::Local(1), Entry::Unmatched])], + ) + .await; + publish(pool, 851).await; + let road = target(pool, import_id, 0).await.unwrap(); + set_entry(pool, import_id, 0, 1, Entry::Local(2)).await; + // An addition with an older clock arrives while the batch holds the register. + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + apply(&task_pool, remote_op(REMOTE, 1, 1, added(road, 2, 999))).await; + }); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!( + !handle.is_finished(), + "the operation waits for the register" + ); + *slot.lock().unwrap() = Some(handle); + }) + }); + resync(pool, import_id).await; + publish(pool, 852).await; + join(&spawned).await; + assert_eq!(statuses(pool, import_id).await, ["published", "published"]); + let (present, position, op_id) = register(pool, road, 2).await.unwrap(); + assert!(present); + assert_eq!(position, 1); + assert!(op_id.starts_with("web_"), "{op_id}"); + assert_eq!(rows(pool, road).await, [(1001, 0), (1002, 1)]); + assert_consistent(pool, road).await; + fixture.drop().await; +} + +/// Extra acceptance item (P0): a removal written to the journal but not yet +/// applied to the register must keep the track out. +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_does_not_add_tracks_removed_by_unapplied_operations() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 3).await; + trust_remote(pool).await; + let import_id = matched_import( + pool, + "journal", + &[( + "Journal", + vec![Entry::Local(1), Entry::Unmatched, Entry::Unmatched], + )], + ) + .await; + publish(pool, 861).await; + let road = target(pool, import_id, 0).await.unwrap(); + + // Received from another device and committed; its application has not run. + let op = remote_op(REMOTE, 5, now_ms(), removed(road, 2)); + sqlx::query( + "INSERT INTO furumusic__fed_sync_ops + (user_id, op_id, origin_device_id, seq, kind, payload_json, hlc_ms, received_at_ms, tombstone) + VALUES ($1, $2, $3, $4, 'playlist_track_removed', $5, $6, $6, true)", + ) + .bind(USER) + .bind(&op.op_id) + .bind(&op.origin_device_id) + .bind(op.seq) + .bind(serde_json::to_value(&op.payload).unwrap()) + .bind(op.hlc_ms) + .execute(pool) + .await + .unwrap(); + assert!(register(pool, road, 2).await.is_none()); + set_entry(pool, import_id, 0, 1, Entry::Local(2)).await; + resync(pool, import_id).await; + publish(pool, 862).await; + assert_eq!(statuses(pool, import_id).await[1], "already_present"); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(2))).await, + 0 + ); + assert!(register(pool, road, 2).await.is_none()); + assert_eq!(rows(pool, road).await, [(1001, 0)]); + + // A removal that reaches the journal while the batch runs: the batch is + // repeated and leaves the track out as well. + set_entry(pool, import_id, 0, 2, Entry::Local(3)).await; + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + apply(&task_pool, remote_op(REMOTE, 6, 2, removed(road, 3))).await; + }); + tokio::time::sleep(Duration::from_millis(400)).await; + *slot.lock().unwrap() = Some(handle); + }) + }); + resync(pool, import_id).await; + publish(pool, 863).await; + join(&spawned).await; + assert_eq!(statuses(pool, import_id).await[2], "already_present"); + assert_eq!( + own_ops(pool, "playlist_track_added", Some(&cid(3))).await, + 0 + ); + assert!(!register(pool, road, 3).await.unwrap().0); + assert_eq!(rows(pool, road).await, [(1001, 0)]); + assert_consistent(pool, road).await; + fixture.drop().await; +} + +/// Extra acceptance item (P0): concurrent operations must not let the +/// register and the materialized playlist diverge. +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_registers_and_playlist_rows_stay_consistent_under_concurrent_sync() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 6).await; + trust_remote(pool).await; + let import_id = matched_import( + pool, + "concurrent", + &[( + "Concurrent", + vec![ + Entry::Local(1), + Entry::Unmatched, + Entry::Unmatched, + Entry::Unmatched, + ], + )], + ) + .await; + publish(pool, 871).await; + let road = target(pool, import_id, 0).await.unwrap(); + + // Two devices add and remove the same track at the same time. + let base = now_ms() + 1_000_000; + for round in 0..40i64 { + let add_wins = round % 2 == 1; + let (add_hlc, remove_hlc) = if add_wins { + (base + 2 * round + 1, base + 2 * round) + } else { + (base + 2 * round, base + 2 * round + 1) + }; + let add = remote_op(REMOTE, round + 1, add_hlc, added(road, 4, 10 + round)); + let remove = remote_op(REMOTE_B, round + 1, remove_hlc, removed(road, 4)); + if round % 4 < 2 { + tokio::join!(apply(pool, add), apply(pool, remove)); + } else { + tokio::join!(apply(pool, remove), apply(pool, add)); + } + assert_eq!(register(pool, road, 4).await.unwrap().0, add_wins); + assert_consistent(pool, road).await; + } + + // Operations applied while a batch publishes the same tracks. + set_entry(pool, import_id, 0, 1, Entry::Local(5)).await; + set_entry(pool, import_id, 0, 2, Entry::Local(6)).await; + set_entry(pool, import_id, 0, 3, Entry::Local(2)).await; + let spawned: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned)); + hooks::once(Point::BeforeAdd, move || { + Box::pin(async move { + let (removal_pool, stale_pool) = (hook_pool.clone(), hook_pool.clone()); + let later = now_ms() + 2_000_000; + let handle = tokio::spawn(async move { + tokio::join!( + apply( + &removal_pool, + remote_op(REMOTE, 100, later, removed(road, 5)) + ), + apply( + &stale_pool, + remote_op(REMOTE_B, 100, 1, added(road, 6, 999)) + ), + ); + }); + tokio::time::sleep(Duration::from_millis(200)).await; + *slot.lock().unwrap() = Some(handle); + }) + }); + // Later moves of the published track wait for the commit and then apply in order. + let spawned_after: Spawned = Arc::default(); + let (hook_pool, slot) = (pool.clone(), Arc::clone(&spawned_after)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let (first_pool, second_pool) = (hook_pool.clone(), hook_pool.clone()); + let later = now_ms() + 3_000_000; + let handle = tokio::spawn(async move { + tokio::join!( + apply( + &first_pool, + remote_op(REMOTE, 101, later, added(road, 2, 500)) + ), + apply( + &second_pool, + remote_op(REMOTE_B, 101, later + 1, added(road, 2, 600)) + ), + ); + }); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !handle.is_finished(), + "the operations wait for the register" + ); + *slot.lock().unwrap() = Some(handle); + }) + }); + resync(pool, import_id).await; + publish(pool, 872).await; + join(&spawned).await; + join(&spawned_after).await; + assert_eq!( + statuses(pool, import_id).await, + [ + "published", + "already_present", + "already_present", + "published" + ] + ); + assert!(!register(pool, road, 5).await.unwrap().0); + assert!(register(pool, road, 6).await.unwrap().0); + let (present, position, _) = register(pool, road, 2).await.unwrap(); + assert!(present); + assert_eq!(position, 600); + assert!(rows(pool, road).await.contains(&(1002, 600))); + assert_consistent(pool, road).await; + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_publications_of_one_user_run_one_after_another() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 4).await; + let first = matched_import( + pool, + "first", + &[("First", vec![Entry::Local(1), Entry::Local(2)])], + ) + .await; + let second: Arc>> = Arc::default(); + let spawned: Spawned = Arc::default(); + let (hook_pool, slot, second_id) = (pool.clone(), Arc::clone(&spawned), Arc::clone(&second)); + hooks::once(Point::BeforeCommit, move || { + Box::pin(async move { + let id = matched_import( + &hook_pool, + "second", + &[("Second", vec![Entry::Local(3), Entry::Local(4)])], + ) + .await; + *second_id.lock().unwrap() = Some(id); + let task_pool = hook_pool.clone(); + let handle = tokio::spawn(async move { + publish(&task_pool, 882).await; + }); + tokio::time::sleep(Duration::from_millis(500)).await; + // The second import waits for the first batch before it even + // creates its playlist. + let created: Option> = sqlx::query_scalar( + "SELECT target_created_at FROM furumusic__library_import_playlist WHERE import_id = $1", + ) + .bind(id) + .fetch_one(&hook_pool) + .await + .unwrap(); + assert!(created.is_none()); + assert!(!handle.is_finished()); + *slot.lock().unwrap() = Some(handle); + }) + }); + publish(pool, 881).await; + join(&spawned).await; + let second = second.lock().unwrap().unwrap(); + assert_eq!(fixture.status(first).await, "done"); + assert_eq!(fixture.status(second).await, "done"); + assert_eq!(statuses(pool, second).await, ["published", "published"]); + let (first_last, second_first): (i64, i64) = sqlx::query_as( + "SELECT max(seq) FILTER (WHERE payload_json->>'content_id' IN ($1, $2)), + min(seq) FILTER (WHERE payload_json->>'title' = 'Second') + FROM furumusic__fed_sync_ops WHERE user_id = $3", + ) + .bind(cid(1)) + .bind(cid(2)) + .bind(USER) + .fetch_one(pool) + .await + .unwrap(); + assert!(second_first > first_last); + fixture.drop().await; +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_defers_tracks_and_playlists_beyond_the_device_sync_budget() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 20).await; + let entries: Vec = (1..=20).map(Entry::Local).collect(); + let import_id = matched_import( + pool, + "budget", + &[("Budget", entries), ("Empty", vec![Entry::Unmatched])], + ) + .await; + let baseline = devices::outgoing_sync_line_size(pool, USER).await.unwrap(); + + // Not even an empty playlist fits: nothing is created. + let output = publish_with(pool, 891, Some(baseline.music_snapshot + 10)).await; + assert!( + output.contains("2 not created within the budget"), + "{output}" + ); + assert_eq!(target(pool, import_id, 0).await, None); + assert_eq!(target(pool, import_id, 1).await, None); + assert_eq!(own_ops(pool, "playlist_created", None).await, 0); + let deferred = statuses(pool, import_id).await; + assert!( + deferred[..20] + .iter() + .all(|status| status == "deferred_sync_limit") + ); + + // Room for the playlists and a few tracks: the first tracks in source order. + let budget = baseline.music_snapshot + 3_000; + resync(pool, import_id).await; + publish_with(pool, 892, Some(budget)).await; + let road = target(pool, import_id, 0).await.unwrap(); + let states = statuses(pool, import_id).await; + let published = states + .iter() + .filter(|status| *status == "published") + .count(); + assert!((1..20).contains(&published), "{states:?}"); + assert!( + states[..published] + .iter() + .all(|status| status == "published") + ); + assert!( + states[published..20] + .iter() + .all(|status| status == "deferred_sync_limit") + ); + let size = devices::outgoing_sync_line_size(pool, USER).await.unwrap(); + assert!(size.music_snapshot <= budget, "{size:?} > {budget}"); + + // With the default budget the rest follows at the end, in order. + resync(pool, import_id).await; + publish(pool, 893).await; + assert!( + statuses(pool, import_id).await[..20] + .iter() + .all(|status| status == "published") + ); + assert!(target(pool, import_id, 1).await.is_some()); + let positions: Vec = rows(pool, road) + .await + .into_iter() + .map(|row| row.1) + .collect(); + assert_eq!(positions, (0..20).collect::>()); + fixture.drop().await; +} + +/// Measures the outgoing line on a realistic import: 3000 federated and 200 +/// local matches. Run with `--nocapture` to see the numbers. +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_measures_the_outgoing_device_sync_line() { + let (_serial, fixture) = setup().await; + let pool = &fixture.pool; + library(pool, 200).await; + let mut entries: Vec = (1..=200).map(Entry::Local).collect(); + entries.extend((1..=3000).map(|n| Entry::Fed(10_000 + n))); + let import_id = matched_import(pool, "measure", &[("Large import", entries)]).await; + let before = devices::outgoing_sync_line_size(pool, USER).await.unwrap(); + let started = std::time::Instant::now(); + let output = publish(pool, 901).await; + let elapsed = started.elapsed(); + let after = devices::outgoing_sync_line_size(pool, USER).await.unwrap(); + let states = statuses(pool, import_id).await; + let published = states + .iter() + .filter(|status| *status == "published") + .count(); + let deferred = states + .iter() + .filter(|status| *status == "deferred_sync_limit") + .count(); + let ops_bytes: i64 = sqlx::query_scalar( + "SELECT COALESCE(sum(length(payload_json::text)), 0)::int8 FROM furumusic__fed_sync_ops WHERE user_id = $1", + ) + .bind(USER) + .fetch_one(pool) + .await + .unwrap(); + eprintln!( + "outgoing line before: {before:?}; after: {after:?}; published {published}, deferred {deferred}; \ + operation payloads {ops_bytes} bytes; publish took {elapsed:?}\n{output}" + ); + let budget = AppConfig::default().library_import_sync_budget; + assert!(after.music_snapshot <= budget); + assert!(after.full_line <= crate::library_import::publisher::HARD_LINE_LIMIT); + assert!(after.full_line > after.music_snapshot); + assert_eq!(published + deferred, 3200); + assert!(published > 2000, "{published}"); + fixture.drop().await; +} diff --git a/src/player/mod.rs b/src/player/mod.rs index a378022..15fdb61 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -7511,6 +7511,40 @@ async fn federation_artwork_discovery_handler( // POST /api/player/playlists — create playlist // --------------------------------------------------------------------------- +/// Inserts a private playlist owned by `user_id` in the caller's transaction. +/// Recording its Device Sync operation is up to the caller. +pub(crate) async fn create_owned_playlist_tx( + conn: &mut sqlx::PgConnection, + user_id: i64, + title: &str, + description: Option<&str>, +) -> sqlx::Result { + let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); + sqlx::query_scalar( + "INSERT INTO furumusic__playlist (owner_id, title, description, is_public, created_at, updated_at) \ + VALUES ($1, $2, $3, false, $4, $4) RETURNING id", + ) + .bind(user_id) + .bind(title) + .bind(description) + .bind(&now) + .fetch_one(conn) + .await +} + +/// [`create_owned_playlist_tx`] in a transaction of its own. +pub(crate) async fn create_owned_playlist( + pool: &sqlx::PgPool, + user_id: i64, + title: &str, + description: Option<&str>, +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let playlist_id = create_owned_playlist_tx(&mut tx, user_id, title, description).await?; + tx.commit().await?; + Ok(playlist_id) +} + async fn create_playlist_handler( auth_ctx: auth::AuthContext, session: Session, @@ -7525,22 +7559,14 @@ async fn create_playlist_handler( if title.is_empty() { return Ok(json_error(StatusCode::BAD_REQUEST, "title is required")); } - let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); - let row: (i64,) = sqlx::query_as( - "INSERT INTO furumusic__playlist (owner_id, title, is_public, created_at, updated_at) \ - VALUES ($1, $2, false, $3, $3) RETURNING id", - ) - .bind(user.id) - .bind(&title) - .bind(&now) - .fetch_one(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string()))?; + let playlist_id = create_owned_playlist(pool, user.id, &title, None) + .await + .map_err(|e| cot::Error::internal(e.to_string()))?; - record_fed_playlist_created(pool, user.id, row.0, &title).await; + record_fed_playlist_created(pool, user.id, playlist_id, &title).await; Json(PlaylistCard { - id: row.0, + id: playlist_id, cover_url: None, cover_urls: Vec::new(), title,