Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e09ba153a4 | ||
|
|
e47348b21d | ||
|
|
8af4d2cbbc | ||
|
|
84c5eb571c | ||
|
|
987063d616 | ||
|
|
3046c3f924 | ||
|
|
ddea053e9d |
No files matched your search
@@ -0,0 +1,3 @@
|
||||
[registries.gitea]
|
||||
index = "sparse+https://gt.hexor.cy/api/packages/Furumi/cargo/"
|
||||
credential-provider = "cargo:token"
|
||||
@@ -2,6 +2,8 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "**"
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
@@ -20,6 +22,7 @@ jobs:
|
||||
toolchain: "1.97"
|
||||
components: rustfmt, clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: python3 -m unittest discover -s scripts -p 'test_*.py'
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo check --workspace --all-targets --all-features
|
||||
- run: cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Publish crates
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v[0-9]*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: crates-io-publish
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_NET_RETRY: 10
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: "1.97"
|
||||
components: rustfmt, clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: python3 -m unittest discover -s scripts -p 'test_*.py'
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo check --workspace --all-targets --all-features --locked
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
- run: cargo test --workspace --locked
|
||||
- name: Verify release packages once
|
||||
run: python3 scripts/publish_crates.py --dry-run
|
||||
|
||||
publish-crates-io:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: "1.97"
|
||||
- name: Publish to crates.io without rebuilding
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
run: python3 scripts/publish_crates.py --no-verify
|
||||
|
||||
publish-gitea:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: "1.97"
|
||||
- name: Publish mirror to Gitea without rebuilding
|
||||
env:
|
||||
CARGO_REGISTRIES_GITEA_TOKEN: ${{ secrets.CARGO_REGISTRIES_GITEA_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$CARGO_REGISTRIES_GITEA_TOKEN" ]; then
|
||||
echo "::error::Add the CARGO_REGISTRIES_GITEA_TOKEN repository Actions secret, then rerun this workflow."
|
||||
exit 1
|
||||
fi
|
||||
export CARGO_REGISTRIES_GITEA_TOKEN="Bearer $CARGO_REGISTRIES_GITEA_TOKEN"
|
||||
python3 scripts/publish_crates.py --registry gitea --no-verify
|
||||
@@ -375,3 +375,14 @@ architectural constraint:
|
||||
projections or opaque placeholders.
|
||||
- A device's protocol version is what that device reported; relays never
|
||||
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.
|
||||
+27
-2
@@ -1,6 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased — podcast discovery (`podcast_dht`)
|
||||
## 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
|
||||
|
||||
Releases `music-dht 0.6.0` and `furumi-library 0.3.0`.
|
||||
`federation-net` remains at `0.3.1`.
|
||||
|
||||
- Tag-driven CI verifies release packages once, then publishes to crates.io
|
||||
and the Furumi Gitea Cargo mirror in parallel jobs without recompiling.
|
||||
Already published versions are skipped independently in each registry.
|
||||
Authentication uses `CARGO_REGISTRY_TOKEN` and `CARGO_REGISTRIES_GITEA_TOKEN`.
|
||||
|
||||
### Podcast discovery (`podcast_dht`)
|
||||
|
||||
- `music-dht 0.6.0`: new `music_dht::podcast_dht` overlay for public podcast
|
||||
discovery on its own ALPN `furumi-fd/podcast-dht/1` (version 1) and its own
|
||||
@@ -38,7 +63,7 @@
|
||||
- The music DHT (`music-dht-v5`), `federation-net` and device-sync protocol v4
|
||||
are unchanged. See "Public discovery (podcast_dht)" in `PODCASTS.md`.
|
||||
|
||||
## Unreleased — podcast contract
|
||||
### Podcast contract and storage
|
||||
|
||||
- `music-dht 0.6.0` (breaking): new `music_dht::podcast` module with the shared
|
||||
podcast contract: canonical `FeedUrl`, `PodcastId`/`EpisodeId` derivation
|
||||
|
||||
Generated
+1
-1
@@ -2100,7 +2100,7 @@ checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
|
||||
|
||||
[[package]]
|
||||
name = "music-dht"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ repository = "https://gt.hexor.cy/ab/frid"
|
||||
|
||||
[workspace.dependencies]
|
||||
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-base = "1"
|
||||
iroh-tickets = "1"
|
||||
|
||||
@@ -50,13 +50,13 @@ crates/
|
||||
|
||||
## Using the libraries
|
||||
|
||||
Until crates are published to a registry, depend on the repository directly:
|
||||
Use the published crates from crates.io:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
federation-net = { git = "https://gt.hexor.cy/ab/frid.git" }
|
||||
music-dht = { git = "https://gt.hexor.cy/ab/frid.git" }
|
||||
furumi-library = { git = "https://gt.hexor.cy/ab/frid.git" }
|
||||
federation-net = "0.3.1"
|
||||
music-dht = "0.6.0"
|
||||
furumi-library = "0.3.0"
|
||||
```
|
||||
|
||||
Start with the crate documentation:
|
||||
@@ -80,6 +80,48 @@ The integration tests open real local sockets and establish iroh connections.
|
||||
Some rendezvous tests also use public discovery infrastructure, so a restricted
|
||||
sandbox may need explicit network permission.
|
||||
|
||||
## Publishing
|
||||
|
||||
Add these repository Actions secrets:
|
||||
|
||||
- `CARGO_REGISTRY_TOKEN`: a crates.io API token with publish access to
|
||||
`federation-net`, `music-dht` and `furumi-library`.
|
||||
- `CARGO_REGISTRIES_GITEA_TOKEN`: a raw Gitea personal access token with
|
||||
`write:package` and permission to publish under the `Furumi` organization.
|
||||
Create it under user Settings → Applications. The workflow adds the
|
||||
required `Bearer` prefix itself; no username secret is needed.
|
||||
|
||||
Update changed crate versions, workspace dependency requirements, `Cargo.lock`
|
||||
and `CHANGELOG.md`, then merge to `main`. Create `<crate>-v<version>` tags for
|
||||
the changed crates and one workspace release tag, for example:
|
||||
|
||||
```bash
|
||||
git tag -a music-dht-v0.6.0 -m 'music-dht 0.6.0'
|
||||
git tag -a furumi-library-v0.3.0 -m 'furumi-library 0.3.0'
|
||||
git tag -a v0.6.0 -m 'Frid podcast release'
|
||||
git push origin music-dht-v0.6.0 furumi-library-v0.3.0 v0.6.0
|
||||
```
|
||||
|
||||
Only the `v*` workspace tag triggers `.github/workflows/publish.yml`; the
|
||||
crate tags identify each package release without starting duplicate uploads.
|
||||
The workflow runs the workspace checks and verifies the release packages in
|
||||
one build job. Two publishing jobs then upload without rebuilding
|
||||
(`cargo publish --no-verify`), selecting missing versions independently in
|
||||
crates.io and the Gitea mirror at
|
||||
`https://gt.hexor.cy/api/packages/Furumi/cargo/`. The mirror includes all three
|
||||
crates, including an unchanged version missing there. Already published
|
||||
versions are skipped on retries; a registry lookup error fails the release
|
||||
instead of assuming absence. Mirrored manifests retain crates.io dependency
|
||||
references, so the mirror waits up to ten minutes for new workspace
|
||||
dependencies to appear in crates.io before packaging its uploads.
|
||||
|
||||
Preview the selection with `python3 scripts/publish_crates.py --plan`, or
|
||||
verify the packages without uploading with `--dry-run`. Add `--registry gitea`
|
||||
to preview or publish to the mirror. If a secret was
|
||||
missing or a publish failed, fix the cause and rerun the existing tag workflow;
|
||||
do not move release tags. Manual dispatch must select the release tag as its
|
||||
ref. Publication is performed by CI, not by the tagging commands above.
|
||||
|
||||
## License
|
||||
|
||||
Frid is released under the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
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"
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/music-dht"
|
||||
|
||||
@@ -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
|
||||
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.
|
||||
@@ -96,6 +96,7 @@ pub mod device_sync;
|
||||
mod dht;
|
||||
mod error;
|
||||
pub mod jam;
|
||||
pub mod lyrics;
|
||||
mod message;
|
||||
mod node;
|
||||
mod normalization;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Publish missing workspace versions together; Cargo orders their dependencies."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
INDEXES = {
|
||||
"crates-io": "https://index.crates.io/",
|
||||
"gitea": "https://gt.hexor.cy/api/packages/Furumi/cargo/",
|
||||
}
|
||||
|
||||
|
||||
def index_path(name):
|
||||
name = name.lower()
|
||||
if len(name) < 3:
|
||||
return f"{len(name)}/{name}"
|
||||
if len(name) == 3:
|
||||
return f"3/{name[0]}/{name}"
|
||||
return f"{name[:2]}/{name[2:4]}/{name}"
|
||||
|
||||
|
||||
def is_published(name, version, registry="crates-io"):
|
||||
request = urllib.request.Request(
|
||||
INDEXES[registry] + index_path(name),
|
||||
headers={"User-Agent": "frid-release-ci", "Cache-Control": "no-cache"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
versions = [json.loads(line) for line in response.read().splitlines()]
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return False
|
||||
raise
|
||||
return any(row["vers"] == version for row in versions)
|
||||
|
||||
|
||||
def unpublished_packages(metadata, registry="crates-io"):
|
||||
members = set(metadata["workspace_members"])
|
||||
packages = []
|
||||
for package in sorted(metadata["packages"], key=lambda item: item["name"]):
|
||||
registries = package["publish"]
|
||||
if package["id"] not in members or (
|
||||
registries is not None and registry not in registries
|
||||
):
|
||||
continue
|
||||
name, version = package["name"], package["version"]
|
||||
if is_published(name, version, registry):
|
||||
print(f"Skip {name} {version}: already published", flush=True)
|
||||
else:
|
||||
print(f"Publish {name} {version}", flush=True)
|
||||
packages.append(name)
|
||||
return packages
|
||||
|
||||
|
||||
def wait_for_mirror_dependencies(metadata, selected):
|
||||
# Mirrored manifests retain their crates.io dependencies. In the parallel
|
||||
# upload job, wait for new workspace dependencies to reach crates.io before
|
||||
# Cargo resolves the mirror's packages (it does not compile them again).
|
||||
members = {p["name"]: p for p in metadata["packages"] if p["id"] in metadata["workspace_members"]}
|
||||
required = {
|
||||
(dep["name"], members[dep["name"]]["version"])
|
||||
for name in selected
|
||||
for dep in members[name]["dependencies"]
|
||||
if dep.get("path") and dep["name"] in members and dep["kind"] != "dev"
|
||||
}
|
||||
deadline = time.monotonic() + 600
|
||||
while required:
|
||||
required = {(name, version) for name, version in required if not is_published(name, version)}
|
||||
if not required:
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError(f"Workspace dependencies did not reach crates.io: {sorted(required)}")
|
||||
print(f"Waiting for crates.io dependencies before mirroring: {sorted(required)}", flush=True)
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--plan", action="store_true", help="list packages without publishing")
|
||||
parser.add_argument("--dry-run", action="store_true", help="verify packages without uploading")
|
||||
parser.add_argument("--registry", choices=INDEXES, default="crates-io")
|
||||
parser.add_argument("--no-verify", action="store_true", help="publish packages already verified by CI without rebuilding")
|
||||
args = parser.parse_args()
|
||||
token_variable = "CARGO_REGISTRY_TOKEN" if args.registry == "crates-io" else "CARGO_REGISTRIES_GITEA_TOKEN"
|
||||
if not (args.plan or args.dry_run) and not os.environ.get(token_variable):
|
||||
parser.error(f"{token_variable} must be set for publishing")
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
["cargo", "metadata", "--no-deps", "--format-version", "1", "--locked"],
|
||||
text=True,
|
||||
))
|
||||
packages = unpublished_packages(metadata, args.registry)
|
||||
if args.plan or not packages:
|
||||
return
|
||||
if args.registry == "gitea":
|
||||
wait_for_mirror_dependencies(metadata, packages)
|
||||
command = ["cargo", "publish", "--registry", args.registry, "--locked", "--all-features"]
|
||||
for name in packages:
|
||||
command.extend(["--package", name])
|
||||
if args.dry_run:
|
||||
command.append("--dry-run")
|
||||
if args.no_verify:
|
||||
command.append("--no-verify")
|
||||
# Multi-package publishing verifies against a temporary local registry,
|
||||
# then uploads and waits for dependencies to appear before their users.
|
||||
subprocess.run(command, check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
import io
|
||||
import json
|
||||
import unittest
|
||||
import urllib.error
|
||||
from contextlib import redirect_stdout
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import publish_crates
|
||||
|
||||
|
||||
class PublishCratesTests(unittest.TestCase):
|
||||
def test_publish_job_does_not_rebuild_verified_packages(self):
|
||||
with patch("sys.argv", ["publish_crates.py", "--no-verify"]):
|
||||
with patch.dict(publish_crates.os.environ, {"CARGO_REGISTRY_TOKEN": "test-only"}):
|
||||
with patch.object(publish_crates.subprocess, "check_output", return_value=json.dumps({})):
|
||||
with patch.object(publish_crates, "unpublished_packages", return_value=["music-dht", "furumi-library"]):
|
||||
with patch.object(publish_crates.subprocess, "run") as run:
|
||||
publish_crates.main()
|
||||
run.assert_called_once_with([
|
||||
"cargo", "publish", "--registry", "crates-io", "--locked", "--all-features",
|
||||
"--package", "music-dht", "--package", "furumi-library", "--no-verify",
|
||||
], check=True)
|
||||
|
||||
def test_existing_and_private_versions_are_excluded_on_retry(self):
|
||||
packages = [
|
||||
{"id": "net", "name": "federation-net", "version": "0.3.1", "publish": None},
|
||||
{"id": "dht", "name": "music-dht", "version": "0.6.0", "publish": None},
|
||||
{"id": "lib", "name": "furumi-library", "version": "0.3.0", "publish": None},
|
||||
{"id": "demo", "name": "demo", "version": "0.1.0", "publish": []},
|
||||
{"id": "internal", "name": "internal", "version": "0.1.0", "publish": ["private"]},
|
||||
{"id": "external", "name": "external", "version": "0.1.0", "publish": None},
|
||||
]
|
||||
metadata = {"packages": packages, "workspace_members": [p["id"] for p in packages[:-1]]}
|
||||
for published, expected in [
|
||||
({"federation-net"}, ["furumi-library", "music-dht"]),
|
||||
({"federation-net", "music-dht"}, ["furumi-library"]),
|
||||
]:
|
||||
with self.subTest(published=published), redirect_stdout(io.StringIO()):
|
||||
with patch.object(publish_crates, "is_published", side_effect=lambda name, *args: name in published):
|
||||
self.assertEqual(publish_crates.unpublished_packages(metadata), expected)
|
||||
|
||||
def test_mirror_waits_for_workspace_dependencies_without_building(self):
|
||||
metadata = {"workspace_members": ["lib", "dht"], "packages": [
|
||||
{"id": "lib", "name": "furumi-library", "version": "0.3.0", "dependencies": [
|
||||
{"name": "music-dht", "path": "/workspace/music-dht", "kind": None},
|
||||
]},
|
||||
{"id": "dht", "name": "music-dht", "version": "0.6.0", "dependencies": []},
|
||||
]}
|
||||
with patch.object(publish_crates, "is_published", side_effect=[False, True]) as published:
|
||||
with patch.object(publish_crates.time, "sleep") as sleep, redirect_stdout(io.StringIO()):
|
||||
publish_crates.wait_for_mirror_dependencies(metadata, ["furumi-library"])
|
||||
self.assertEqual(published.call_count, 2)
|
||||
sleep.assert_called_once_with(10)
|
||||
|
||||
def test_gitea_uses_its_own_index(self):
|
||||
response = MagicMock()
|
||||
response.__enter__.return_value.read.return_value = b'{"vers":"0.3.1"}\n'
|
||||
with patch.object(publish_crates.urllib.request, "urlopen", return_value=response) as fetch:
|
||||
self.assertTrue(publish_crates.is_published("federation-net", "0.3.1", "gitea"))
|
||||
self.assertEqual(fetch.call_args.args[0].full_url,
|
||||
"https://gt.hexor.cy/api/packages/Furumi/cargo/fe/de/federation-net")
|
||||
|
||||
def test_registry_errors_do_not_look_like_unpublished_versions(self):
|
||||
for status in (403, 429, 500):
|
||||
error = urllib.error.HTTPError("https://index.crates.io/test", status, "error", {}, None)
|
||||
with self.subTest(status=status), patch.object(publish_crates.urllib.request, "urlopen", side_effect=error):
|
||||
with self.assertRaises(urllib.error.HTTPError):
|
||||
publish_crates.is_published("music-dht", "0.6.0")
|
||||
|
||||
def test_missing_crate_and_existing_version(self):
|
||||
error = urllib.error.HTTPError("https://index.crates.io/test", 404, "missing", {}, None)
|
||||
with patch.object(publish_crates.urllib.request, "urlopen", side_effect=error):
|
||||
self.assertFalse(publish_crates.is_published("new-crate", "0.1.0"))
|
||||
response = MagicMock()
|
||||
response.__enter__.return_value.read.return_value = b'{"vers":"0.6.0","yanked":false}\n'
|
||||
with patch.object(publish_crates.urllib.request, "urlopen", return_value=response):
|
||||
self.assertTrue(publish_crates.is_published("music-dht", "0.6.0"))
|
||||
self.assertFalse(publish_crates.is_published("music-dht", "0.7.0"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user