//! 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, target.target_playlist_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, Some(target_id)).await, BatchEnd::LeaseLost => Ok(Step::LeaseLost), } } /// Pauses the source playlist unless its target changed since it was /// read: a `…/recreate` meanwhile must not be undone. async fn pause(&mut self, source: i64, target: Option) -> Result { match store::pause_playlist(self.pool, self.import.id, self.run_id, source, target).await? { store::PauseOutcome::Paused => self.report.paused_playlists += 1, store::PauseOutcome::TargetChanged => {} store::PauseOutcome::LeaseLost => return Ok(Step::LeaseLost), } 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"); } }