forked from Furumi/furumi-web
Run public podcast discovery on the federation node
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0400a08718
commit
c17cd790a7
3 files changed
+249
-28
No files matched your search
+115
-14
@@ -1,43 +1,64 @@
|
||||
//! Informational publication of the protocol versions exposed by this peer.
|
||||
//! Informational publication of the protocol versions exposed by this peer,
|
||||
//! and observation of the peers' manifests for the podcast-discovery overlay.
|
||||
|
||||
use std::time::Duration;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::Result;
|
||||
use music_dht::StreamAcceptor;
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::StreamExt;
|
||||
use music_dht::capabilities::{
|
||||
CAPABILITIES_PROTOCOL_VERSION, CapabilityManifest, CapabilityMessage, JAM_ID, SIMILARITY_ID,
|
||||
read_message, write_message,
|
||||
CAPABILITIES_ALPN, CAPABILITIES_PROTOCOL_VERSION, CapabilityManifest, CapabilityMessage,
|
||||
JAM_ID, SIMILARITY_ID, read_message, write_message,
|
||||
};
|
||||
use music_dht::podcast_dht::PodcastDht;
|
||||
use music_dht::{EndpointId, MusicDhtService, StreamAcceptor};
|
||||
|
||||
use super::serve::AUDIO_PROTOCOL_VERSION;
|
||||
|
||||
fn local_manifest() -> CapabilityManifest {
|
||||
CapabilityManifest::frid("furumusic", env!("CARGO_PKG_VERSION"))
|
||||
/// How often known peers are considered for a manifest probe.
|
||||
const PROBE_INTERVAL: Duration = Duration::from_secs(5 * 60);
|
||||
/// A peer's manifest is probed again after this long.
|
||||
const REPROBE_AFTER: Duration = Duration::from_secs(60 * 60);
|
||||
/// Peers probed per round and in parallel.
|
||||
const PROBES_PER_ROUND: usize = 64;
|
||||
const PROBE_CONCURRENCY: usize = 8;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The manifest of this node. The public podcast-discovery overlay is
|
||||
/// advertised only while the node serves it (`podcast_dht`).
|
||||
fn local_manifest(podcast_dht: bool) -> CapabilityManifest {
|
||||
let manifest = CapabilityManifest::frid("furumusic", env!("CARGO_PKG_VERSION"))
|
||||
// The web server does not expose federation Jam yet.
|
||||
.without_protocol(JAM_ID)
|
||||
.with_protocol("audio", AUDIO_PROTOCOL_VERSION)
|
||||
.with_protocol(
|
||||
SIMILARITY_ID,
|
||||
music_dht::similarity::SIMILARITY_PROTOCOL_VERSION,
|
||||
)
|
||||
);
|
||||
if podcast_dht {
|
||||
manifest.with_podcast_dht()
|
||||
} else {
|
||||
manifest
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn serve(mut acceptor: StreamAcceptor) {
|
||||
pub async fn serve(mut acceptor: StreamAcceptor, podcast_dht: bool) {
|
||||
while let Some(stream) = acceptor.accept().await {
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = serve_one(stream).await {
|
||||
if let Err(error) = serve_one(stream, podcast_dht).await {
|
||||
tracing::debug!("capability stream failed: {error:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_one(mut stream: music_dht::ByteStream) -> Result<()> {
|
||||
async fn serve_one(mut stream: music_dht::ByteStream, podcast_dht: bool) -> Result<()> {
|
||||
let response = match read_message(&mut stream).await? {
|
||||
CapabilityMessage::Get {
|
||||
version: CAPABILITIES_PROTOCOL_VERSION,
|
||||
} => CapabilityMessage::Manifest {
|
||||
manifest: local_manifest(),
|
||||
manifest: local_manifest(podcast_dht),
|
||||
},
|
||||
CapabilityMessage::Get { version } => CapabilityMessage::Error {
|
||||
message: format!("unsupported capability protocol {version}"),
|
||||
@@ -52,13 +73,93 @@ async fn serve_one(mut stream: music_dht::ByteStream) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Probes the manifests of known peers and tells the podcast overlay which
|
||||
/// of them lack it ([`PodcastDht::note_peer_capabilities`]), so bootstrap
|
||||
/// stops dialing them. A peer that does not answer is left alone: the
|
||||
/// overlay only learns contacts that answer on its own protocol anyway.
|
||||
pub async fn probe_loop(service: Arc<MusicDhtService>, dht: Arc<PodcastDht>) {
|
||||
let mut probed: HashMap<EndpointId, Instant> = HashMap::new();
|
||||
let mut interval = tokio::time::interval(PROBE_INTERVAL);
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
interval.tick().await;
|
||||
let own = service.endpoint_id();
|
||||
probed.retain(|_, at| at.elapsed() < REPROBE_AFTER);
|
||||
let peers: Vec<EndpointId> = service
|
||||
.connected_peers()
|
||||
.into_iter()
|
||||
.chain(
|
||||
service
|
||||
.known_peers()
|
||||
.into_iter()
|
||||
.map(|contact| contact.peer_id),
|
||||
)
|
||||
.filter(|peer| *peer != own && !probed.contains_key(peer))
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.take(PROBES_PER_ROUND)
|
||||
.collect();
|
||||
let results = futures_util::stream::iter(peers.into_iter().map(|peer| {
|
||||
let service = Arc::clone(&service);
|
||||
async move { (peer, probe_peer(&service, peer).await) }
|
||||
}))
|
||||
.buffer_unordered(PROBE_CONCURRENCY)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
for (peer, result) in results {
|
||||
probed.insert(peer, Instant::now());
|
||||
match result {
|
||||
Ok(manifest) => {
|
||||
if let Err(error) = dht.note_peer_capabilities(peer, &manifest).await {
|
||||
tracing::debug!(%peer, "podcast overlay capability note failed: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::trace!(%peer, "peer capability probe unavailable: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_peer(service: &MusicDhtService, peer: EndpointId) -> Result<CapabilityManifest> {
|
||||
let mut stream =
|
||||
tokio::time::timeout(PROBE_TIMEOUT, service.open_stream(peer, CAPABILITIES_ALPN))
|
||||
.await
|
||||
.context("capability stream timed out")??;
|
||||
write_message(
|
||||
&mut stream,
|
||||
&CapabilityMessage::Get {
|
||||
version: CAPABILITIES_PROTOCOL_VERSION,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
stream.send.finish()?;
|
||||
let response = tokio::time::timeout(PROBE_TIMEOUT, read_message(&mut stream))
|
||||
.await
|
||||
.context("capability request timed out")??;
|
||||
let CapabilityMessage::Manifest { manifest } = response else {
|
||||
anyhow::bail!("peer did not return a capability manifest");
|
||||
};
|
||||
manifest.validate()?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_podcast_overlay_is_advertised_only_while_it_runs() {
|
||||
assert!(!local_manifest(false).supports_podcast_dht());
|
||||
let manifest = local_manifest(true);
|
||||
assert!(manifest.supports_podcast_dht());
|
||||
manifest.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_describes_only_supported_player_protocols() {
|
||||
let manifest = local_manifest();
|
||||
let manifest = local_manifest(false);
|
||||
assert_eq!(manifest.application, "furumusic");
|
||||
assert_eq!(
|
||||
manifest.protocols.get("audio"),
|
||||
|
||||
+55
-14
@@ -9,6 +9,11 @@
|
||||
//! for catalog metadata and, when enabled, compatible similarity embeddings;
|
||||
//! local playback and the local library remain independent of the network.
|
||||
//!
|
||||
//! The node also runs the public podcast-discovery overlay
|
||||
//! ([`podcast_discovery`], `music_dht::podcast_dht`): it publishes cards of
|
||||
//! the podcasts that accounts explicitly shared (`crate::podcasts::discovery`)
|
||||
//! under the server's node identity.
|
||||
//!
|
||||
//! Settings are the regular admin config entries (`federation_enabled`,
|
||||
//! `federation_network_id`, `federation_save_on_listen`) and apply on the fly —
|
||||
//! saving the settings starts, stops or re-joins the node without a server
|
||||
@@ -17,6 +22,7 @@
|
||||
mod capabilities;
|
||||
pub mod client;
|
||||
pub mod devices;
|
||||
pub(crate) mod podcast_discovery;
|
||||
mod receive;
|
||||
mod serve;
|
||||
mod similarity;
|
||||
@@ -30,6 +36,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use music_dht::capabilities::CAPABILITIES_ALPN;
|
||||
use music_dht::podcast_dht::{PODCAST_DHT_ALPN, PodcastDht};
|
||||
use music_dht::similarity_dht::SimilarityDht;
|
||||
use music_dht::similarity_lsh::SIMILARITY_DHT_ALPN;
|
||||
use music_dht::{
|
||||
@@ -60,6 +67,8 @@ const TRANSPORT_SAMPLE_LIMIT: usize = 16;
|
||||
struct Running {
|
||||
service: Arc<MusicDhtService>,
|
||||
similarity_dht: Arc<SimilarityDht>,
|
||||
/// Public podcast discovery; `None` when the overlay failed to start.
|
||||
podcast_dht: Option<Arc<PodcastDht>>,
|
||||
network_name: String,
|
||||
tasks: Vec<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
@@ -290,6 +299,9 @@ pub struct Federation {
|
||||
download_locks: std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
|
||||
pool: tokio::sync::OnceCell<PgPool>,
|
||||
running: tokio::sync::Mutex<Option<Running>>,
|
||||
/// The running podcast-discovery overlay, readable without waiting for
|
||||
/// `running` (held while the node starts).
|
||||
podcast_dht: std::sync::Mutex<Option<Arc<PodcastDht>>>,
|
||||
sync_lock: tokio::sync::Mutex<()>,
|
||||
supervisor_started: AtomicBool,
|
||||
recovery_count: AtomicU64,
|
||||
@@ -325,6 +337,7 @@ pub fn handle() -> Arc<Federation> {
|
||||
download_locks: std::sync::Mutex::new(Default::default()),
|
||||
pool: tokio::sync::OnceCell::new(),
|
||||
running: tokio::sync::Mutex::new(None),
|
||||
podcast_dht: std::sync::Mutex::new(None),
|
||||
sync_lock: tokio::sync::Mutex::new(()),
|
||||
supervisor_started: AtomicBool::new(false),
|
||||
recovery_count: AtomicU64::new(0),
|
||||
@@ -474,6 +487,7 @@ impl Federation {
|
||||
} else if recovery_only {
|
||||
return Ok(false);
|
||||
}
|
||||
*lock(&self.podcast_dht) = None;
|
||||
stop_running(guard.take()).await;
|
||||
} else if recovery_only {
|
||||
tracing::warn!(network = %network_name, "retrying stopped federation service");
|
||||
@@ -498,6 +512,7 @@ impl Federation {
|
||||
.schema_independent_stream_protocol(SIMILARITY_ALPN)
|
||||
.schema_independent_stream_protocol(SIMILARITY_DHT_ALPN)
|
||||
.schema_independent_stream_protocol(CAPABILITIES_ALPN)
|
||||
.schema_independent_stream_protocol(PODCAST_DHT_ALPN)
|
||||
.build()
|
||||
.map_err(|err| anyhow::anyhow!("invalid federation config: {err}"))?;
|
||||
let (service, mut events) =
|
||||
@@ -530,6 +545,14 @@ impl Federation {
|
||||
Arc::clone(&similarity_manager),
|
||||
));
|
||||
|
||||
// Public podcast discovery: the server node publishes the podcasts
|
||||
// accounts explicitly shared (see `crate::podcasts::discovery`).
|
||||
let podcast_discovery =
|
||||
podcast_discovery::start(&service, &self.data_dir, pool.clone()).await;
|
||||
let podcast_dht = podcast_discovery
|
||||
.as_ref()
|
||||
.map(|discovery| Arc::clone(&discovery.dht));
|
||||
|
||||
// Drain DHT events into the log; the channel is bounded.
|
||||
let event_task = tokio::spawn(async move {
|
||||
while let Some(event) = events.recv().await {
|
||||
@@ -588,7 +611,10 @@ impl Federation {
|
||||
let capabilities_acceptor = service
|
||||
.stream_acceptor(CAPABILITIES_ALPN)
|
||||
.map_err(|err| anyhow::anyhow!("failed to take the capabilities acceptor: {err}"))?;
|
||||
let capabilities_task = tokio::spawn(capabilities::serve(capabilities_acceptor));
|
||||
let capabilities_task = tokio::spawn(capabilities::serve(
|
||||
capabilities_acceptor,
|
||||
podcast_dht.is_some(),
|
||||
));
|
||||
let similarity_acceptor = service
|
||||
.stream_acceptor(SIMILARITY_ALPN)
|
||||
.map_err(|err| anyhow::anyhow!("failed to take the similarity acceptor: {err}"))?;
|
||||
@@ -599,23 +625,29 @@ impl Federation {
|
||||
Arc::clone(&self.transport_stats),
|
||||
));
|
||||
|
||||
let mut tasks = vec![
|
||||
event_task,
|
||||
sync_task,
|
||||
audio_task,
|
||||
catalog_task,
|
||||
device_task,
|
||||
device_sync_task,
|
||||
capabilities_task,
|
||||
similarity_task,
|
||||
similarity_dht_serve_task,
|
||||
similarity_dht_maintenance_task,
|
||||
similarity_dht_sync_task,
|
||||
];
|
||||
if let Some(discovery) = podcast_discovery {
|
||||
tasks.extend(discovery.tasks);
|
||||
}
|
||||
*lock(&self.podcast_dht) = podcast_dht.clone();
|
||||
*guard = Some(Running {
|
||||
service,
|
||||
similarity_dht,
|
||||
podcast_dht,
|
||||
network_name,
|
||||
tasks: vec![
|
||||
event_task,
|
||||
sync_task,
|
||||
audio_task,
|
||||
catalog_task,
|
||||
device_task,
|
||||
device_sync_task,
|
||||
capabilities_task,
|
||||
similarity_task,
|
||||
similarity_dht_serve_task,
|
||||
similarity_dht_maintenance_task,
|
||||
similarity_dht_sync_task,
|
||||
],
|
||||
tasks,
|
||||
});
|
||||
self.set_error(None);
|
||||
drop(guard);
|
||||
@@ -659,6 +691,7 @@ impl Federation {
|
||||
|
||||
async fn stop(&self) {
|
||||
let mut guard = self.running.lock().await;
|
||||
*lock(&self.podcast_dht) = None;
|
||||
stop_running(guard.take()).await;
|
||||
}
|
||||
|
||||
@@ -685,6 +718,12 @@ impl Federation {
|
||||
.context("federation is not running")
|
||||
}
|
||||
|
||||
/// The public podcast-discovery overlay, while the node runs it. Does
|
||||
/// not wait for a node that is starting or stopping.
|
||||
pub fn podcast_discovery(&self) -> Option<Arc<PodcastDht>> {
|
||||
lock(&self.podcast_dht).clone()
|
||||
}
|
||||
|
||||
async fn spawn_sync_soon(self: &Arc<Self>) {
|
||||
if let Ok(service) = self.service().await {
|
||||
let fed = Arc::clone(self);
|
||||
@@ -1018,6 +1057,8 @@ impl Federation {
|
||||
"last_rendezvous_error": health.last_rendezvous_error,
|
||||
"recovery_count": self.recovery_count.load(Ordering::Relaxed),
|
||||
"similarity_routing_peers": running.similarity_dht.known_peers(),
|
||||
"podcast_discovery": running.podcast_dht.is_some(),
|
||||
"podcast_discovery_peers": running.podcast_dht.as_ref().map(|dht| dht.known_peers()),
|
||||
"published_items": published,
|
||||
"transport": transport,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Runs the public podcast-discovery overlay (`music_dht::podcast_dht`) on
|
||||
//! the web server's federation node.
|
||||
//!
|
||||
//! The overlay shares the node's iroh endpoint and identity with the music
|
||||
//! DHT, like `similarity_dht`: its ALPN is registered as a
|
||||
//! schema-independent stream protocol, its routing contacts and replica
|
||||
//! cache live in `podcast-dht.sqlite3` in the federation data directory (a
|
||||
//! replaceable cache, not durable state), and the capability manifest
|
||||
//! advertises `podcast_dht` only while it runs. What the node publishes is
|
||||
//! decided by [`crate::podcasts::discovery`] for all accounts.
|
||||
//!
|
||||
//! Failing to open the overlay disables public discovery and nothing else:
|
||||
//! the federation node, the music DHT and private podcast sync keep running.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use music_dht::MusicDhtService;
|
||||
use music_dht::podcast_dht::{PODCAST_DHT_ALPN, PodcastDht};
|
||||
use sqlx::PgPool;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
/// Cache file of the overlay in the federation data directory.
|
||||
pub(crate) const CACHE_FILE: &str = "podcast-dht.sqlite3";
|
||||
|
||||
/// The running overlay and its tasks (serving, maintenance, publication
|
||||
/// reconciler, capability probes).
|
||||
pub(crate) struct PodcastDiscovery {
|
||||
pub(crate) dht: Arc<PodcastDht>,
|
||||
pub(crate) tasks: Vec<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
/// Opens the overlay on `service` (whose config registered
|
||||
/// [`PODCAST_DHT_ALPN`]) and starts its tasks. Returns `None`, with a
|
||||
/// warning, when the cache cannot be opened or the acceptor is unavailable.
|
||||
pub(crate) async fn start(
|
||||
service: &Arc<MusicDhtService>,
|
||||
data_dir: &Path,
|
||||
pool: PgPool,
|
||||
) -> Option<PodcastDiscovery> {
|
||||
let (dht, serve_task) = open(service, data_dir).await?;
|
||||
let tasks = vec![
|
||||
serve_task,
|
||||
tokio::spawn(Arc::clone(&dht).maintenance()),
|
||||
tokio::spawn(crate::podcasts::discovery::run(pool, Arc::clone(&dht))),
|
||||
tokio::spawn(super::capabilities::probe_loop(
|
||||
Arc::clone(service),
|
||||
Arc::clone(&dht),
|
||||
)),
|
||||
];
|
||||
tracing::info!("public podcast discovery started");
|
||||
Some(PodcastDiscovery { dht, tasks })
|
||||
}
|
||||
|
||||
/// Opens the overlay cache and serves overlay requests; the rest of
|
||||
/// [`start`] (maintenance, reconciler, probes) is not started.
|
||||
pub(crate) async fn open(
|
||||
service: &Arc<MusicDhtService>,
|
||||
data_dir: &Path,
|
||||
) -> Option<(Arc<PodcastDht>, JoinHandle<()>)> {
|
||||
let dht = match PodcastDht::open(Arc::clone(service), data_dir.join(CACHE_FILE)).await {
|
||||
Ok(dht) => dht,
|
||||
Err(error) => {
|
||||
tracing::warn!("public podcast discovery disabled: cannot open its cache: {error}");
|
||||
// Refuse overlay streams instead of queueing them.
|
||||
drop(service.stream_acceptor(PODCAST_DHT_ALPN));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let acceptor = match service.stream_acceptor(PODCAST_DHT_ALPN) {
|
||||
Ok(acceptor) => acceptor,
|
||||
Err(error) => {
|
||||
tracing::warn!("public podcast discovery disabled: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let serve_task = tokio::spawn(Arc::clone(&dht).serve(acceptor));
|
||||
Some((dht, serve_task))
|
||||
}
|
||||
Reference in new issue
Block a user