2 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov f88ef69c1a feat: store content-addressed lyrics in furumi-library 0.4.0
CI / check (push) Successful in 2m17s
Publish crates / build (push) Successful in 2m33s
Publish crates / publish-gitea (push) Successful in 16s
Publish crates / publish-crates-io (push) Successful in 17s
2026-11-23 16:31:49 +02:00
ab e09ba153a4 feat: add optional content-addressed lyrics protocol
CI / check (push) Successful in 2m19s
Publish crates / build (push) Successful in 2m31s
Publish crates / publish-crates-io (push) Successful in 22s
Publish crates / publish-gitea (push) Successful in 22s
2026-11-23 01:42:03 +02:00
13 changed files with 615 additions and 6 deletions

No files matched your search

+11
View File
@@ -375,3 +375,14 @@ architectural constraint:
projections or opaque placeholders. projections or opaque placeholders.
- A device's protocol version is what that device reported; relays never - A device's protocol version is what that device reported; relays never
substitute their own. substitute their own.
## Optional lyrics streams
The optional music-dht lyrics contract uses furumi/lyrics/1 independently of
audio, catalog and device-sync. A bounded JSON request identifies exact audio
bytes by canonical b3 content ID; the response returns bounded alternative
versions with provenance, plain text and/or LRC timestamps. Empty versions mean
unavailable. Each direction ends with EOF. Applications advertise lyrics: 1
only when serving it; older peers keep their existing wire layouts and simply
lack this ALPN. Fetching external metadata and selecting/displaying versions
remain application policy. Lyrics are never published into DHT records.
+19
View File
@@ -1,5 +1,24 @@
# Changelog # Changelog
## v0.7.1 — 2026-11-23
Releases `furumi-library 0.4.0` against `music-dht 0.7.0` so applications can use the same podcast and lyrics types. The SQLite library can now store alternative lyrics by audio content ID, merge peer copies with local edits, and remember explicitly removed versions.
## v0.7.0 — 2026-11-23
Releases `music-dht 0.7.0`. Other crate versions remain unchanged.
- Optional `music_dht::lyrics` contract on `furumi/lyrics/1`, addressed by
canonical audio content ID, with alternative plain/LRC texts, provenance,
language and instrumental markers.
- Bounded versioned JSON envelopes and shared validation/read/write helpers.
Applications advertise `lyrics: 1` only when serving it.
- Existing audio, catalog, DHT and sync layouts are unchanged; unsupported
peers simply lack this ALPN. External lookup and display remain application
responsibilities.
- Tests cover content/version validation, text/frame bounds, roundtrips and
real streams to both supporting and legacy peers.
## v0.6.0 — 2026-11-20 ## v0.6.0 — 2026-11-20
Releases `music-dht 0.6.0` and `furumi-library 0.3.0`. Releases `music-dht 0.6.0` and `furumi-library 0.3.0`.
Generated
+2 -2
View File
@@ -932,7 +932,7 @@ dependencies = [
[[package]] [[package]]
name = "furumi-library" name = "furumi-library"
version = "0.3.0" version = "0.4.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"blake3", "blake3",
@@ -2100,7 +2100,7 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]] [[package]]
name = "music-dht" name = "music-dht"
version = "0.6.0" version = "0.7.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://gt.hexor.cy/ab/frid"
[workspace.dependencies] [workspace.dependencies]
federation-net = { path = "crates/federation-net", version = "0.3.1" } federation-net = { path = "crates/federation-net", version = "0.3.1" }
music-dht = { path = "crates/music-dht", version = "0.6.0" } music-dht = { path = "crates/music-dht", version = "0.7.0" }
iroh = "1" iroh = "1"
iroh-base = "1" iroh-base = "1"
iroh-tickets = "1" iroh-tickets = "1"
+1 -1
View File
@@ -56,7 +56,7 @@ Use the published crates from crates.io:
[dependencies] [dependencies]
federation-net = "0.3.1" federation-net = "0.3.1"
music-dht = "0.6.0" music-dht = "0.6.0"
furumi-library = "0.3.0" furumi-library = "0.4.0"
``` ```
Start with the crate documentation: Start with the crate documentation:
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "furumi-library" name = "furumi-library"
version = "0.3.0" version = "0.4.0"
description = "Client-independent SQLite music library for Furumi players" description = "Client-independent SQLite music library for Furumi players"
readme = "README.md" readme = "README.md"
documentation = "https://docs.rs/furumi-library" documentation = "https://docs.rs/furumi-library"
+5
View File
@@ -11,6 +11,7 @@
//! (`podcasts.sqlite3`); the music library never stores episodes. //! (`podcasts.sqlite3`); the music library never stores episodes.
pub mod import; pub mod import;
pub mod lyrics;
pub mod models; pub mod models;
pub mod podcasts; pub mod podcasts;
@@ -93,6 +94,10 @@ CREATE TABLE IF NOT EXISTS tracks (
file_size_bytes INTEGER, file_size_bytes INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now')) created_at TEXT NOT NULL DEFAULT (datetime('now'))
); );
CREATE TABLE IF NOT EXISTS track_lyrics (
content_id TEXT PRIMARY KEY,
payload TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS track_artists ( CREATE TABLE IF NOT EXISTS track_artists (
track_id INTEGER NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, track_id INTEGER NOT NULL REFERENCES tracks(id) ON DELETE CASCADE,
artist_id INTEGER NOT NULL REFERENCES artists(id) ON DELETE CASCADE, artist_id INTEGER NOT NULL REFERENCES artists(id) ON DELETE CASCADE,
+216
View File
@@ -0,0 +1,216 @@
//! Local lyrics indexed by canonical audio identity, independent of file paths.
use crate::Library;
use anyhow::Result;
use music_dht::lyrics::{LyricsVersion, MAX_LYRICS_VERSIONS};
use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
/// Stable key for the text representations, independent of provider labels and IDs.
pub fn identity(version: &LyricsVersion) -> String {
let mut hash = blake3::Hasher::new();
for text in [&version.plain_text, &version.synced_lrc] {
hash.update(&[u8::from(text.is_some())]);
if let Some(text) = text {
hash.update(&(text.len() as u64).to_le_bytes());
hash.update(text.as_bytes());
}
}
hash.finalize().to_hex().to_string()
}
/// Appends distinct, validated alternatives while preserving local order and exclusions.
pub fn merge(
versions: &mut Vec<LyricsVersion>,
incoming: impl IntoIterator<Item = LyricsVersion>,
hidden: &HashSet<String>,
) {
let mut seen: HashSet<_> = versions.iter().map(identity).collect();
for mut version in incoming {
let id = identity(&version);
if versions.len() == MAX_LYRICS_VERSIONS {
break;
}
if !hidden.contains(&id) && seen.insert(id.clone()) && version.validate().is_ok() {
version.id = id;
versions.push(version);
}
}
}
/// Local alternatives and exclusions that prevent a deleted version resurfacing from a peer.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SavedLyrics {
/// Alternatives in display order, with locally edited versions first.
pub versions: Vec<LyricsVersion>,
/// Content-based identities of alternatives explicitly removed by the user.
pub hidden: HashSet<String>,
}
impl Library {
/// Reads the local lyrics for these audio bytes.
pub fn lyrics(&self, content_id: &str) -> Result<SavedLyrics> {
validate_content_id(content_id)?;
read(&self.lock(), content_id)
}
/// Keeps peer lyrics only when the corresponding audio has been imported.
pub fn merge_lyrics(&self, content_id: &str, versions: Vec<LyricsVersion>) -> Result<()> {
validate_content_id(content_id)?;
if versions.is_empty() {
return Ok(());
}
let mut db = self.lock();
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let local: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM tracks WHERE content_id=?1)",
[content_id],
|row| row.get(0),
)?;
if local {
let mut saved = read(&tx, content_id)?;
let before = saved.versions.len();
merge(&mut saved.versions, versions, &saved.hidden);
if saved.versions.len() != before {
write(&tx, content_id, &saved)?;
}
}
tx.commit()?;
Ok(())
}
/// Adds, replaces or removes an alternative on a local track.
///
/// Clients may supply a freshly computed audio identity for older tracks
/// that have yet to finish content ID backfill. If the track already has
/// an identity, the edit must still refer to those exact audio bytes.
pub fn edit_lyrics(
&self,
track_id: i64,
content_id: &str,
replaced: Option<&str>,
version: Option<LyricsVersion>,
) -> Result<SavedLyrics> {
validate_content_id(content_id)?;
let mut db = self.lock();
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
let current: Option<String> = tx
.query_row(
"SELECT content_id FROM tracks WHERE id=?1",
[track_id],
|row| row.get(0),
)
.optional()?
.ok_or_else(|| anyhow::anyhow!("The local track has been removed"))?;
anyhow::ensure!(
current.as_deref().is_none_or(|id| id == content_id),
"The local audio has changed"
);
let mut saved = read(&tx, content_id)?;
if let Some(id) = replaced {
saved.hidden.insert(id.to_owned());
saved.versions.retain(|entry| entry.id != id);
}
if let Some(mut version) = version {
version.validate()?;
let id = identity(&version);
saved.hidden.remove(&id);
saved.versions.retain(|entry| entry.id != id);
anyhow::ensure!(
saved.versions.len() < MAX_LYRICS_VERSIONS,
"This track already has 16 versions"
);
version.id = id;
saved.versions.insert(0, version);
}
write(&tx, content_id, &saved)?;
tx.commit()?;
Ok(saved)
}
}
fn validate_content_id(content_id: &str) -> Result<()> {
music_dht::lyrics::LyricsRequest::new(content_id)?;
Ok(())
}
fn read(db: &Connection, content_id: &str) -> Result<SavedLyrics> {
let json: Option<String> = db
.query_row(
"SELECT payload FROM track_lyrics WHERE content_id=?1",
[content_id],
|row| row.get(0),
)
.optional()?;
Ok(json
.map(|json| serde_json::from_str(&json))
.transpose()?
.unwrap_or_default())
}
fn write(tx: &Transaction<'_>, content_id: &str, saved: &SavedLyrics) -> Result<()> {
tx.execute(
"INSERT INTO track_lyrics (content_id, payload) VALUES (?1, ?2)
ON CONFLICT(content_id) DO UPDATE SET payload=excluded.payload",
(content_id, serde_json::to_string(saved)?),
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn version(text: &str) -> LyricsVersion {
LyricsVersion {
id: "peer-id".into(),
label: "Lyrics".into(),
source: "manual".into(),
source_id: None,
language: None,
plain_text: Some(text.into()),
synced_lrc: None,
instrumental: false,
}
}
#[test]
fn persists_only_for_local_audio_and_preserves_edits_across_merges() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("library.db");
let library = Library::open(&path).unwrap();
let content_id = format!("b3:{}", "a".repeat(64));
let peer = version("Peer lyrics");
library
.merge_lyrics(&content_id, vec![peer.clone()])
.unwrap();
assert!(library.lyrics(&content_id).unwrap().versions.is_empty());
library
.lock()
.execute_batch("INSERT INTO releases(id, title) VALUES (1, 'Release');")
.unwrap();
library
.lock()
.execute(
"INSERT INTO tracks(id, title, release_id, file_path, content_id)
VALUES (1, 'Track', 1, 'local.flac', ?1)",
[&content_id],
)
.unwrap();
library
.merge_lyrics(&content_id, vec![peer.clone(), peer.clone()])
.unwrap();
assert_eq!(library.lyrics(&content_id).unwrap().versions.len(), 1);
let editable = version("My lyrics");
let peer_key = identity(&peer);
library
.edit_lyrics(1, &content_id, Some(&peer_key), Some(editable.clone()))
.unwrap();
library.merge_lyrics(&content_id, vec![peer]).unwrap();
drop(library);
let saved = Library::open(&path).unwrap().lyrics(&content_id).unwrap();
assert_eq!(saved.versions.len(), 1);
assert_eq!(saved.versions[0].id, identity(&editable));
assert!(saved.hidden.contains(&peer_key));
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "music-dht" name = "music-dht"
version = "0.6.0" version = "0.7.0"
description = "Distributed music library search: a Kademlia-style DHT on top of federation-net" description = "Distributed music library search: a Kademlia-style DHT on top of federation-net"
readme = "README.md" readme = "README.md"
documentation = "https://docs.rs/music-dht" documentation = "https://docs.rs/music-dht"
+11
View File
@@ -290,3 +290,14 @@ cargo test -p music-dht --features podcast-feed
The integration test starts three real nodes in one process (they use Iroh's The integration test starts three real nodes in one process (they use Iroh's
public relay infrastructure), so it needs network access. public relay infrastructure), so it needs network access.
## Optional lyrics
The `lyrics` module defines `furumi/lyrics/1`: bounded versioned JSON requests
by canonical audio content ID and responses with alternative plain/LRC texts,
provenance, language and instrumental markers. Each direction ends with EOF.
Use `LyricsRequest::new`, `write_request` and `read_response_from`; finish the
send half after writing, and verify the echoed response content ID.
Applications register this ALPN and explicitly advertise `lyrics: 1` only when
serving it. Existing wire protocols remain unchanged. External enrichment and
display remain application policy; lyrics never enter DHT records.
+1
View File
@@ -96,6 +96,7 @@ pub mod device_sync;
mod dht; mod dht;
mod error; mod error;
pub mod jam; pub mod jam;
pub mod lyrics;
mod message; mod message;
mod node; mod node;
mod normalization; mod normalization;
+262
View File
@@ -0,0 +1,262 @@
//! Optional content-addressed lyrics, independent of audio/catalog wire layouts.
//!
//! One bounded JSON request and response per stream; writers finish their send
//! half after writing. Unsupported peers simply lack this ALPN/capability.
use crate::error::{MusicDhtError, Result};
use federation_net::ByteStream;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncReadExt};
/// Optional lyrics stream ALPN.
pub const LYRICS_ALPN: &[u8] = b"furumi/lyrics/1";
/// Version of the lyrics envelope.
pub const LYRICS_PROTOCOL_VERSION: u16 = 1;
/// Capability identifier; applications advertise it only when serving lyrics.
pub const LYRICS_ID: &str = "lyrics";
/// Maximum number of alternative texts returned for one content identity.
pub const MAX_LYRICS_VERSIONS: usize = 16;
/// Maximum UTF-8 bytes per plain or timed text.
pub const MAX_LYRICS_TEXT_BYTES: usize = 256 * 1024;
/// Maximum JSON response, including escaping overhead.
pub const MAX_LYRICS_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
/// Maximum request bytes.
pub const MAX_LYRICS_REQUEST_BYTES: usize = 1024;
/// Fetch all available versions for these exact audio bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LyricsRequest {
/// Envelope version.
pub version: u16,
/// Canonical `b3:<hex>` audio content identity, never a title match.
pub content_id: String,
}
impl LyricsRequest {
/// Constructs a validated request.
pub fn new(content_id: impl Into<String>) -> Result<Self> {
let request = Self {
version: LYRICS_PROTOCOL_VERSION,
content_id: content_id.into(),
};
request.validate()?;
Ok(request)
}
/// Rejects unsupported versions and noncanonical identities.
pub fn validate(&self) -> Result<()> {
if self.version != LYRICS_PROTOCOL_VERSION
|| crate::normalize_content_id(&self.content_id).as_ref() != Some(&self.content_id)
{
return Err(invalid(
"unsupported lyrics version or invalid content identity",
));
}
Ok(())
}
}
/// One alternative text; timed and plain representations belong together.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LyricsVersion {
/// Opaque identity scoped to this response's content identity.
pub id: String,
/// Human-readable version label.
pub label: String,
/// Provenance, for example `lrclib` or `manual`.
pub source: String,
/// Stable provider record id, when available.
pub source_id: Option<String>,
/// Optional BCP-47 language tag.
pub language: Option<String>,
/// Text without synchronization.
pub plain_text: Option<String>,
/// LRC text with line timestamps, including optional offset metadata.
pub synced_lrc: Option<String>,
/// Explicitly identified as instrumental.
pub instrumental: bool,
}
impl LyricsVersion {
/// Validates text bounds and requires actual text or an instrumental marker.
pub fn validate(&self) -> Result<()> {
for text in [&self.id, &self.label, &self.source] {
if text.trim().is_empty() || text.len() > 512 {
return Err(invalid("invalid lyrics metadata"));
}
}
for text in [&self.source_id, &self.language].into_iter().flatten() {
if text.len() > 512 {
return Err(invalid("lyrics metadata too large"));
}
}
for text in [&self.plain_text, &self.synced_lrc].into_iter().flatten() {
if text.len() > MAX_LYRICS_TEXT_BYTES {
return Err(invalid("lyrics text too large"));
}
}
let has_text = [&self.plain_text, &self.synced_lrc]
.into_iter()
.flatten()
.any(|v| !v.trim().is_empty());
if (!has_text && !self.instrumental) || (has_text && self.instrumental) {
return Err(invalid("lyrics must contain text or be instrumental"));
}
Ok(())
}
}
/// Versions ordered best first (timed before plain); empty means unavailable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LyricsResponse {
/// Envelope version.
pub version: u16,
/// Echo of the requested audio identity.
pub content_id: String,
/// Available alternatives, best first.
pub versions: Vec<LyricsVersion>,
}
impl LyricsResponse {
/// Validates envelope, content identity, version count and each text.
pub fn validate(&self) -> Result<()> {
LyricsRequest {
version: self.version,
content_id: self.content_id.clone(),
}
.validate()?;
if self.versions.len() > MAX_LYRICS_VERSIONS {
return Err(invalid("too many lyrics versions"));
}
let mut ids = std::collections::HashSet::new();
for version in &self.versions {
version.validate()?;
if !ids.insert(&version.id) {
return Err(invalid("duplicate lyrics version"));
}
}
Ok(())
}
}
/// Writes a request. Caller finishes the send half afterwards.
pub async fn write_request(stream: &mut ByteStream, value: &LyricsRequest) -> Result<()> {
value.validate()?;
write_json(stream, value, MAX_LYRICS_REQUEST_BYTES).await
}
/// Writes a response. Caller finishes the send half afterwards.
pub async fn write_response(stream: &mut ByteStream, value: &LyricsResponse) -> Result<()> {
value.validate()?;
write_json(stream, value, MAX_LYRICS_RESPONSE_BYTES).await
}
/// Reads a request through EOF with a strict byte bound.
pub async fn read_request_from<R: AsyncRead + Unpin>(reader: &mut R) -> Result<LyricsRequest> {
let value: LyricsRequest = read_json(reader, MAX_LYRICS_REQUEST_BYTES).await?;
value.validate()?;
Ok(value)
}
/// Reads a response through EOF with strict byte and semantic bounds.
pub async fn read_response_from<R: AsyncRead + Unpin>(reader: &mut R) -> Result<LyricsResponse> {
let value: LyricsResponse = read_json(reader, MAX_LYRICS_RESPONSE_BYTES).await?;
value.validate()?;
Ok(value)
}
async fn read_json<R: AsyncRead + Unpin, T: serde::de::DeserializeOwned>(
reader: &mut R,
max: usize,
) -> Result<T> {
let mut bytes = Vec::new();
reader
.take(max as u64 + 1)
.read_to_end(&mut bytes)
.await
.map_err(|e| MusicDhtError::Network(e.to_string()))?;
if bytes.len() > max {
return Err(invalid("lyrics frame too large"));
}
serde_json::from_slice(&bytes).map_err(invalid)
}
async fn write_json<T: Serialize>(stream: &mut ByteStream, value: &T, max: usize) -> Result<()> {
let bytes = serde_json::to_vec(value).map_err(invalid)?;
if bytes.len() > max {
return Err(invalid("lyrics frame too large"));
}
stream
.send
.write_all(&bytes)
.await
.map_err(|e| MusicDhtError::Network(e.to_string()))
}
fn invalid(error: impl std::fmt::Display) -> MusicDhtError {
MusicDhtError::Protocol(error.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn version() -> LyricsVersion {
LyricsVersion {
id: "1".into(),
label: "Original".into(),
source: "manual".into(),
source_id: None,
language: None,
plain_text: Some("hello".into()),
synced_lrc: None,
instrumental: false,
}
}
fn response() -> LyricsResponse {
LyricsResponse {
version: 1,
content_id: format!("b3:{}", "a".repeat(64)),
versions: vec![version()],
}
}
#[tokio::test]
async fn roundtrip_and_reject_incompatible_version() {
let value = response();
let bytes = serde_json::to_vec(&value).unwrap();
assert_eq!(
read_response_from(&mut bytes.as_slice()).await.unwrap(),
value
);
let mut bad = value;
bad.version = 2;
assert!(bad.validate().is_err());
assert!(LyricsRequest::new("not-a-content-id").is_err());
}
#[test]
fn semantic_limits() {
let mut value = response();
value.versions[0].plain_text = Some("x".repeat(MAX_LYRICS_TEXT_BYTES));
value.validate().unwrap();
value.versions[0].plain_text.as_mut().unwrap().push('x');
assert!(value.validate().is_err());
let mut value = response();
value.versions = (0..MAX_LYRICS_VERSIONS)
.map(|i| LyricsVersion {
id: i.to_string(),
..version()
})
.collect();
value.validate().unwrap();
value.versions.push(LyricsVersion {
id: "extra".into(),
..version()
});
assert!(value.validate().is_err());
assert!(
LyricsVersion {
plain_text: None,
..version()
}
.validate()
.is_err()
);
}
#[tokio::test]
async fn bounded_frames_and_empty_results() {
let bytes = vec![b'x'; MAX_LYRICS_REQUEST_BYTES + 1];
assert!(read_request_from(&mut bytes.as_slice()).await.is_err());
let value = LyricsResponse {
versions: vec![],
..response()
};
value.validate().unwrap();
}
}
+84
View File
@@ -0,0 +1,84 @@
//! Lyrics is an optional ALPN: compatible peers exchange texts, old peers keep
//! their DHT protocol and simply cannot serve the new stream.
use music_dht::lyrics::{self, LYRICS_ALPN, LyricsRequest, LyricsResponse, LyricsVersion};
use music_dht::{MusicDhtConfig, MusicDhtService, NetworkId};
use std::time::Duration;
#[tokio::test]
async fn optional_lyrics_stream_roundtrip_and_legacy_peer() {
tokio::time::timeout(Duration::from_secs(120), async {
let server_dir = tempfile::tempdir().unwrap();
let client_dir = tempfile::tempdir().unwrap();
let network = NetworkId::from_name(&server_dir.path().to_string_lossy());
let config = MusicDhtConfig::builder()
.data_dir(server_dir.path())
.network_id(network)
.schema_independent_stream_protocol(LYRICS_ALPN)
.build()
.unwrap();
let (server, _server_events) = MusicDhtService::start(config).await.unwrap();
let config = MusicDhtConfig::builder()
.data_dir(client_dir.path())
.network_id(network)
.build()
.unwrap();
let (legacy, _client_events) = MusicDhtService::start(config).await.unwrap();
legacy
.connect(server.ticket().await.unwrap())
.await
.unwrap();
let mut acceptor = server.stream_acceptor(LYRICS_ALPN).unwrap();
let task = tokio::spawn(async move {
let mut stream = acceptor.accept().await.unwrap();
let request = lyrics::read_request_from(&mut stream.recv).await.unwrap();
let response = LyricsResponse {
version: 1,
content_id: request.content_id,
versions: vec![LyricsVersion {
id: "original".into(),
label: "Original".into(),
source: "manual".into(),
source_id: None,
language: Some("en".into()),
plain_text: Some("Words".into()),
synced_lrc: Some("[00:01]Words".into()),
instrumental: false,
}],
};
lyrics::write_response(&mut stream, &response)
.await
.unwrap();
stream.send.finish().unwrap();
let _ = stream.send.stopped().await;
});
let request = LyricsRequest::new(format!("b3:{}", "a".repeat(64))).unwrap();
let mut stream = legacy
.open_stream(server.endpoint_id(), LYRICS_ALPN)
.await
.unwrap();
lyrics::write_request(&mut stream, &request).await.unwrap();
stream.send.finish().unwrap();
let response = lyrics::read_response_from(&mut stream.recv).await.unwrap();
assert_eq!(response.content_id, request.content_id);
assert_eq!(
response.versions[0].synced_lrc.as_deref(),
Some("[00:01]Words")
);
task.await.unwrap();
assert!(
server
.open_stream(legacy.endpoint_id(), LYRICS_ALPN)
.await
.is_err()
);
assert!(
!music_dht::capabilities::CapabilityManifest::frid("legacy", "1")
.protocols
.contains_key(lyrics::LYRICS_ID)
);
legacy.shutdown().await.unwrap();
server.shutdown().await.unwrap();
})
.await
.expect("lyrics integration timed out");
}