forked from Furumi/furumi-web
1410 lines
55 KiB
Rust
1410 lines
55 KiB
Rust
//! Public discovery of shared podcasts (`music_dht::podcast_dht`).
|
|
//!
|
|
//! The web server is one federation node that serves many accounts. Its
|
|
//! node identity (the persistent iroh key stored in PostgreSQL) is the only
|
|
//! key the server can sign with, so **the server node publishes**, never an
|
|
//! account: a card carries the server's key as `publisher` and nothing that
|
|
//! identifies the account (frid `PODCASTS.md`, "Card").
|
|
//!
|
|
//! # Rule for several accounts
|
|
//!
|
|
//! * A podcast is published only when at least one active account
|
|
//! explicitly shares it: `effective_share` of that account's merged registers holds
|
|
//! (subscribed, shared, and the share decision orders after the latest
|
|
//! subscription write). Every other podcast of every account is private
|
|
//! and produces no network traffic at all.
|
|
//! * The server publishes **one card per podcast**, whatever the number of
|
|
//! accounts sharing it. Cards are keyed by `(podcast_id, publisher)`, so
|
|
//! two accounts can never produce conflicting records: the card is built
|
|
//! from one sharing account (the *representative*, see
|
|
//! [`aggregate_share_states`]) and stays published while any account
|
|
//! still shares it.
|
|
//! * Revoking (share off, unsubscribing, on any device of the account)
|
|
//! removes the account from the set. The card is tombstoned when no
|
|
//! account shares the podcast any more. This is the §3 rule "turning
|
|
//! sharing off revokes the user's own publication and does not remove
|
|
//! publications made by other users": the card of the server publisher
|
|
//! holds no per-account data, so while another account still shares the
|
|
//! podcast nothing published is attributable to the account that
|
|
//! stopped; the shared card is the other account's publication.
|
|
//! * A late or stale device state cannot resurrect a publication: only the
|
|
//! merged registers count, and an old `shared = true` loses to the newer
|
|
//! share decision (`ShareRecord` LWW). [`PodcastDht::sync_shares`] is
|
|
//! declarative: everything not in the computed set is unpublished.
|
|
//!
|
|
//! # Privacy confirmation
|
|
//!
|
|
//! `PodcastShareState::privacy_confirmed` is client-held state. The web
|
|
//! keeps it per account in `furumusic__podcast_share_confirmation` (never
|
|
//! synced), bound to the share decision (`share_op_id`) and to the exact
|
|
//! card URLs the user confirmed. A card with privacy warnings
|
|
//! (`PodcastCardSpec::privacy_warnings`: a token in the query, a member-feed
|
|
//! host, ...) is published only when its account confirmed those URLs for
|
|
//! its current share decision; otherwise the podcast is *pending
|
|
//! confirmation* for that account and the account does not count as
|
|
//! sharing it. A share decision taken on another device (for example a TUI
|
|
//! that asked its own user) therefore still asks the web user, and a feed
|
|
//! that moves to a URL that looks private asks again.
|
|
//!
|
|
//! # Reconciler
|
|
//!
|
|
//! [`run`] recomputes the set and calls [`PodcastDht::sync_shares`] after
|
|
//! every change that can affect it ([`request_reconcile`]: share toggles,
|
|
//! subscribe and unsubscribe, received sync operations and snapshots, feed
|
|
//! refreshes of shared podcasts) and every [`RECONCILE_INTERVAL`].
|
|
//!
|
|
//! The first round of a federation run waits for the first device-sync
|
|
//! round (every trusted device polled answered, failed or timed out; at
|
|
//! most [`FIRST_DEVICE_SYNC_WAIT`]). The overlay withholds the cards it
|
|
//! published before the restart until the first `sync_shares`, which
|
|
//! re-sends the cards still shared. Without the wait that first call would
|
|
//! use the share decisions stored when the server stopped, so a podcast
|
|
//! whose sharing was turned off on a TUI meanwhile would be announced
|
|
//! again until the share-off arrived. A device that cannot be reached at
|
|
//! start still delivers its decision only when it syncs. A
|
|
//! failing database connection or query skips the round instead of
|
|
//! unpublishing everything (the overlay's own maintenance republishes the
|
|
//! cards in the meantime). Stored data of one `(account, podcast)` that
|
|
//! does not decode never skips the round: that pair counts as not shared
|
|
//! and every other podcast is reconciled ([`load_shared`]), so revocation
|
|
//! stays fail-safe for each podcast on its own.
|
|
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::sync::{Arc, OnceLock};
|
|
use std::time::Duration;
|
|
|
|
use anyhow::Result;
|
|
use music_dht::podcast::{FeedUrl, PodcastId, PodcastMeta, ShareRecord, SubscriptionRecord};
|
|
use music_dht::podcast_dht::{
|
|
FeedUrlPrivacyWarning, MAX_PODCAST_RECORDS_PER_PUBLISHER, PodcastCard, PodcastCardSpec,
|
|
PodcastDht, PodcastDhtSyncStats, PodcastShareState, PublishedPodcast,
|
|
};
|
|
use sqlx::{PgConnection, PgPool, Row};
|
|
use tokio::sync::{Notify, watch};
|
|
|
|
use super::{apply, feed_url_col, podcast_id_col};
|
|
|
|
/// Periodic reconciliation, also after missed notifications.
|
|
pub(crate) const RECONCILE_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
|
|
|
/// Wait after a change notification so that a burst of changes (a sync
|
|
/// batch, a refresh run) becomes one round.
|
|
pub(crate) const RECONCILE_DEBOUNCE: Duration = Duration::from_secs(2);
|
|
|
|
/// Longest wait of the first round for the first device-sync round of the
|
|
/// federation run (one exchange times out after 30 s).
|
|
pub(crate) const FIRST_DEVICE_SYNC_WAIT: Duration = Duration::from_secs(45);
|
|
|
|
/// Podcasts the server node publishes at most.
|
|
///
|
|
/// A replica keeps at most `MAX_PODCAST_RECORDS_PER_PUBLISHER` (256) records
|
|
/// of one publisher, tombstones included, and refuses a new
|
|
/// `(podcast_id, publisher)` key over it. The server is one publisher for
|
|
/// all of its accounts, so it keeps room for the tombstones of recently
|
|
/// revoked cards (they live 24 h). Podcasts beyond the cap stay unpublished
|
|
/// (see [`aggregate_share_states`]); a round also never asks for more keys
|
|
/// than replicas still accept ([`Incumbents::key_headroom`]).
|
|
pub(crate) const MAX_SERVER_SHARED_PODCASTS: usize = 192;
|
|
|
|
fn notifier() -> &'static Notify {
|
|
static NOTIFY: OnceLock<Notify> = OnceLock::new();
|
|
NOTIFY.get_or_init(Notify::new)
|
|
}
|
|
|
|
/// Asks the running reconciler (if any) for a round soon. Cheap and
|
|
/// idempotent; call it after committing a change.
|
|
pub(crate) fn request_reconcile() {
|
|
notifier().notify_one();
|
|
}
|
|
|
|
/// Whether the server's federation node runs public discovery, as shown
|
|
/// to the accounts.
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) enum Discovery<'a> {
|
|
/// Federation is not running on this server.
|
|
Off,
|
|
/// The federation node runs, but the overlay could not start (its
|
|
/// cache could not be opened): see the federation status.
|
|
Unavailable,
|
|
/// The overlay runs.
|
|
Running(&'a PodcastDht),
|
|
}
|
|
|
|
impl<'a> Discovery<'a> {
|
|
/// The overlay, when it runs.
|
|
pub(crate) fn dht(self) -> Option<&'a PodcastDht> {
|
|
match self {
|
|
Self::Running(dht) => Some(dht),
|
|
Self::Off | Self::Unavailable => None,
|
|
}
|
|
}
|
|
|
|
/// `running`, `unavailable` or `off`.
|
|
pub(crate) fn state(self) -> &'static str {
|
|
match self {
|
|
Self::Running(_) => "running",
|
|
Self::Unavailable => "unavailable",
|
|
Self::Off => "off",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A confirmation that an account may publish a card despite its privacy
|
|
/// warnings.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub(crate) struct ShareConfirmation {
|
|
/// Share decision the confirmation belongs to (`ShareRecord::op_id`).
|
|
pub(crate) share_op_id: String,
|
|
/// Confirmed `PodcastCardSpec::feed_url`.
|
|
pub(crate) feed_url: FeedUrl,
|
|
/// Confirmed `PodcastCardSpec::id_feed_url`.
|
|
pub(crate) id_feed_url: Option<FeedUrl>,
|
|
}
|
|
|
|
/// One account's view of the publication of one podcast.
|
|
#[derive(Debug, Clone)]
|
|
pub(crate) struct AccountShare {
|
|
/// Account.
|
|
pub(crate) user_id: i64,
|
|
/// Merged subscription register with its alias set.
|
|
pub(crate) subscription: SubscriptionRecord,
|
|
/// Merged share register.
|
|
pub(crate) share: Option<ShareRecord>,
|
|
/// Card this account would publish, or why it cannot be built.
|
|
pub(crate) card: Result<PodcastCardSpec, String>,
|
|
/// Stored privacy confirmation, if any (possibly stale).
|
|
pub(crate) confirmation: Option<ShareConfirmation>,
|
|
/// The catalog metadata comes from the server's own fetch of the feed,
|
|
/// not (yet) from a synced subscription register of a client.
|
|
pub(crate) meta_from_feed: bool,
|
|
}
|
|
|
|
impl AccountShare {
|
|
/// Whether the account's registers say "publish" (`effective_share`).
|
|
pub(crate) fn is_shared(&self) -> bool {
|
|
music_dht::podcast::effective_share(Some(&self.subscription), self.share.as_ref())
|
|
}
|
|
|
|
/// Privacy warnings of the card (empty when the card cannot be built).
|
|
pub(crate) fn warnings(&self) -> Vec<FeedUrlPrivacyWarning> {
|
|
self.card
|
|
.as_ref()
|
|
.map(PodcastCardSpec::privacy_warnings)
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// Whether the stored confirmation covers the current share decision
|
|
/// and exactly the current card URLs.
|
|
pub(crate) fn privacy_confirmed(&self) -> bool {
|
|
let (Some(confirmation), Some(share), Ok(card)) =
|
|
(&self.confirmation, &self.share, &self.card)
|
|
else {
|
|
return false;
|
|
};
|
|
confirmation.share_op_id == share.op_id
|
|
&& confirmation.feed_url == card.feed_url
|
|
&& confirmation.id_feed_url == card.id_feed_url
|
|
}
|
|
|
|
/// Shared, but the card has privacy warnings the account has not
|
|
/// confirmed for this share decision.
|
|
pub(crate) fn pending_confirmation(&self) -> bool {
|
|
self.is_shared()
|
|
&& self.card.is_ok()
|
|
&& !self.warnings().is_empty()
|
|
&& !self.privacy_confirmed()
|
|
}
|
|
|
|
/// Whether the catalog text comes from the server's own fetch of the
|
|
/// podcast's origin URL (the URL its id is derived from): an account
|
|
/// can point its synced catalog at any URL before the server fetches
|
|
/// it, so `meta_from_feed` alone says nothing about where the text
|
|
/// comes from.
|
|
pub(crate) fn trusted_meta(&self) -> bool {
|
|
self.meta_from_feed
|
|
&& self.card.as_ref().is_ok_and(|card| {
|
|
card.id_feed_url.is_none()
|
|
&& PodcastId::from_feed_url(&card.feed_url) == self.subscription.podcast_id
|
|
})
|
|
}
|
|
|
|
/// Whether the account counts as sharing the podcast publicly.
|
|
pub(crate) fn publishable(&self) -> bool {
|
|
self.is_shared()
|
|
&& self.card.is_ok()
|
|
&& (self.warnings().is_empty() || self.privacy_confirmed())
|
|
}
|
|
}
|
|
|
|
/// The card an account would publish: the public projection of its
|
|
/// subscription (`PodcastCardSpec::from_subscription`), with the URL it
|
|
/// fetches and the channel metadata from its catalog, the origin URL as
|
|
/// `id_feed_url` when the feed moved, and the feed's episode count and
|
|
/// newest publication time. Never progress, history, device or account
|
|
/// data.
|
|
pub(crate) fn build_card(
|
|
subscription: &SubscriptionRecord,
|
|
catalog: Option<&PodcastMeta>,
|
|
episode_count: Option<u32>,
|
|
latest_episode_at_ms: Option<i64>,
|
|
) -> Result<PodcastCardSpec, String> {
|
|
let mut card = PodcastCardSpec::from_subscription(subscription).map_err(|e| e.to_string())?;
|
|
let origin = card
|
|
.id_feed_url
|
|
.clone()
|
|
.unwrap_or_else(|| card.feed_url.clone());
|
|
if let Some(meta) = catalog {
|
|
card.feed_url = meta.feed_url.clone();
|
|
card.title = meta.title.clone();
|
|
card.author = meta.author.clone();
|
|
card.description = meta.description.clone();
|
|
card.link = meta.link.clone();
|
|
card.image_url = meta.image_url.clone();
|
|
}
|
|
card.id_feed_url = (origin != card.feed_url).then_some(origin);
|
|
card.episode_count = episode_count;
|
|
card.latest_episode_at_ms = latest_episode_at_ms;
|
|
let card = card.bounded();
|
|
card.validate().map_err(|e| e.to_string())?;
|
|
Ok(card)
|
|
}
|
|
|
|
async fn load_confirmation(
|
|
conn: &mut PgConnection,
|
|
user_id: i64,
|
|
podcast_id: &PodcastId,
|
|
) -> Result<Option<ShareConfirmation>> {
|
|
let row = sqlx::query(
|
|
"SELECT share_op_id, feed_url, id_feed_url
|
|
FROM furumusic__podcast_share_confirmation
|
|
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);
|
|
};
|
|
let id_feed_url = match row.try_get::<Option<String>, _>("id_feed_url")? {
|
|
Some(url) => match FeedUrl::try_from(url) {
|
|
Ok(url) => Some(url),
|
|
// A row that no longer parses confirms nothing.
|
|
Err(_) => return Ok(None),
|
|
},
|
|
None => None,
|
|
};
|
|
let Ok(feed_url) = feed_url_col(&row, "feed_url") else {
|
|
return Ok(None);
|
|
};
|
|
Ok(Some(ShareConfirmation {
|
|
share_op_id: row.try_get("share_op_id")?,
|
|
feed_url,
|
|
id_feed_url,
|
|
}))
|
|
}
|
|
|
|
/// Loads one account's publication view of a podcast; `None` without a
|
|
/// subscription register.
|
|
pub(crate) async fn load_account_share(
|
|
conn: &mut PgConnection,
|
|
user_id: i64,
|
|
podcast_id: &PodcastId,
|
|
) -> Result<Option<AccountShare>> {
|
|
let Some(subscription) = apply::load_subscription_register(conn, user_id, podcast_id).await?
|
|
else {
|
|
return Ok(None);
|
|
};
|
|
let share = apply::load_share(conn, user_id, podcast_id).await?;
|
|
let catalog = sqlx::query(
|
|
"SELECT feed_url, title, author, description, link, image_url, meta_from_feed
|
|
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 (catalog, meta_from_feed) = match catalog {
|
|
Some(row) => (
|
|
Some(PodcastMeta {
|
|
feed_url: 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")?,
|
|
}),
|
|
row.try_get("meta_from_feed")?,
|
|
),
|
|
None => (None, false),
|
|
};
|
|
// Episodes of the current feed document only: references learned from
|
|
// the account's own queue or progress (`source = 'sync'`) and episodes
|
|
// that left the feed are not part of the public projection.
|
|
let stats = sqlx::query(
|
|
"SELECT COUNT(*) AS episodes, MAX(published_at_ms) AS latest
|
|
FROM furumusic__podcast_episode
|
|
WHERE user_id = $1 AND podcast_id = $2 AND source = 'feed' AND in_feed",
|
|
)
|
|
.bind(user_id)
|
|
.bind(podcast_id.as_str())
|
|
.fetch_one(&mut *conn)
|
|
.await?;
|
|
let episodes: i64 = stats.try_get("episodes")?;
|
|
let latest: Option<i64> = stats.try_get("latest")?;
|
|
let episode_count = (episodes > 0).then(|| u32::try_from(episodes).unwrap_or(u32::MAX));
|
|
let card = build_card(&subscription, catalog.as_ref(), episode_count, latest);
|
|
let confirmation = load_confirmation(conn, user_id, podcast_id).await?;
|
|
Ok(Some(AccountShare {
|
|
user_id,
|
|
subscription,
|
|
share,
|
|
card,
|
|
confirmation,
|
|
meta_from_feed,
|
|
}))
|
|
}
|
|
|
|
/// The shared `(account, podcast)` pairs of one round.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub(crate) struct SharedLoad {
|
|
/// Readable pairs, for [`aggregate_share_states`].
|
|
pub(crate) shares: Vec<AccountShare>,
|
|
/// Pairs left out because a stored row of theirs does not decode (a
|
|
/// catalog or alias URL, the subscription register, a podcast id).
|
|
/// They count as not shared: fail closed for that pair only.
|
|
pub(crate) unreadable: usize,
|
|
}
|
|
|
|
/// Whether an error while loading one `(account, podcast)` comes from its
|
|
/// stored data (a value that does not decode) rather than from the
|
|
/// database connection or the query itself.
|
|
fn is_row_data_error(error: &anyhow::Error) -> bool {
|
|
match error.downcast_ref::<sqlx::Error>() {
|
|
Some(
|
|
sqlx::Error::Decode(_)
|
|
| sqlx::Error::ColumnDecode { .. }
|
|
| sqlx::Error::ColumnNotFound(_)
|
|
| sqlx::Error::ColumnIndexOutOfBounds { .. }
|
|
| sqlx::Error::TypeNotFound { .. },
|
|
) => true,
|
|
Some(_) => false,
|
|
// Decoding done in Rust (URLs, JSON registers, ids).
|
|
None => true,
|
|
}
|
|
}
|
|
|
|
/// Every `(account, podcast)` whose registers say subscribed and shared,
|
|
/// for active accounts only (a deactivated account publishes nothing),
|
|
/// optionally restricted to `users` (tests run against a shared database).
|
|
/// `effective_share` is decided in Rust ([`AccountShare::is_shared`]).
|
|
///
|
|
/// Revocation must stay fail-safe for every podcast on its own (frid
|
|
/// `PODCASTS.md`, "Publication"): a pair whose stored data does not decode
|
|
/// is left out and counted in [`SharedLoad::unreadable`] (so its card is
|
|
/// revoked unless another account shares the podcast), and the round goes
|
|
/// on for everyone else. Only a failing connection or query fails the
|
|
/// round.
|
|
pub(crate) async fn load_shared(pool: &PgPool, users: Option<&[i64]>) -> Result<SharedLoad> {
|
|
let mut conn = pool.acquire().await?;
|
|
let rows = sqlx::query(
|
|
"SELECT s.user_id, s.podcast_id
|
|
FROM furumusic__podcast_subscription s
|
|
JOIN furumusic__podcast_share sh
|
|
ON sh.user_id = s.user_id AND sh.podcast_id = s.podcast_id
|
|
JOIN furumusic__user u ON u.id = s.user_id AND u.is_active
|
|
WHERE s.subscribed AND sh.shared
|
|
AND ($1::BIGINT[] IS NULL OR s.user_id = ANY($1))
|
|
ORDER BY s.podcast_id COLLATE \"C\", s.user_id",
|
|
)
|
|
.bind(users)
|
|
.fetch_all(&mut *conn)
|
|
.await?;
|
|
let mut out = SharedLoad {
|
|
shares: Vec::with_capacity(rows.len()),
|
|
unreadable: 0,
|
|
};
|
|
for row in rows {
|
|
let user_id: i64 = row.try_get("user_id")?;
|
|
let Ok(podcast_id) = podcast_id_col(&row, "podcast_id") else {
|
|
out.unreadable += 1;
|
|
continue;
|
|
};
|
|
match load_account_share(&mut conn, user_id, &podcast_id).await {
|
|
Ok(Some(share)) => out.shares.push(share),
|
|
Ok(None) => {}
|
|
Err(error) if is_row_data_error(&error) => out.unreadable += 1,
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Result of [`aggregate_share_states`].
|
|
#[derive(Debug, Clone, Default)]
|
|
pub(crate) struct Aggregation {
|
|
/// One state per published podcast, sorted by podcast id.
|
|
pub(crate) states: Vec<PodcastShareState>,
|
|
/// Account that provides each published card.
|
|
pub(crate) representatives: BTreeMap<PodcastId, i64>,
|
|
/// Shared podcasts held back until their accounts confirm the privacy
|
|
/// warnings (no account confirmed).
|
|
pub(crate) pending_confirmation: usize,
|
|
/// Shared podcasts whose card cannot be built (no origin URL, invalid
|
|
/// metadata).
|
|
pub(crate) failed: usize,
|
|
/// Publishable podcasts left out by [`MAX_SERVER_SHARED_PODCASTS`]
|
|
/// (sorted).
|
|
pub(crate) over_limit: Vec<PodcastId>,
|
|
/// Shared `(account, podcast)` pairs left out because their stored data
|
|
/// does not decode ([`SharedLoad::unreadable`]).
|
|
pub(crate) unreadable: usize,
|
|
}
|
|
|
|
/// What the overlay publishes now: keeps the publication stable between
|
|
/// rounds and within what replicas accept.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub(crate) struct Incumbents {
|
|
/// Podcasts with an active card of this node (`PodcastDht::published`).
|
|
pub(crate) published: BTreeSet<PodcastId>,
|
|
/// Public text of every active card, so its representative is
|
|
/// recognized after a restart too ([`CardText`]).
|
|
pub(crate) cards: BTreeMap<PodcastId, CardText>,
|
|
/// Podcasts of which replicas still hold a record of this node: active
|
|
/// cards and tombstones that have not expired. Each one occupies a
|
|
/// `(podcast_id, publisher)` key in the replicas; republishing it
|
|
/// reuses the key.
|
|
pub(crate) live_keys: BTreeSet<PodcastId>,
|
|
/// Representative account of each card in the previous round (kept in
|
|
/// memory; empty after a restart, then [`Self::cards`] decides).
|
|
pub(crate) representatives: BTreeMap<PodcastId, i64>,
|
|
}
|
|
|
|
impl Incumbents {
|
|
/// What the overlay publishes at `now_ms` (unix milliseconds).
|
|
pub(crate) fn from_published(publications: &[PublishedPodcast], now_ms: u64) -> Self {
|
|
let mut incumbents = Self::default();
|
|
for publication in publications {
|
|
if publication.active {
|
|
incumbents.published.insert(publication.podcast_id.clone());
|
|
if let Some(card) = publication.record.card() {
|
|
incumbents
|
|
.cards
|
|
.insert(publication.podcast_id.clone(), CardText::of_card(card));
|
|
}
|
|
}
|
|
if publication.active || publication.record.expires_at_ms() > now_ms {
|
|
incumbents.live_keys.insert(publication.podcast_id.clone());
|
|
}
|
|
}
|
|
incumbents
|
|
}
|
|
|
|
/// Whether publishing `podcast_id` needs a key replicas do not hold
|
|
/// for this node yet.
|
|
fn needs_new_key(&self, podcast_id: &PodcastId) -> bool {
|
|
!self.published.contains(podcast_id) && !self.live_keys.contains(podcast_id)
|
|
}
|
|
|
|
/// New `(podcast_id, publisher)` keys replicas still accept from this
|
|
/// node: `MAX_PODCAST_RECORDS_PER_PUBLISHER` minus the records they
|
|
/// keep (active cards and unexpired tombstones, including the
|
|
/// tombstones of cards displaced in this very round, which replace
|
|
/// their card in place).
|
|
pub(crate) fn key_headroom(&self) -> usize {
|
|
let live = self.live_keys.union(&self.published).count();
|
|
MAX_PODCAST_RECORDS_PER_PUBLISHER.saturating_sub(live)
|
|
}
|
|
}
|
|
|
|
/// The public text of a card: what a representative decides.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub(crate) struct CardText {
|
|
feed_url: FeedUrl,
|
|
id_feed_url: Option<FeedUrl>,
|
|
title: String,
|
|
author: Option<String>,
|
|
description: Option<String>,
|
|
image_url: Option<String>,
|
|
link: Option<String>,
|
|
}
|
|
|
|
impl CardText {
|
|
fn of_spec(spec: &PodcastCardSpec) -> Self {
|
|
Self {
|
|
feed_url: spec.feed_url.clone(),
|
|
id_feed_url: spec.id_feed_url.clone(),
|
|
title: spec.title.clone(),
|
|
author: spec.author.clone(),
|
|
description: spec.description.clone(),
|
|
image_url: spec.image_url.clone(),
|
|
link: spec.link.clone(),
|
|
}
|
|
}
|
|
|
|
fn of_card(card: &PodcastCard) -> Self {
|
|
Self {
|
|
feed_url: card.feed_url.clone(),
|
|
id_feed_url: card.id_feed_url.clone(),
|
|
title: card.title.clone(),
|
|
author: card.author.clone(),
|
|
description: card.description.clone(),
|
|
image_url: card.image_url.clone(),
|
|
link: card.link.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Computes what the server node publishes from the accounts' views.
|
|
///
|
|
/// * Only accounts for which [`AccountShare::publishable`] holds count.
|
|
/// * One state per podcast, built from one *representative* account. Its
|
|
/// registers and card are passed with `privacy_confirmed = true` (no
|
|
/// warnings, or the account confirmed exactly these URLs for its current
|
|
/// share decision), so `sync_shares` never holds anything back on its
|
|
/// own. The representative is, in this order: an account whose card has
|
|
/// no privacy warnings; the *incumbent* (the previous round's
|
|
/// representative, or after a restart an account whose card has the
|
|
/// exact text of the published card), so another account sharing the
|
|
/// same podcast never takes over a published card; an account whose
|
|
/// catalog the server fetched itself from the podcast's origin URL
|
|
/// ([`AccountShare::trusted_meta`]); the smallest account id.
|
|
/// * At most [`MAX_SERVER_SHARED_PODCASTS`] podcasts, shared fairly between
|
|
/// the accounts ([`allocate`]): an account whose podcasts fit in its fair
|
|
/// part of the budget never loses a published card because of other
|
|
/// accounts, whatever their share times say. A round never asks for more
|
|
/// new keys than replicas accept ([`Incumbents::key_headroom`]): a
|
|
/// podcast that would need one waits (`over_limit`) until tombstones
|
|
/// expire, and no published card is displaced for it.
|
|
pub(crate) fn aggregate_share_states(
|
|
shares: Vec<AccountShare>,
|
|
incumbents: &Incumbents,
|
|
) -> Aggregation {
|
|
let mut aggregation = Aggregation::default();
|
|
let mut by_podcast: BTreeMap<PodcastId, Vec<AccountShare>> = BTreeMap::new();
|
|
for share in shares {
|
|
if !share.is_shared() {
|
|
continue;
|
|
}
|
|
by_podcast
|
|
.entry(share.subscription.podcast_id.clone())
|
|
.or_default()
|
|
.push(share);
|
|
}
|
|
let mut candidates: BTreeMap<PodcastId, AccountShare> = BTreeMap::new();
|
|
let mut queues: BTreeMap<i64, Vec<QueuedPodcast>> = BTreeMap::new();
|
|
for (podcast_id, accounts) in by_podcast {
|
|
let previous = incumbents.representatives.get(&podcast_id).copied();
|
|
let published_text = incumbents.cards.get(&podcast_id);
|
|
let publishable: Vec<&AccountShare> = accounts
|
|
.iter()
|
|
.filter(|share| share.publishable())
|
|
.collect();
|
|
let representative = publishable.iter().min_by_key(|share| {
|
|
let same_text = published_text.is_some_and(|published| {
|
|
share
|
|
.card
|
|
.as_ref()
|
|
.is_ok_and(|card| CardText::of_spec(card) == *published)
|
|
});
|
|
(
|
|
!share.warnings().is_empty(),
|
|
previous != Some(share.user_id),
|
|
!same_text,
|
|
!share.trusted_meta(),
|
|
share.user_id,
|
|
)
|
|
});
|
|
match representative {
|
|
Some(representative) => {
|
|
let published = incumbents.published.contains(&podcast_id);
|
|
for share in &publishable {
|
|
queues
|
|
.entry(share.user_id)
|
|
.or_default()
|
|
.push(QueuedPodcast {
|
|
newcomer: !published,
|
|
shared_at_ms: share.share.as_ref().map_or(i64::MAX, |r| r.hlc_ms),
|
|
podcast_id: podcast_id.clone(),
|
|
});
|
|
}
|
|
candidates.insert(podcast_id, (*representative).clone());
|
|
}
|
|
None if accounts.iter().any(AccountShare::pending_confirmation) => {
|
|
aggregation.pending_confirmation += 1;
|
|
}
|
|
None => aggregation.failed += 1,
|
|
}
|
|
}
|
|
let selected = allocate(queues, incumbents, MAX_SERVER_SHARED_PODCASTS);
|
|
for (podcast_id, share) in candidates {
|
|
if !selected.contains(&podcast_id) {
|
|
aggregation.over_limit.push(podcast_id);
|
|
continue;
|
|
}
|
|
let Ok(card) = share.card else {
|
|
continue;
|
|
};
|
|
aggregation
|
|
.representatives
|
|
.insert(podcast_id.clone(), share.user_id);
|
|
aggregation.states.push(PodcastShareState {
|
|
subscription: share.subscription,
|
|
share: share.share,
|
|
card: Some(card),
|
|
privacy_confirmed: true,
|
|
});
|
|
}
|
|
aggregation
|
|
}
|
|
|
|
/// One publishable podcast in an account's queue, in priority order.
|
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
|
struct QueuedPodcast {
|
|
/// Not published by this node yet (published cards come first).
|
|
newcomer: bool,
|
|
/// The account's own share decision time: it only orders the account's
|
|
/// own podcasts, never those of other accounts.
|
|
shared_at_ms: i64,
|
|
podcast_id: PodcastId,
|
|
}
|
|
|
|
/// Picks at most `budget` podcasts from the accounts' queues, round-robin:
|
|
/// every round each account (by id) takes its next podcast not picked yet
|
|
/// (a podcast several accounts share counts once and is free for the
|
|
/// others). Inside a round already published podcasts go first, so the
|
|
/// last, partial round never replaces a published card by a new one.
|
|
///
|
|
/// So with `n` sharing accounts every account keeps at least
|
|
/// `min(its podcasts, budget / n)` of them, its published ones first; only
|
|
/// podcasts of accounts beyond their fair part are left out (and revoked),
|
|
/// newest first.
|
|
///
|
|
/// A podcast that needs a new replica key ([`Incumbents::needs_new_key`])
|
|
/// is picked only while [`Incumbents::key_headroom`] lasts; otherwise it is
|
|
/// skipped (left out) and the account's next podcast is taken, so a
|
|
/// rebalance displaces at most as many published cards as replicas can
|
|
/// take new cards for.
|
|
fn allocate(
|
|
mut queues: BTreeMap<i64, Vec<QueuedPodcast>>,
|
|
incumbents: &Incumbents,
|
|
budget: usize,
|
|
) -> BTreeSet<PodcastId> {
|
|
for queue in queues.values_mut() {
|
|
// Popped from the end.
|
|
queue.sort_by(|left, right| right.cmp(left));
|
|
}
|
|
let mut new_keys_left = incumbents.key_headroom();
|
|
let mut selected = BTreeSet::new();
|
|
while selected.len() < budget {
|
|
let mut picks: Vec<(bool, i64, PodcastId)> = Vec::new();
|
|
for (user_id, queue) in &mut queues {
|
|
while let Some(next) = queue.pop() {
|
|
let podcast_id = next.podcast_id;
|
|
if selected.contains(&podcast_id)
|
|
|| picks.iter().any(|(_, _, picked)| *picked == podcast_id)
|
|
{
|
|
continue;
|
|
}
|
|
if incumbents.needs_new_key(&podcast_id) {
|
|
if new_keys_left == 0 {
|
|
continue;
|
|
}
|
|
new_keys_left -= 1;
|
|
}
|
|
picks.push((
|
|
!incumbents.published.contains(&podcast_id),
|
|
*user_id,
|
|
podcast_id,
|
|
));
|
|
break;
|
|
}
|
|
}
|
|
if picks.is_empty() {
|
|
break;
|
|
}
|
|
picks.sort();
|
|
for (_, _, podcast_id) in picks {
|
|
if selected.len() >= budget {
|
|
break;
|
|
}
|
|
selected.insert(podcast_id);
|
|
}
|
|
}
|
|
selected
|
|
}
|
|
|
|
/// Outcome of one reconciliation round.
|
|
#[derive(Debug, Clone)]
|
|
pub(crate) struct ReconcileReport {
|
|
/// What was computed.
|
|
pub(crate) aggregation: Aggregation,
|
|
/// What the overlay did.
|
|
pub(crate) stats: PodcastDhtSyncStats,
|
|
}
|
|
|
|
/// What the last round left over, kept in memory for the next round and
|
|
/// for the accounts' share status.
|
|
#[derive(Debug, Default)]
|
|
struct RoundMemory {
|
|
representatives: BTreeMap<PodcastId, i64>,
|
|
over_limit: BTreeSet<PodcastId>,
|
|
failed: BTreeSet<PodcastId>,
|
|
}
|
|
|
|
fn memory() -> std::sync::MutexGuard<'static, RoundMemory> {
|
|
static MEMORY: OnceLock<std::sync::Mutex<RoundMemory>> = OnceLock::new();
|
|
MEMORY
|
|
.get_or_init(Default::default)
|
|
.lock()
|
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
}
|
|
|
|
/// Why the last round did not publish a podcast that is shared and
|
|
/// publishable: `over_limit` (beyond the account's part of
|
|
/// [`MAX_SERVER_SHARED_PODCASTS`]) or `failed` (the overlay could not sign
|
|
/// or store its card). `None` otherwise or before the first round.
|
|
pub(crate) fn held_reason(podcast_id: &PodcastId) -> Option<&'static str> {
|
|
let memory = memory();
|
|
if memory.over_limit.contains(podcast_id) {
|
|
Some("over_limit")
|
|
} else if memory.failed.contains(podcast_id) {
|
|
Some("failed")
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// One round: load the shared podcasts of every account (or of `users`),
|
|
/// aggregate them against what the overlay publishes now and let it
|
|
/// publish and revoke.
|
|
pub(crate) async fn reconcile_once(
|
|
pool: &PgPool,
|
|
dht: &PodcastDht,
|
|
users: Option<&[i64]>,
|
|
) -> Result<ReconcileReport> {
|
|
let publications = dht
|
|
.published()
|
|
.await
|
|
.map_err(|error| anyhow::anyhow!("podcast publications unavailable: {error}"))?;
|
|
let load = load_shared(pool, users).await?;
|
|
let mut incumbents = Incumbents::from_published(&publications, unix_now_ms());
|
|
incumbents.representatives = memory().representatives.clone();
|
|
let mut aggregation = aggregate_share_states(load.shares, &incumbents);
|
|
aggregation.unreadable = load.unreadable;
|
|
let stats = dht
|
|
.sync_shares(aggregation.states.clone())
|
|
.await
|
|
.map_err(|error| anyhow::anyhow!("podcast publication failed: {error}"))?;
|
|
{
|
|
let mut memory = memory();
|
|
memory.representatives = aggregation.representatives.clone();
|
|
memory.over_limit = aggregation.over_limit.iter().cloned().collect();
|
|
memory.failed = stats
|
|
.failed
|
|
.iter()
|
|
.map(|failure| failure.podcast_id.clone())
|
|
.collect();
|
|
}
|
|
Ok(ReconcileReport { aggregation, stats })
|
|
}
|
|
|
|
fn unix_now_ms() -> u64 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.map_or(0, |elapsed| {
|
|
u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
|
|
})
|
|
}
|
|
|
|
/// Runs the reconciler until the task is aborted (federation stop).
|
|
///
|
|
/// The first round waits for `first_device_sync`, the first device-sync
|
|
/// round of this federation run (`federation::devices::sync_loop`), but at
|
|
/// most [`FIRST_DEVICE_SYNC_WAIT`]: see the module documentation.
|
|
pub(crate) async fn run(
|
|
pool: PgPool,
|
|
dht: Arc<PodcastDht>,
|
|
first_device_sync: watch::Receiver<bool>,
|
|
) {
|
|
run_rounds(pool, dht, first_device_sync, FIRST_DEVICE_SYNC_WAIT, None).await;
|
|
}
|
|
|
|
/// [`run`] with the longest first wait and the accounts (all when `None`)
|
|
/// as parameters.
|
|
pub(crate) async fn run_rounds(
|
|
pool: PgPool,
|
|
dht: Arc<PodcastDht>,
|
|
mut first_device_sync: watch::Receiver<bool>,
|
|
first_wait: Duration,
|
|
users: Option<Vec<i64>>,
|
|
) {
|
|
// A closed channel (the device-sync loop ended) does not wait either.
|
|
if tokio::time::timeout(first_wait, first_device_sync.wait_for(|done| *done))
|
|
.await
|
|
.is_err()
|
|
{
|
|
tracing::warn!(
|
|
seconds = first_wait.as_secs(),
|
|
"podcast publications: the first device-sync round did not end in time; \
|
|
publishing the stored share decisions"
|
|
);
|
|
}
|
|
let mut interval = tokio::time::interval(RECONCILE_INTERVAL);
|
|
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
|
loop {
|
|
tokio::select! {
|
|
_ = interval.tick() => {}
|
|
_ = notifier().notified() => tokio::time::sleep(RECONCILE_DEBOUNCE).await,
|
|
}
|
|
// Only counts are logged: never feed URLs, titles or accounts.
|
|
match reconcile_once(&pool, &dht, users.as_deref()).await {
|
|
Ok(report) => {
|
|
let stats = &report.stats;
|
|
let aggregation = &report.aggregation;
|
|
if stats.published > 0
|
|
|| stats.unpublished > 0
|
|
|| !stats.failed.is_empty()
|
|
|| !stats.held_back.is_empty()
|
|
|| !aggregation.over_limit.is_empty()
|
|
|| aggregation.unreadable > 0
|
|
{
|
|
tracing::info!(
|
|
shared = aggregation.states.len(),
|
|
published = stats.published,
|
|
unchanged = stats.unchanged,
|
|
unpublished = stats.unpublished,
|
|
failed = stats.failed.len(),
|
|
held_back = stats.held_back.len(),
|
|
pending_confirmation = aggregation.pending_confirmation,
|
|
over_limit = aggregation.over_limit.len(),
|
|
unreadable = aggregation.unreadable,
|
|
"podcast publications reconciled"
|
|
);
|
|
}
|
|
}
|
|
Err(error) => tracing::warn!("podcast publication round skipped: {error:#}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Confirmations (local, never synced)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// Records that the account confirmed publishing `card`'s URLs for the
|
|
/// share decision `share_op_id`.
|
|
pub(crate) async fn store_confirmation(
|
|
conn: &mut PgConnection,
|
|
user_id: i64,
|
|
podcast_id: &PodcastId,
|
|
confirmation: &ShareConfirmation,
|
|
now_ms: i64,
|
|
) -> Result<()> {
|
|
sqlx::query(
|
|
"INSERT INTO furumusic__podcast_share_confirmation
|
|
(user_id, podcast_id, share_op_id, feed_url, id_feed_url, confirmed_at_ms)
|
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
ON CONFLICT (user_id, podcast_id) DO UPDATE SET
|
|
share_op_id = EXCLUDED.share_op_id, feed_url = EXCLUDED.feed_url,
|
|
id_feed_url = EXCLUDED.id_feed_url, confirmed_at_ms = EXCLUDED.confirmed_at_ms",
|
|
)
|
|
.bind(user_id)
|
|
.bind(podcast_id.as_str())
|
|
.bind(&confirmation.share_op_id)
|
|
.bind(confirmation.feed_url.as_str())
|
|
.bind(confirmation.id_feed_url.as_ref().map(FeedUrl::as_str))
|
|
.bind(now_ms)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Forgets the account's confirmation (sharing turned off, unsubscribed).
|
|
pub(crate) async fn clear_confirmation(
|
|
conn: &mut PgConnection,
|
|
user_id: i64,
|
|
podcast_id: &PodcastId,
|
|
) -> Result<()> {
|
|
sqlx::query(
|
|
"DELETE FROM furumusic__podcast_share_confirmation
|
|
WHERE user_id = $1 AND podcast_id = $2",
|
|
)
|
|
.bind(user_id)
|
|
.bind(podcast_id.as_str())
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn url(path: &str) -> FeedUrl {
|
|
FeedUrl::parse(&format!("https://podcasts.example/{path}")).unwrap()
|
|
}
|
|
|
|
fn subscription(path: &str, generation: u64) -> SubscriptionRecord {
|
|
let feed_url = url(path);
|
|
SubscriptionRecord {
|
|
podcast_id: PodcastId::from_feed_url(&feed_url),
|
|
subscribed: true,
|
|
podcast: PodcastMeta {
|
|
feed_url: feed_url.clone(),
|
|
title: format!("Show {path}"),
|
|
author: Some("Host".into()),
|
|
description: None,
|
|
link: None,
|
|
image_url: None,
|
|
},
|
|
feed_aliases: vec![feed_url],
|
|
generation,
|
|
hlc_ms: 1_000,
|
|
op_id: format!("dev:{generation}"),
|
|
}
|
|
}
|
|
|
|
fn account(user_id: i64, path: &str, shared: bool, share_hlc: i64) -> AccountShare {
|
|
let subscription = subscription(path, 1);
|
|
let share = ShareRecord {
|
|
podcast_id: subscription.podcast_id.clone(),
|
|
shared,
|
|
generation: 2,
|
|
hlc_ms: share_hlc,
|
|
op_id: format!("u{user_id}:share"),
|
|
};
|
|
let card = build_card(&subscription, None, Some(3), Some(42));
|
|
AccountShare {
|
|
user_id,
|
|
subscription,
|
|
share: Some(share),
|
|
card,
|
|
confirmation: None,
|
|
meta_from_feed: true,
|
|
}
|
|
}
|
|
|
|
fn aggregate(shares: Vec<AccountShare>) -> Aggregation {
|
|
aggregate_share_states(shares, &Incumbents::default())
|
|
}
|
|
|
|
fn id(path: &str) -> PodcastId {
|
|
PodcastId::from_feed_url(&url(path))
|
|
}
|
|
|
|
fn confirm(share: &mut AccountShare) {
|
|
let card = share.card.clone().unwrap();
|
|
share.confirmation = Some(ShareConfirmation {
|
|
share_op_id: share.share.as_ref().unwrap().op_id.clone(),
|
|
feed_url: card.feed_url,
|
|
id_feed_url: card.id_feed_url,
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn one_card_per_podcast_from_the_smallest_sharing_account() {
|
|
let aggregation = aggregate(vec![
|
|
account(7, "a.xml", true, 10),
|
|
account(3, "a.xml", true, 20),
|
|
account(1, "a.xml", false, 30),
|
|
account(5, "b.xml", false, 10),
|
|
]);
|
|
assert_eq!(aggregation.states.len(), 1);
|
|
let state = &aggregation.states[0];
|
|
assert!(state.is_shared());
|
|
assert!(state.privacy_confirmed);
|
|
assert_eq!(
|
|
aggregation.representatives[&state.subscription.podcast_id],
|
|
3
|
|
);
|
|
let card = state.card.as_ref().unwrap();
|
|
assert_eq!(card.episode_count, Some(3));
|
|
assert_eq!(card.latest_episode_at_ms, Some(42));
|
|
assert!(card.id_feed_url.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_share_older_than_the_subscription_does_not_count() {
|
|
let mut stale = account(1, "a.xml", true, 10);
|
|
// Subscribed again after the share decision: private again.
|
|
stale.subscription.generation = 3;
|
|
let aggregation = aggregate(vec![stale]);
|
|
assert!(aggregation.states.is_empty());
|
|
assert_eq!(aggregation.failed, 0);
|
|
assert_eq!(aggregation.pending_confirmation, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn urls_that_look_private_need_the_accounts_own_confirmation() {
|
|
let secret = "feed.xml?token=8f3a9c2e7d1b4a6f";
|
|
let unconfirmed = account(1, secret, true, 10);
|
|
assert!(!unconfirmed.warnings().is_empty());
|
|
assert!(unconfirmed.pending_confirmation());
|
|
let aggregation = aggregate(vec![unconfirmed.clone()]);
|
|
assert!(aggregation.states.is_empty());
|
|
assert_eq!(aggregation.pending_confirmation, 1);
|
|
|
|
let mut confirmed = account(2, secret, true, 20);
|
|
confirm(&mut confirmed);
|
|
assert!(confirmed.publishable());
|
|
let aggregation = aggregate(vec![unconfirmed.clone(), confirmed.clone()]);
|
|
assert_eq!(aggregation.states.len(), 1);
|
|
assert_eq!(
|
|
aggregation
|
|
.representatives
|
|
.values()
|
|
.copied()
|
|
.collect::<Vec<_>>(),
|
|
vec![2]
|
|
);
|
|
|
|
// A new share decision (another op) needs a new confirmation.
|
|
let mut redecided = confirmed.clone();
|
|
redecided.share.as_mut().unwrap().op_id = "u2:share-again".into();
|
|
assert!(redecided.pending_confirmation());
|
|
// So does a feed that moved to other URLs.
|
|
let mut moved = confirmed;
|
|
moved.card.as_mut().unwrap().feed_url = url("other.xml?token=8f3a9c2e7d1b4a6f");
|
|
assert!(!moved.privacy_confirmed());
|
|
}
|
|
|
|
#[test]
|
|
fn an_account_without_warnings_is_preferred_as_representative() {
|
|
let mut moved_secret = account(1, "a.xml", true, 10);
|
|
// Account 1 fetches the feed from a URL that looks private.
|
|
moved_secret.card = build_card(
|
|
&moved_secret.subscription,
|
|
Some(&PodcastMeta {
|
|
feed_url: url("a.xml?key=8f3a9c2e7d1b4a6f"),
|
|
..moved_secret.subscription.podcast.clone()
|
|
}),
|
|
None,
|
|
None,
|
|
);
|
|
confirm(&mut moved_secret);
|
|
let plain = account(9, "a.xml", true, 20);
|
|
let aggregation = aggregate(vec![moved_secret, plain]);
|
|
assert_eq!(
|
|
aggregation
|
|
.representatives
|
|
.values()
|
|
.copied()
|
|
.collect::<Vec<_>>(),
|
|
vec![9]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn inside_an_account_the_longest_shared_podcasts_go_first() {
|
|
let shares = (0..MAX_SERVER_SHARED_PODCASTS + 3)
|
|
.map(|index| account(1, &format!("{index}.xml"), true, 1_000 - index as i64))
|
|
.collect();
|
|
let aggregation = aggregate(shares);
|
|
assert_eq!(aggregation.states.len(), MAX_SERVER_SHARED_PODCASTS);
|
|
// The three most recently shared (largest hlc) are left out.
|
|
let mut left_out: Vec<PodcastId> =
|
|
(0..3).map(|index| id(&format!("{index}.xml"))).collect();
|
|
left_out.sort();
|
|
assert_eq!(aggregation.over_limit, left_out);
|
|
}
|
|
|
|
#[test]
|
|
fn many_shares_of_another_account_never_unpublish_a_card() {
|
|
// A's card is published. B (a device with a lagging or forged
|
|
// clock: share times near 0) shares far more than the cap.
|
|
let mine = account(1, "mine.xml", true, 5_000);
|
|
let theirs: Vec<AccountShare> = (0..300)
|
|
.map(|index| account(2, &format!("b{index}.xml"), true, index))
|
|
.collect();
|
|
let mut published: BTreeSet<PodcastId> = (0..MAX_SERVER_SHARED_PODCASTS - 1)
|
|
.map(|index| id(&format!("b{index}.xml")))
|
|
.collect();
|
|
published.insert(id("mine.xml"));
|
|
let incumbents = Incumbents {
|
|
published: published.clone(),
|
|
..Incumbents::default()
|
|
};
|
|
let mut shares = theirs;
|
|
shares.push(mine);
|
|
let aggregation = aggregate_share_states(shares, &incumbents);
|
|
let states: BTreeSet<PodcastId> = aggregation
|
|
.states
|
|
.iter()
|
|
.map(|state| state.subscription.podcast_id.clone())
|
|
.collect();
|
|
assert_eq!(states.len(), MAX_SERVER_SHARED_PODCASTS);
|
|
// Nothing published is displaced; only B's new podcasts wait.
|
|
assert_eq!(states, published);
|
|
assert_eq!(
|
|
aggregation.over_limit.len(),
|
|
300 - (MAX_SERVER_SHARED_PODCASTS - 1)
|
|
);
|
|
assert!(!aggregation.over_limit.contains(&id("mine.xml")));
|
|
}
|
|
|
|
#[test]
|
|
fn the_budget_is_shared_fairly_between_accounts() {
|
|
// B alone filled the budget; A shares five podcasts afterwards.
|
|
let mut shares: Vec<AccountShare> = (0..MAX_SERVER_SHARED_PODCASTS)
|
|
.map(|index| account(2, &format!("b{index}.xml"), true, index as i64))
|
|
.collect();
|
|
let published: BTreeSet<PodcastId> = shares
|
|
.iter()
|
|
.map(|share| share.subscription.podcast_id.clone())
|
|
.collect();
|
|
for index in 0..5 {
|
|
shares.push(account(1, &format!("a{index}.xml"), true, 10_000 + index));
|
|
}
|
|
let incumbents = Incumbents {
|
|
published,
|
|
..Incumbents::default()
|
|
};
|
|
let aggregation = aggregate_share_states(shares, &incumbents);
|
|
assert_eq!(aggregation.states.len(), MAX_SERVER_SHARED_PODCASTS);
|
|
for index in 0..5 {
|
|
assert_eq!(
|
|
aggregation
|
|
.representatives
|
|
.get(&id(&format!("a{index}.xml"))),
|
|
Some(&1),
|
|
"A gets its fair part"
|
|
);
|
|
}
|
|
// B, beyond its fair part, gives up its five most recently shared.
|
|
let mut left_out: Vec<PodcastId> = (MAX_SERVER_SHARED_PODCASTS - 5
|
|
..MAX_SERVER_SHARED_PODCASTS)
|
|
.map(|index| id(&format!("b{index}.xml")))
|
|
.collect();
|
|
left_out.sort();
|
|
assert_eq!(aggregation.over_limit, left_out);
|
|
|
|
// A podcast both share counts once and is free for both.
|
|
let shared = vec![
|
|
account(1, "both.xml", true, 1),
|
|
account(2, "both.xml", true, 1),
|
|
account(2, "b-only.xml", true, 2),
|
|
];
|
|
let selected = aggregate(shared);
|
|
assert_eq!(selected.states.len(), 2);
|
|
}
|
|
|
|
/// Selected podcasts that need a new replica key, and live keys.
|
|
fn keys_asked(aggregation: &Aggregation, incumbents: &Incumbents) -> usize {
|
|
let new_keys = aggregation
|
|
.states
|
|
.iter()
|
|
.filter(|state| incumbents.needs_new_key(&state.subscription.podcast_id))
|
|
.count();
|
|
incumbents.live_keys.union(&incumbents.published).count() + new_keys
|
|
}
|
|
|
|
#[test]
|
|
fn a_rebalance_never_asks_replicas_for_more_keys_than_they_accept() {
|
|
// B alone published the whole budget; A shares 96 new podcasts, so
|
|
// its fair part is 96, but replicas take only 256 - 192 = 64 new
|
|
// keys from this node (displaced cards keep theirs as tombstones).
|
|
let mut shares: Vec<AccountShare> = (0..MAX_SERVER_SHARED_PODCASTS)
|
|
.map(|index| account(2, &format!("b{index}.xml"), true, index as i64))
|
|
.collect();
|
|
let published: BTreeSet<PodcastId> = shares
|
|
.iter()
|
|
.map(|share| share.subscription.podcast_id.clone())
|
|
.collect();
|
|
for index in 0..96 {
|
|
shares.push(account(1, &format!("a{index}.xml"), true, 10_000 + index));
|
|
}
|
|
let incumbents = Incumbents {
|
|
live_keys: published.clone(),
|
|
published,
|
|
..Incumbents::default()
|
|
};
|
|
assert_eq!(
|
|
incumbents.key_headroom(),
|
|
MAX_PODCAST_RECORDS_PER_PUBLISHER - MAX_SERVER_SHARED_PODCASTS
|
|
);
|
|
let aggregation = aggregate_share_states(shares.clone(), &incumbents);
|
|
assert_eq!(aggregation.states.len(), MAX_SERVER_SHARED_PODCASTS);
|
|
assert!(keys_asked(&aggregation, &incumbents) <= MAX_PODCAST_RECORDS_PER_PUBLISHER);
|
|
let of = |user: i64| {
|
|
aggregation
|
|
.representatives
|
|
.values()
|
|
.filter(|representative| **representative == user)
|
|
.count()
|
|
};
|
|
let headroom = MAX_PODCAST_RECORDS_PER_PUBLISHER - MAX_SERVER_SHARED_PODCASTS;
|
|
assert_eq!(of(1), headroom, "A gets as many as replicas accept");
|
|
assert_eq!(of(2), MAX_SERVER_SHARED_PODCASTS - headroom);
|
|
// A's podcasts beyond the headroom wait; B's displaced ones too.
|
|
assert_eq!(aggregation.over_limit.len(), (96 - headroom) + headroom);
|
|
|
|
// The next round (the displaced cards are tombstones now) asks for
|
|
// nothing new and displaces nothing more until they expire.
|
|
let mut next = Incumbents::default();
|
|
for state in &aggregation.states {
|
|
next.published.insert(state.subscription.podcast_id.clone());
|
|
}
|
|
next.live_keys = incumbents
|
|
.live_keys
|
|
.union(&next.published)
|
|
.cloned()
|
|
.collect();
|
|
assert_eq!(next.key_headroom(), 0);
|
|
let again = aggregate_share_states(shares.clone(), &next);
|
|
let selected: BTreeSet<PodcastId> = again
|
|
.states
|
|
.iter()
|
|
.map(|state| state.subscription.podcast_id.clone())
|
|
.collect();
|
|
assert_eq!(selected, next.published, "nothing moves without headroom");
|
|
assert!(keys_asked(&again, &next) <= MAX_PODCAST_RECORDS_PER_PUBLISHER);
|
|
|
|
// Once the tombstones expired, A gets the rest of its fair part.
|
|
next.live_keys = next.published.clone();
|
|
let later = aggregate_share_states(shares, &next);
|
|
assert!(keys_asked(&later, &next) <= MAX_PODCAST_RECORDS_PER_PUBLISHER);
|
|
let of = |user: i64| {
|
|
later
|
|
.representatives
|
|
.values()
|
|
.filter(|representative| **representative == user)
|
|
.count()
|
|
};
|
|
assert_eq!(of(1), 96);
|
|
assert_eq!(of(2), 96);
|
|
}
|
|
|
|
#[test]
|
|
fn a_shared_tombstoned_podcast_reuses_its_key() {
|
|
// Every key is taken (192 cards, 64 tombstones): a podcast whose
|
|
// tombstone is still live can be published again, a new one waits.
|
|
let mut shares: Vec<AccountShare> = (0..MAX_SERVER_SHARED_PODCASTS - 1)
|
|
.map(|index| account(2, &format!("b{index}.xml"), true, index as i64))
|
|
.collect();
|
|
let published: BTreeSet<PodcastId> = shares
|
|
.iter()
|
|
.map(|share| share.subscription.podcast_id.clone())
|
|
.collect();
|
|
let mut live_keys = published.clone();
|
|
for index in 0..65 {
|
|
live_keys.insert(id(&format!("gone{index}.xml")));
|
|
}
|
|
shares.push(account(1, "gone0.xml", true, 1));
|
|
shares.push(account(1, "fresh.xml", true, 0));
|
|
let incumbents = Incumbents {
|
|
published,
|
|
live_keys,
|
|
..Incumbents::default()
|
|
};
|
|
assert_eq!(incumbents.key_headroom(), 0);
|
|
let aggregation = aggregate_share_states(shares, &incumbents);
|
|
assert_eq!(aggregation.representatives.get(&id("gone0.xml")), Some(&1));
|
|
assert_eq!(aggregation.over_limit, vec![id("fresh.xml")]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_published_card_keeps_its_representative() {
|
|
// Account 9 provides the published card; account 3 starts sharing
|
|
// the same podcast with other text.
|
|
let provider = account(9, "a.xml", true, 10);
|
|
let mut newcomer = account(3, "a.xml", true, 20);
|
|
newcomer.card.as_mut().unwrap().title = "Rewritten".into();
|
|
let published_card = CardText::of_spec(provider.card.as_ref().unwrap());
|
|
let incumbents = Incumbents {
|
|
published: BTreeSet::from([id("a.xml")]),
|
|
representatives: BTreeMap::from([(id("a.xml"), 9)]),
|
|
..Incumbents::default()
|
|
};
|
|
let aggregation =
|
|
aggregate_share_states(vec![provider.clone(), newcomer.clone()], &incumbents);
|
|
assert_eq!(aggregation.representatives[&id("a.xml")], 9);
|
|
assert_eq!(
|
|
aggregation.states[0].card.as_ref().unwrap().title,
|
|
"Show a.xml"
|
|
);
|
|
|
|
// After a restart (no memory) the published card's text names it.
|
|
let restarted = Incumbents {
|
|
published: BTreeSet::from([id("a.xml")]),
|
|
cards: BTreeMap::from([(id("a.xml"), published_card)]),
|
|
..Incumbents::default()
|
|
};
|
|
let aggregation =
|
|
aggregate_share_states(vec![provider.clone(), newcomer.clone()], &restarted);
|
|
assert_eq!(aggregation.representatives[&id("a.xml")], 9);
|
|
|
|
// The incumbent also outranks server-fetched metadata of another
|
|
// account: whoever shares first keeps the card's text.
|
|
let mut synced_provider = provider.clone();
|
|
synced_provider.meta_from_feed = false;
|
|
let aggregation =
|
|
aggregate_share_states(vec![synced_provider, newcomer.clone()], &incumbents);
|
|
assert_eq!(aggregation.representatives[&id("a.xml")], 9);
|
|
|
|
// Without an incumbent, metadata the server fetched from the origin
|
|
// URL wins over metadata a client synced, even for a smaller id.
|
|
newcomer.meta_from_feed = false;
|
|
let aggregation = aggregate(vec![provider, newcomer]);
|
|
assert_eq!(aggregation.representatives[&id("a.xml")], 9);
|
|
}
|
|
|
|
#[test]
|
|
fn metadata_fetched_from_another_url_is_not_trusted() {
|
|
// Account 3 synced a catalog URL of its choice (the origin stays
|
|
// in its aliases); the server fetched that URL, so `meta_from_feed`
|
|
// holds, but the text does not come from the podcast's origin.
|
|
let mut pointed = account(3, "a.xml", true, 10);
|
|
pointed.card = build_card(
|
|
&pointed.subscription,
|
|
Some(&PodcastMeta {
|
|
feed_url: url("elsewhere.xml"),
|
|
title: "Elsewhere".into(),
|
|
..pointed.subscription.podcast.clone()
|
|
}),
|
|
None,
|
|
None,
|
|
);
|
|
assert!(pointed.meta_from_feed);
|
|
assert!(!pointed.trusted_meta());
|
|
let origin = account(9, "a.xml", true, 20);
|
|
assert!(origin.trusted_meta());
|
|
let aggregation = aggregate(vec![pointed, origin]);
|
|
assert_eq!(aggregation.representatives[&id("a.xml")], 9);
|
|
}
|
|
|
|
#[test]
|
|
fn the_last_round_says_why_a_shared_podcast_is_not_published() {
|
|
let over = id("held-over-limit.xml");
|
|
let failed = id("held-failed.xml");
|
|
{
|
|
let mut memory = memory();
|
|
memory.over_limit.insert(over.clone());
|
|
memory.failed.insert(failed.clone());
|
|
}
|
|
assert_eq!(held_reason(&over), Some("over_limit"));
|
|
assert_eq!(held_reason(&failed), Some("failed"));
|
|
assert_eq!(held_reason(&id("held-none.xml")), None);
|
|
let mut memory = memory();
|
|
memory.over_limit.remove(&over);
|
|
memory.failed.remove(&failed);
|
|
}
|
|
|
|
#[test]
|
|
fn a_card_never_carries_personal_state() {
|
|
let share = account(1, "a.xml", true, 10);
|
|
let card = share.card.unwrap();
|
|
let json = serde_json::to_string(&card).unwrap();
|
|
for personal in [
|
|
"generation",
|
|
"op_id",
|
|
"hlc_ms",
|
|
"u1:share",
|
|
"dev:1",
|
|
"device",
|
|
] {
|
|
assert!(!json.contains(personal), "{personal} in {json}");
|
|
}
|
|
}
|
|
}
|