forked from Furumi/furumi-web
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
f10e384650
commit
4d6a1513d9
13 files changed
+3316
-45
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
/// `<request origin>/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<Vec<DownloadProxy>> {
|
||||
|
||||
+237
-9
@@ -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<String> {
|
||||
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<String> {
|
||||
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<i64>,
|
||||
) -> Result<Option<String>> {
|
||||
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<OutgoingSyncSize> {
|
||||
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<SyncOpWire>,
|
||||
) -> Result<()> {
|
||||
apply_ops(pool, Arc::new(PlayerDeviceHub::default()), user_id, ops).await
|
||||
}
|
||||
|
||||
async fn apply_ops(
|
||||
pool: &sqlx::PgPool,
|
||||
hub: Arc<PlayerDeviceHub>,
|
||||
@@ -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<i64> = 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<Option<S
|
||||
Ok(value.and_then(|value| music_dht::normalize_content_id(&value)))
|
||||
}
|
||||
|
||||
async fn synced_fed_track_for_track(
|
||||
pub(crate) async fn synced_fed_track_for_track(
|
||||
pool: &sqlx::PgPool,
|
||||
track_id: i64,
|
||||
content_id: &str,
|
||||
@@ -4413,6 +4630,15 @@ async fn ops_for_peer(
|
||||
peer_device_id: &str,
|
||||
) -> Result<Vec<SyncOpWire>> {
|
||||
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<Vec<SyncOpWire>> {
|
||||
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(())
|
||||
}
|
||||
|
||||
+23
-11
@@ -86,7 +86,8 @@ pub async fn reconcile(pool: &PgPool, user_id: Option<i64>) -> 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<bool> {
|
||||
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<i32>,
|
||||
) -> anyhow::Result<bool> {
|
||||
let playlist: Option<i64> = 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
|
||||
|
||||
@@ -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<bool>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
@@ -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<ImportPath>,
|
||||
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<PlaylistPath>| {
|
||||
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,
|
||||
|
||||
@@ -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<Option<Stop>> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<String>,
|
||||
pub target_playlist_id: Option<i64>,
|
||||
/// 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<Vec<PublishTarget>> {
|
||||
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::<String, _>(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<String>,
|
||||
pub content_id: Option<String>,
|
||||
pub track_id: Option<i64>,
|
||||
pub fed: Option<Value>,
|
||||
}
|
||||
|
||||
/// 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<Vec<PublishEntry>> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
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<u64> {
|
||||
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<bool> {
|
||||
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<std::collections::HashMap<String, Receipt>> {
|
||||
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<String>,
|
||||
/// 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<i64> = 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<Option<&str>> = updates
|
||||
.iter()
|
||||
.map(|update| update.content_id.as_deref())
|
||||
.collect();
|
||||
let failed: Vec<bool> = 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<bool> {
|
||||
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<bool>,
|
||||
) -> sqlx::Result<ResyncOutcome> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let status: Option<String> = 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::<ImportStatus>) {
|
||||
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<RecreateOutcome> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let status: Option<String> = 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::<ImportStatus>(),
|
||||
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.
|
||||
|
||||
@@ -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<ItemRow> = 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;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+39
-13
@@ -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<i64> {
|
||||
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<i64> {
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user