Files
furumi-web/src/podcasts/actions.rs
T
sanapachandClaude Opus 5.5 cfebe1898f Bound user-started feed and audio requests per account
Feed downloads and proxy streams have per-account and server-wide
limits, new subscriptions stop at 1000 per account, and scheduled
refreshes take accounts in turns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:12:38 +02:00

684 lines
26 KiB
Rust

//! Local user actions: they build the device-sync operation, append it to
//! the account's sync log with its stamp and apply it through the shared
//! code path, all in one transaction.
use anyhow::Result;
use music_dht::device_sync::{SyncOpPayload, SyncOpWire};
use music_dht::podcast::{
EpisodeId, FeedUrl, ListenSession, PodcastEpisodeRef, PodcastId, PodcastMeta, ProgressRecord,
ProgressStatus, effective_share, merge_feed_aliases, merge_listen_session,
next_podcast_generation, resolve_podcast_id,
};
use sqlx::{PgConnection, Row};
use super::apply::{self, ApplyOutcome};
use super::{PodcastStore, PodcastStoreError, invalid};
use crate::federation::devices;
/// Result of [`PodcastStore::subscribe`].
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SubscribeOutcome {
/// Podcast the URL resolved to (an existing one when the URL is a known
/// feed URL or alias).
pub(crate) podcast_id: PodcastId,
/// The podcast was already subscribed; no operation was emitted.
pub(crate) already_subscribed: bool,
/// Operations appended to the sync log (and applied).
pub(crate) ops: Vec<SyncOpWire>,
}
/// A listening session of this account as seen by the progress register.
///
/// Returned by explicit actions; periodic checkpoints of the session use its
/// `generation` ([`PodcastStore::checkpoint`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProgressSession {
/// Episode being played.
pub(crate) episode: PodcastEpisodeRef,
/// Session id (also the `ListenSession::session_id`).
pub(crate) session_id: String,
/// Generation of the session's latest explicit action.
pub(crate) generation: u64,
}
/// A progress register written by a local action.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ProgressWrite {
/// The register as written.
pub(crate) record: ProgressRecord,
/// The session after the action (its generation for later checkpoints).
pub(crate) session: ProgressSession,
/// Operation appended to the sync log.
pub(crate) op: SyncOpWire,
}
/// Result of [`PodcastStore::checkpoint`].
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CheckpointOutcome {
/// The checkpoint was written.
Written(Box<ProgressWrite>),
/// The register holds a greater generation (another device or an
/// explicit action took over). Nothing was written: stop writing at the
/// old generation, or continue locally with an explicit action
/// ([`PodcastStore::start_session`] / [`PodcastStore::seek`]).
Superseded {
/// Current register.
current: ProgressRecord,
},
/// This session already completed the episode at its generation; a
/// checkpoint would turn it back into "in progress". Nothing was written.
AlreadyCompleted {
/// Current register.
current: ProgressRecord,
},
}
#[derive(Debug, Clone, Copy)]
enum ExplicitAction {
Start(i64),
Seek(i64),
Restart,
MarkPlayed,
MarkUnplayed,
}
/// Validates the payload (with a provisional stamp), appends it to the sync
/// log with the next stamp of `device_id` and applies exactly that operation
/// through [`apply::apply_op`]. `make` receives the operation id, which
/// explicit actions without a session use as their session id.
pub(crate) async fn emit(
conn: &mut PgConnection,
user_id: i64,
device_id: &str,
make: impl Fn(&str) -> SyncOpPayload,
) -> Result<SyncOpWire> {
SyncOpWire {
op_id: "provisional".to_string(),
origin_device_id: device_id.to_string(),
seq: 0,
hlc_ms: 0,
payload: make("provisional"),
}
.validate_podcast()
.map_err(invalid)?;
let op = devices::append_local_op(conn, user_id, device_id, &make).await?;
match apply::apply_op(conn, user_id, &op).await? {
ApplyOutcome::Rejected(reason) => Err(invalid(reason)),
_ => Ok(op),
}
}
/// Resolves a feed URL against every known URL of every podcast of the
/// account: the alias sets, the catalog fetch URLs and the registers'
/// `podcast.feed_url` (`resolve_podcast_id`).
pub(crate) async fn resolve_podcast(
conn: &mut PgConnection,
user_id: i64,
url: &FeedUrl,
) -> Result<PodcastId> {
let rows = sqlx::query(
"SELECT podcast_id FROM furumusic__podcast_feed_alias
WHERE user_id = $1 AND feed_url = $2
UNION SELECT podcast_id FROM furumusic__podcast
WHERE user_id = $1 AND feed_url = $2
UNION SELECT podcast_id FROM furumusic__podcast_subscription
WHERE user_id = $1 AND podcast_json->>'feed_url' = $2",
)
.bind(user_id)
.bind(url.as_str())
.fetch_all(&mut *conn)
.await?;
let ids = rows
.iter()
.map(|row| super::podcast_id_col(row, "podcast_id"))
.collect::<sqlx::Result<Vec<_>>>()?;
Ok(resolve_podcast_id(url, ids.iter().map(|id| (id, url))))
}
async fn catalog_meta(
conn: &mut PgConnection,
user_id: i64,
podcast_id: &PodcastId,
) -> Result<Option<PodcastMeta>> {
let row = sqlx::query(
"SELECT feed_url, title, author, description, link, image_url
FROM furumusic__podcast WHERE user_id = $1 AND podcast_id = $2",
)
.bind(user_id)
.bind(podcast_id.as_str())
.fetch_optional(&mut *conn)
.await?;
let Some(row) = row else {
return Ok(None);
};
Ok(Some(PodcastMeta {
feed_url: super::feed_url_col(&row, "feed_url")?,
title: row.try_get("title")?,
author: row.try_get("author")?,
description: row.try_get("description")?,
link: row.try_get("link")?,
image_url: row.try_get("image_url")?,
}))
}
async fn share_payload(
conn: &mut PgConnection,
user_id: i64,
podcast_id: &PodcastId,
shared: bool,
) -> Result<SyncOpPayload> {
let subscription = apply::load_subscription_register(conn, user_id, podcast_id).await?;
let share = apply::load_share(conn, user_id, podcast_id).await?;
Ok(SyncOpPayload::PodcastShareSet {
podcast_id: podcast_id.clone(),
shared,
generation: next_podcast_generation(subscription.as_ref(), share.as_ref()),
})
}
/// The reference carried by operations: identity and display only.
fn op_ref(episode: &PodcastEpisodeRef) -> PodcastEpisodeRef {
let mut episode = episode.clone();
episode.progress_generation = None;
episode
}
impl PodcastStore {
/// Subscribes to the podcast of `podcast.feed_url` (explicit user action).
///
/// The URL is resolved against known feed URLs and aliases first, so
/// subscribing again, through a redirect target or from someone else's
/// card reuses the existing podcast with its progress and history. When
/// the podcast is already subscribed nothing is emitted. Otherwise one
/// `podcast_subscription_set` with generation
/// `next_podcast_generation(..)` and the known aliases is appended and
/// applied. The new subscription is private until
/// [`PodcastStore::set_shared`].
///
/// Pass the channel metadata of the fetched feed
/// (`ParsedFeed::to_podcast_meta(url)`), then ingest the episodes with
/// [`PodcastStore::apply_feed`].
pub(crate) async fn subscribe(
&self,
user_id: i64,
podcast: &PodcastMeta,
) -> Result<SubscribeOutcome> {
let meta = podcast.bounded();
meta.validate().map_err(invalid)?;
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
let podcast_id = resolve_podcast(&mut tx, user_id, &meta.feed_url).await?;
let current = apply::load_subscription_register(&mut tx, user_id, &podcast_id).await?;
if current.as_ref().is_some_and(|record| record.subscribed) {
return Ok(SubscribeOutcome {
podcast_id,
already_subscribed: true,
ops: Vec::new(),
});
}
let active: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM furumusic__podcast_subscription
WHERE user_id = $1 AND subscribed",
)
.bind(user_id)
.fetch_one(&mut *tx)
.await?;
if usize::try_from(active).unwrap_or(usize::MAX) >= super::MAX_SUBSCRIPTIONS_PER_ACCOUNT {
return Err(
PodcastStoreError::SubscriptionLimit(super::MAX_SUBSCRIPTIONS_PER_ACCOUNT).into(),
);
}
let share = apply::load_share(&mut tx, user_id, &podcast_id).await?;
let generation = next_podcast_generation(current.as_ref(), share.as_ref());
let aliases = merge_feed_aliases(
&podcast_id,
&apply::load_aliases(&mut tx, user_id, &podcast_id).await?,
std::slice::from_ref(&meta.feed_url),
);
let op = emit(&mut tx, user_id, &device_id, |_| {
SyncOpPayload::PodcastSubscriptionSet {
podcast_id: podcast_id.clone(),
subscribed: true,
podcast: meta.clone(),
feed_aliases: aliases.clone(),
generation,
}
})
.await?;
tx.commit().await?;
Ok(SubscribeOutcome {
podcast_id,
already_subscribed: false,
ops: vec![op],
})
}
/// Unsubscribes (explicit user action).
///
/// Emits `podcast_subscription_set { subscribed: false }` followed by
/// `podcast_share_set { shared: false }`, each with the next podcast
/// generation. Progress, sessions and the catalog are kept, so
/// subscribing again continues where the user stopped. Does nothing when
/// the podcast is not subscribed.
pub(crate) async fn unsubscribe(
&self,
user_id: i64,
podcast_id: &PodcastId,
) -> Result<Vec<SyncOpWire>> {
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
let Some(current) = apply::load_subscription_register(&mut tx, user_id, podcast_id).await?
else {
return Ok(Vec::new());
};
if !current.subscribed {
return Ok(Vec::new());
}
let share = apply::load_share(&mut tx, user_id, podcast_id).await?;
let generation = next_podcast_generation(Some(&current), share.as_ref());
let mut meta = catalog_meta(&mut tx, user_id, podcast_id)
.await?
.map(|meta| meta.bounded())
.unwrap_or_else(|| current.podcast.clone());
meta.feed_url = current.podcast.feed_url.clone();
let aliases = current.feed_aliases.clone();
let unsubscribe = emit(&mut tx, user_id, &device_id, |_| {
SyncOpPayload::PodcastSubscriptionSet {
podcast_id: podcast_id.clone(),
subscribed: false,
podcast: meta.clone(),
feed_aliases: aliases.clone(),
generation,
}
})
.await?;
let revoke_payload = share_payload(&mut tx, user_id, podcast_id, false).await?;
let revoke = emit(&mut tx, user_id, &device_id, |_| revoke_payload.clone()).await?;
tx.commit().await?;
Ok(vec![unsubscribe, revoke])
}
/// Sets the decision to publish the podcast to the federation.
///
/// Sharing needs an active subscription and is a no-op when the podcast
/// is already effectively shared (`effective_share`). Revoking is a no-op
/// when no share decision says `true`. The write uses the next podcast
/// generation, so it orders after the subscription it observed.
// The publication toggle is part of public discovery (MR-W3); until
// then only the tests call it.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) async fn set_shared(
&self,
user_id: i64,
podcast_id: &PodcastId,
shared: bool,
) -> Result<Vec<SyncOpWire>> {
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
let subscription = apply::load_subscription_register(&mut tx, user_id, podcast_id).await?;
let share = apply::load_share(&mut tx, user_id, podcast_id).await?;
if shared {
if !subscription
.as_ref()
.is_some_and(|record| record.subscribed)
{
return Err(PodcastStoreError::NotSubscribed(podcast_id.clone()).into());
}
if effective_share(subscription.as_ref(), share.as_ref()) {
return Ok(Vec::new());
}
} else if !share.as_ref().is_some_and(|record| record.shared) {
return Ok(Vec::new());
}
let payload = share_payload(&mut tx, user_id, podcast_id, shared).await?;
let op = emit(&mut tx, user_id, &device_id, |_| payload.clone()).await?;
tx.commit().await?;
Ok(vec![op])
}
async fn explicit_progress(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
session_id: Option<&str>,
carried_generation: Option<u64>,
action: ExplicitAction,
) -> Result<ProgressWrite> {
episode.validate().map_err(invalid)?;
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
let current = apply::load_progress(&mut tx, user_id, &episode.episode_id).await?;
let max_seen = current
.as_ref()
.map(|record| record.generation)
.into_iter()
.chain(carried_generation)
.max();
let generation = ProgressRecord::explicit_generation(max_seen);
let current_position = current.as_ref().map_or(0, |record| record.position_ms);
let (position_ms, status) = match action {
ExplicitAction::Start(position) | ExplicitAction::Seek(position) => {
(position, ProgressStatus::InProgress)
}
ExplicitAction::Restart => (0, ProgressStatus::InProgress),
ExplicitAction::MarkPlayed => (current_position, ProgressStatus::Completed),
ExplicitAction::MarkUnplayed => (0, ProgressStatus::NotStarted),
};
let reference = op_ref(episode);
let op = emit(&mut tx, user_id, &device_id, |op_id| {
SyncOpPayload::PodcastProgressSet {
episode_id: episode.episode_id.clone(),
podcast_id: episode.podcast_id.clone(),
position_ms,
status,
generation,
session_id: session_id.unwrap_or(op_id).to_string(),
episode: Some(reference.clone()),
}
})
.await?;
tx.commit().await?;
let record = op.podcast_progress().expect("progress payload");
Ok(ProgressWrite {
session: ProgressSession {
episode: episode.clone(),
session_id: record.session_id.clone(),
generation,
},
record,
op,
})
}
/// Starts a listening session at `position_ms` (explicit action).
///
/// The generation is `explicit_generation(max(local, carried_generation))`;
/// pass `PodcastEpisodeRef::progress_generation` of a queue item received
/// through a handoff as `carried_generation`. Ordinary Play resumes from
/// [`PodcastStore::resume_position_ms`].
pub(crate) async fn start_session(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
session_id: &str,
position_ms: i64,
carried_generation: Option<u64>,
) -> Result<ProgressWrite> {
self.explicit_progress(
user_id,
episode,
Some(session_id),
carried_generation,
ExplicitAction::Start(position_ms),
)
.await
}
/// Periodic checkpoint (or pause/stop save) of a running session.
///
/// Keeps the session generation. When the register already holds a
/// greater generation nothing is written ([`CheckpointOutcome::Superseded`]).
pub(crate) async fn checkpoint(
&self,
user_id: i64,
session: &ProgressSession,
position_ms: i64,
) -> Result<CheckpointOutcome> {
let episode = &session.episode;
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
if let Some(current) = apply::load_progress(&mut tx, user_id, &episode.episode_id).await? {
if current.generation > session.generation {
return Ok(CheckpointOutcome::Superseded { current });
}
if current.generation == session.generation
&& current.session_id == session.session_id
&& current.status == ProgressStatus::Completed
{
return Ok(CheckpointOutcome::AlreadyCompleted { current });
}
}
let reference = op_ref(episode);
let op = emit(&mut tx, user_id, &device_id, |_| {
SyncOpPayload::PodcastProgressSet {
episode_id: episode.episode_id.clone(),
podcast_id: episode.podcast_id.clone(),
position_ms,
status: ProgressStatus::InProgress,
generation: session.generation,
session_id: session.session_id.clone(),
episode: Some(reference.clone()),
}
})
.await?;
tx.commit().await?;
let record = op.podcast_progress().expect("progress payload");
Ok(CheckpointOutcome::Written(Box::new(ProgressWrite {
record,
session: session.clone(),
op,
})))
}
/// User seek during a session (explicit action; the returned session
/// carries the new generation for later checkpoints).
pub(crate) async fn seek(
&self,
user_id: i64,
session: &ProgressSession,
position_ms: i64,
) -> Result<ProgressWrite> {
self.explicit_progress(
user_id,
&session.episode,
Some(&session.session_id),
Some(session.generation),
ExplicitAction::Seek(position_ms),
)
.await
}
/// Completes a running session (end of stream or `reaches_completion`)
/// unless another write took over. Record the session itself with
/// [`PodcastStore::record_listen_session`].
///
/// Like [`PodcastStore::checkpoint`], nothing is written when the
/// register holds a greater generation ([`CheckpointOutcome::Superseded`])
/// or when this session already completed the episode
/// ([`CheckpointOutcome::AlreadyCompleted`]). Otherwise `completed` is
/// written with an explicit generation; the check and the write
/// happen in one transaction, so a periodic save after the end never
/// completes the episode twice.
pub(crate) async fn complete_if_current(
&self,
user_id: i64,
session: &ProgressSession,
position_ms: i64,
) -> Result<CheckpointOutcome> {
let episode = &session.episode;
episode.validate().map_err(invalid)?;
let device_id = devices::local_device_id(&self.pool, user_id).await?;
let mut tx = self.begin_write(user_id).await?;
let current = apply::load_progress(&mut tx, user_id, &episode.episode_id).await?;
if let Some(current) = current.as_ref() {
if current.generation > session.generation {
return Ok(CheckpointOutcome::Superseded {
current: current.clone(),
});
}
if current.session_id == session.session_id
&& current.status == ProgressStatus::Completed
{
return Ok(CheckpointOutcome::AlreadyCompleted {
current: current.clone(),
});
}
}
let generation = ProgressRecord::explicit_generation(
current
.as_ref()
.map(|record| record.generation)
.into_iter()
.chain(Some(session.generation))
.max(),
);
let reference = op_ref(episode);
let op = emit(&mut tx, user_id, &device_id, |_| {
SyncOpPayload::PodcastProgressSet {
episode_id: episode.episode_id.clone(),
podcast_id: episode.podcast_id.clone(),
position_ms,
status: ProgressStatus::Completed,
generation,
session_id: session.session_id.clone(),
episode: Some(reference.clone()),
}
})
.await?;
tx.commit().await?;
let record = op.podcast_progress().expect("progress payload");
Ok(CheckpointOutcome::Written(Box::new(ProgressWrite {
record,
session: ProgressSession {
episode: episode.clone(),
session_id: session.session_id.clone(),
generation,
},
op,
})))
}
/// "Start over": position 0, in progress, explicit generation.
pub(crate) async fn restart(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
session_id: &str,
) -> Result<ProgressWrite> {
self.explicit_progress(
user_id,
episode,
Some(session_id),
None,
ExplicitAction::Restart,
)
.await
}
/// "Mark played": status completed, explicit generation. Creates no
/// listening session and invents no listening time.
pub(crate) async fn mark_played(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
) -> Result<ProgressWrite> {
self.explicit_progress(user_id, episode, None, None, ExplicitAction::MarkPlayed)
.await
}
/// "Mark unplayed": status not started at position 0, explicit generation.
pub(crate) async fn mark_unplayed(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
) -> Result<ProgressWrite> {
self.explicit_progress(user_id, episode, None, None, ExplicitAction::MarkUnplayed)
.await
}
/// Records (or grows) a listening session of this account's device.
///
/// Sessions below the history threshold (`ListenSession::should_record`)
/// and versions that do not grow the stored session emit nothing.
/// `session.device_id` must be the account's web device id. The episode
/// reference defaults to the catalog's.
pub(crate) async fn record_listen_session(
&self,
user_id: i64,
session: &ListenSession,
episode: Option<&PodcastEpisodeRef>,
) -> Result<Option<SyncOpWire>> {
let device_id = devices::local_device_id(&self.pool, user_id).await?;
if session.device_id != device_id {
return Err(invalid(
"session device_id differs from the local device id",
));
}
session.validate().map_err(invalid)?;
if !session.should_record() {
return Ok(None);
}
let mut tx = self.begin_write(user_id).await?;
if let Some(current) = apply::load_session(&mut tx, user_id, &session.session_id).await? {
let merged = merge_listen_session(&current, session).map_err(invalid)?;
if merged == current {
return Ok(None);
}
}
let reference = match episode {
Some(episode) => Some(op_ref(episode)),
None => super::queries::episode_ref_in(&mut tx, user_id, &session.episode_id)
.await?
.map(|reference| op_ref(&reference)),
};
let op = emit(&mut tx, user_id, &device_id, |_| {
SyncOpPayload::PodcastListenRecorded {
session: session.clone(),
episode: reference.clone(),
}
})
.await?;
tx.commit().await?;
Ok(Some(op))
}
/// Makes sure the catalog knows an episode a queue item refers to.
///
/// Queue items received through a handoff carry a self-contained
/// `PodcastEpisodeRef`; the account may not have refreshed that feed yet.
/// The reference is recorded like one learned through sync
/// (`source = 'sync'`, never replacing feed metadata). Returns whether a
/// row was added. No register is written.
pub(crate) async fn ensure_episode(
&self,
user_id: i64,
episode: &PodcastEpisodeRef,
) -> Result<bool> {
episode.validate().map_err(invalid)?;
let mut tx = self.begin_write(user_id).await?;
let known = super::queries::episode_ref_in(&mut tx, user_id, &episode.episode_id)
.await?
.is_some();
if !known {
apply::ensure_episode_from_ref(&mut tx, user_id, episode).await?;
}
tx.commit().await?;
Ok(!known)
}
/// Resolves a feed URL to a podcast id: the existing podcast when the
/// URL is a known feed URL or alias (`resolve_podcast_id`), otherwise
/// the id a first subscription through this URL would derive.
#[cfg(test)]
pub(crate) async fn resolve_podcast_id(
&self,
user_id: i64,
url: &FeedUrl,
) -> Result<PodcastId> {
let mut conn = self.pool.acquire().await?;
resolve_podcast(&mut conn, user_id, url).await
}
/// The episode reference for queueing or progress actions (with
/// `progress_generation` set to the stored register's generation), or
/// `None` when the episode is unknown.
pub(crate) async fn episode_ref(
&self,
user_id: i64,
episode_id: &EpisodeId,
) -> Result<Option<PodcastEpisodeRef>> {
let mut conn = self.pool.acquire().await?;
super::queries::episode_ref_in(&mut conn, user_id, episode_id).await
}
}