forked from Furumi/furumi-web
Read uploaded exports without building JSON trees
An upload was buffered by an untagged enum, built into a JSON tree, serialized again and parsed into a second tree, so a 32 MiB body of tiny entries took gigabytes, and nothing limited parallel uploads. The file JSON is now kept as written (serde_json raw values) and passed to the adapter, which borrows each playlist and entry from the bytes and parses them one at a time. An upload may hold at most 200,000 entries and as many playlists, more are refused with 413, and only two uploads are read and parsed at a time. The same body now peaks below 90 MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5d8568ae96
commit
64cb868b54
4 files changed
+263
-75
No files matched your search
+1
-1
@@ -32,7 +32,7 @@ bytes = "1"
|
||||
tower = "0.5"
|
||||
base64 = "0.22"
|
||||
blake3 = "1"
|
||||
serde_json = "1"
|
||||
serde_json = { version = "1", features = ["raw_value"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
chrono = "0.4.44"
|
||||
|
||||
@@ -19,12 +19,19 @@ pub struct InputFile {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Entries (tracks and other items) and playlists one upload may hold. A
|
||||
/// 32 MiB request of real export JSON holds far fewer; the limit keeps tiny
|
||||
/// hand-made entries from turning into gigabytes of parsed tracks.
|
||||
pub const MAX_ENTRIES: usize = 200_000;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdapterError {
|
||||
/// None of the files belongs to this provider's export.
|
||||
NoSupportedFiles,
|
||||
/// A recognised file could not be parsed. The message never contains file contents.
|
||||
Invalid { file: String, reason: String },
|
||||
/// More than [`MAX_ENTRIES`] entries or playlists.
|
||||
TooManyEntries,
|
||||
}
|
||||
|
||||
impl fmt::Display for AdapterError {
|
||||
@@ -32,6 +39,10 @@ impl fmt::Display for AdapterError {
|
||||
match self {
|
||||
Self::NoSupportedFiles => f.write_str("no supported files in the upload"),
|
||||
Self::Invalid { file, reason } => write!(f, "{file}: {reason}"),
|
||||
Self::TooManyEntries => write!(
|
||||
f,
|
||||
"the export has more than {MAX_ENTRIES} entries or playlists"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,19 @@
|
||||
//! artistName, albumName, trackUri}, episode, audiobook, localTrack}}`.
|
||||
//! `YourLibrary.json`: `tracks[].{artist, album, track, uri}` → favorites.
|
||||
//! The export has no playlist ids, durations or ISRC codes.
|
||||
//!
|
||||
//! Files are read without building a JSON tree: values are borrowed from the
|
||||
//! uploaded bytes and parsed one entry at a time, and at most
|
||||
//! [`MAX_ENTRIES`] entries and playlists are taken.
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use serde::de::{IgnoredAny, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use super::{AdapterError, FileAdapter, InputFile, base_name, version_hint};
|
||||
use super::{AdapterError, FileAdapter, InputFile, MAX_ENTRIES, base_name, version_hint};
|
||||
use crate::library_import::model::{
|
||||
ImportedLibrary, ImportedPlaylist, ImportedTrack, PlaylistKind, TrackKind,
|
||||
};
|
||||
@@ -59,19 +66,21 @@ impl FileAdapter for SpotifyExport {
|
||||
provider: PROVIDER.to_owned(),
|
||||
..ImportedLibrary::default()
|
||||
};
|
||||
let mut entries = Entries::default();
|
||||
for (_, file) in playlist_files {
|
||||
let content: PlaylistFile = parse_json(file)?;
|
||||
library.playlists.extend(
|
||||
content
|
||||
for raw in entries.take_playlists(content.playlists)? {
|
||||
let raw: RawPlaylist = lenient_raw(raw);
|
||||
let items = entries.take(raw.items)?;
|
||||
library
|
||||
.playlists
|
||||
.into_iter()
|
||||
.map(|value| playlist(lenient_value(value))),
|
||||
);
|
||||
.push(playlist(raw.name, raw.description, items));
|
||||
}
|
||||
}
|
||||
let mut favorites = Vec::new();
|
||||
for file in library_files {
|
||||
let content: LibraryFile = parse_json(file)?;
|
||||
favorites.extend(content.tracks);
|
||||
favorites.extend(entries.take(content.tracks)?);
|
||||
}
|
||||
if !favorites.is_empty() {
|
||||
library.favorites = Some(ImportedPlaylist {
|
||||
@@ -82,7 +91,7 @@ impl FileAdapter for SpotifyExport {
|
||||
tracks: favorites
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(position, value)| saved_track(position, lenient_value(value)))
|
||||
.map(|(position, raw)| saved_track(position, lenient_raw(raw)))
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
@@ -90,6 +99,34 @@ impl FileAdapter for SpotifyExport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts the entries and playlists of one upload against [`MAX_ENTRIES`].
|
||||
#[derive(Default)]
|
||||
struct Entries {
|
||||
entries: usize,
|
||||
playlists: usize,
|
||||
}
|
||||
|
||||
impl Entries {
|
||||
fn take<'a>(&mut self, elements: Elements<'a>) -> Result<Vec<&'a RawValue>, AdapterError> {
|
||||
self.entries += elements.0.len();
|
||||
if self.entries > MAX_ENTRIES {
|
||||
return Err(AdapterError::TooManyEntries);
|
||||
}
|
||||
Ok(elements.0)
|
||||
}
|
||||
|
||||
fn take_playlists<'a>(
|
||||
&mut self,
|
||||
elements: Elements<'a>,
|
||||
) -> Result<Vec<&'a RawValue>, AdapterError> {
|
||||
self.playlists += elements.0.len();
|
||||
if self.playlists > MAX_ENTRIES {
|
||||
return Err(AdapterError::TooManyEntries);
|
||||
}
|
||||
Ok(elements.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn playlist_file_number(name: &str) -> Option<u32> {
|
||||
let name = base_name(name);
|
||||
let stem = name.strip_suffix(".json")?.strip_prefix("Playlist")?;
|
||||
@@ -108,60 +145,94 @@ fn is_library_file(name: &str) -> bool {
|
||||
|
||||
/// Parses a file whose top level must be a JSON object. Errors name the file
|
||||
/// and the position only: serde messages can quote the content.
|
||||
fn parse_json<T: DeserializeOwned + Default>(file: &InputFile) -> Result<T, AdapterError> {
|
||||
fn parse_json<'a, T: Deserialize<'a> + Default>(file: &'a InputFile) -> Result<T, AdapterError> {
|
||||
let invalid = |reason: String| AdapterError::Invalid {
|
||||
file: base_name(&file.name).to_owned(),
|
||||
reason,
|
||||
};
|
||||
let value: Value = serde_json::from_slice(&file.data).map_err(|error| {
|
||||
let raw: &RawValue = serde_json::from_slice(&file.data).map_err(|error| {
|
||||
invalid(format!(
|
||||
"not valid JSON (line {}, column {})",
|
||||
error.line(),
|
||||
error.column()
|
||||
))
|
||||
})?;
|
||||
if !value.is_object() {
|
||||
if !raw.get().starts_with('{') {
|
||||
return Err(invalid("not a Spotify export file".to_owned()));
|
||||
}
|
||||
Ok(lenient_value(value))
|
||||
Ok(lenient_raw(raw))
|
||||
}
|
||||
|
||||
/// Deserializes `value` as `T`, falling back to `T::default()` when the shape differs.
|
||||
fn lenient_value<T: DeserializeOwned + Default>(value: Value) -> T {
|
||||
serde_json::from_value(value).unwrap_or_default()
|
||||
/// Deserializes `raw` as `T`, falling back to `T::default()` when the shape differs.
|
||||
fn lenient_raw<'a, T: Deserialize<'a> + Default>(raw: &'a RawValue) -> T {
|
||||
serde_json::from_str(raw.get()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn lenient<'de, D, T>(deserializer: D) -> Result<T, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
T: DeserializeOwned + Default,
|
||||
T: Deserialize<'de> + Default,
|
||||
{
|
||||
Ok(lenient_value(Value::deserialize(deserializer)?))
|
||||
Ok(lenient_raw(<&'de RawValue>::deserialize(deserializer)?))
|
||||
}
|
||||
|
||||
/// The elements of a JSON array, borrowed from the file. One more than
|
||||
/// [`MAX_ENTRIES`] are kept, so the caller can tell the limit was exceeded;
|
||||
/// the rest is only checked as JSON.
|
||||
#[derive(Default)]
|
||||
struct Elements<'a>(Vec<&'a RawValue>);
|
||||
|
||||
impl<'de: 'a, 'a> Deserialize<'de> for Elements<'a> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ElementsVisitor<'a>(PhantomData<&'a ()>);
|
||||
|
||||
impl<'de: 'a, 'a> Visitor<'de> for ElementsVisitor<'a> {
|
||||
type Value = Elements<'a>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("an array")
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let mut elements = Vec::new();
|
||||
while elements.len() <= MAX_ENTRIES {
|
||||
match seq.next_element::<&'de RawValue>()? {
|
||||
Some(element) => elements.push(element),
|
||||
None => return Ok(Elements(elements)),
|
||||
}
|
||||
}
|
||||
while seq.next_element::<IgnoredAny>()?.is_some() {}
|
||||
Ok(Elements(elements))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_seq(ElementsVisitor(PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct PlaylistFile {
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
playlists: Vec<Value>,
|
||||
struct PlaylistFile<'a> {
|
||||
#[serde(borrow, deserialize_with = "lenient")]
|
||||
playlists: Elements<'a>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct LibraryFile {
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
tracks: Vec<Value>,
|
||||
struct LibraryFile<'a> {
|
||||
#[serde(borrow, deserialize_with = "lenient")]
|
||||
tracks: Elements<'a>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct RawPlaylist {
|
||||
struct RawPlaylist<'a> {
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
name: Option<String>,
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
description: Option<String>,
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
items: Vec<Value>,
|
||||
#[serde(borrow, deserialize_with = "lenient")]
|
||||
items: Elements<'a>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
@@ -238,17 +309,20 @@ fn text(value: Option<String>) -> Option<String> {
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn playlist(raw: RawPlaylist) -> ImportedPlaylist {
|
||||
fn playlist(
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
items: Vec<&RawValue>,
|
||||
) -> ImportedPlaylist {
|
||||
ImportedPlaylist {
|
||||
kind: PlaylistKind::Playlist,
|
||||
source_id: None,
|
||||
title: text(raw.name).unwrap_or_default(),
|
||||
description: text(raw.description),
|
||||
tracks: raw
|
||||
.items
|
||||
title: text(name).unwrap_or_default(),
|
||||
description: text(description),
|
||||
tracks: items
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(position, value)| playlist_item(position, lenient_value(value)))
|
||||
.map(|(position, raw)| playlist_item(position, lenient_raw(raw)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
@@ -585,6 +659,48 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_beyond_the_limit_are_refused() {
|
||||
let items = |count: usize| vec!["{}"; count].join(",");
|
||||
let at_limit = format!(
|
||||
r#"{{"playlists": [{{"items": [{}]}}, {{"items": []}}]}}"#,
|
||||
items(MAX_ENTRIES)
|
||||
);
|
||||
let library = parse(&[file("Playlist1.json", &at_limit)]);
|
||||
assert_eq!(library.playlists[0].tracks.len(), MAX_ENTRIES);
|
||||
// Over the limit in one playlist, or across playlists and favorites.
|
||||
let over = format!(
|
||||
r#"{{"playlists": [{{"items": [{}]}}]}}"#,
|
||||
items(MAX_ENTRIES + 1)
|
||||
);
|
||||
assert_eq!(
|
||||
SpotifyExport.parse(&[file("Playlist1.json", &over)]),
|
||||
Err(AdapterError::TooManyEntries)
|
||||
);
|
||||
let library_file = r#"{"tracks": [{"track": "Liked"}]}"#;
|
||||
assert_eq!(
|
||||
SpotifyExport.parse(&[
|
||||
file("Playlist1.json", &at_limit),
|
||||
file("YourLibrary.json", library_file)
|
||||
]),
|
||||
Err(AdapterError::TooManyEntries)
|
||||
);
|
||||
let playlists = format!(r#"{{"playlists": [{}]}}"#, items(MAX_ENTRIES + 1));
|
||||
assert_eq!(
|
||||
SpotifyExport.parse(&[file("Playlist1.json", &playlists)]),
|
||||
Err(AdapterError::TooManyEntries)
|
||||
);
|
||||
// What lies beyond the limit is still checked as JSON.
|
||||
let broken = format!(
|
||||
r#"{{"playlists": [{{"items": [{},]}}]}}"#,
|
||||
items(MAX_ENTRIES + 1)
|
||||
);
|
||||
assert!(matches!(
|
||||
SpotifyExport.parse(&[file("Playlist1.json", &broken)]),
|
||||
Err(AdapterError::Invalid { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_file_uris_are_decoded() {
|
||||
assert_eq!(
|
||||
|
||||
+101
-40
@@ -16,6 +16,7 @@ use cot::session::Session;
|
||||
use cot::{App, Body};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::value::RawValue;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use tokio::sync::OnceCell;
|
||||
@@ -41,6 +42,9 @@ use crate::scheduler::SchedulerHandle;
|
||||
pub const MAX_REQUEST_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_FILES: usize = 256;
|
||||
const MAX_SELECTION: usize = 10_000;
|
||||
/// Uploads read and parsed at the same time, so that concurrent requests
|
||||
/// cannot multiply the memory one upload needs.
|
||||
static UPLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2);
|
||||
|
||||
type Response = cot::Result<cot::response::Response>;
|
||||
|
||||
@@ -364,43 +368,46 @@ impl ImportRequest {
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct UploadedFile {
|
||||
name: String,
|
||||
data: FileData,
|
||||
/// File contents as a JSON string, or the file's JSON itself. It is kept
|
||||
/// as written and handed to the adapter without building a JSON tree.
|
||||
data: Box<RawValue>,
|
||||
}
|
||||
|
||||
/// File contents as text, or already parsed JSON.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum FileData {
|
||||
Text(String),
|
||||
Json(Value),
|
||||
impl UploadedFile {
|
||||
fn into_input(self) -> Result<InputFile, Rejection> {
|
||||
let data = if self.data.get().starts_with('"') {
|
||||
serde_json::from_str::<String>(self.data.get())
|
||||
.map_err(|_| Rejection::new(StatusCode::BAD_REQUEST, "invalid import request"))?
|
||||
.into_bytes()
|
||||
} else {
|
||||
Box::<str>::from(self.data).into_boxed_bytes().into_vec()
|
||||
};
|
||||
Ok(InputFile {
|
||||
name: self.name,
|
||||
data,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the uploaded export in memory; nothing of it is stored here.
|
||||
fn parse_upload(request: &ImportRequest) -> Result<ImportedLibrary, Rejection> {
|
||||
let Some(adapter) = adapters::file_adapter(&request.provider) else {
|
||||
fn parse_upload(provider: &str, files: Vec<UploadedFile>) -> Result<ImportedLibrary, Rejection> {
|
||||
let Some(adapter) = adapters::file_adapter(provider) else {
|
||||
return Err(Rejection::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"unknown import source",
|
||||
));
|
||||
};
|
||||
if request.files.len() > MAX_FILES {
|
||||
if files.len() > MAX_FILES {
|
||||
return Err(Rejection::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"too many files in the upload",
|
||||
));
|
||||
}
|
||||
let files: Vec<InputFile> = request
|
||||
.files
|
||||
.iter()
|
||||
let files = files
|
||||
.into_iter()
|
||||
.filter(|file| adapter.accepts(&file.name))
|
||||
.map(|file| InputFile {
|
||||
name: file.name.clone(),
|
||||
data: match &file.data {
|
||||
FileData::Text(text) => text.clone().into_bytes(),
|
||||
FileData::Json(value) => value.to_string().into_bytes(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
.map(UploadedFile::into_input)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
match adapter.parse(&files) {
|
||||
Ok(library) if library.entries().next().is_none() => Err(Rejection::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
@@ -414,6 +421,10 @@ fn parse_upload(request: &ImportRequest) -> Result<ImportedLibrary, Rejection> {
|
||||
Err(failure @ AdapterError::Invalid { .. }) => {
|
||||
Err(Rejection::new(StatusCode::BAD_REQUEST, failure.to_string()))
|
||||
}
|
||||
Err(failure @ AdapterError::TooManyEntries) => Err(Rejection::new(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
failure.to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -620,7 +631,10 @@ async fn session_connection(
|
||||
}
|
||||
|
||||
async fn preview(services: &Services, user_id: i64, db: &Database, request: Request) -> Response {
|
||||
let body: ImportRequest = match read_json(request).await {
|
||||
let Ok(permit) = UPLOADS.acquire().await else {
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "imports are unavailable");
|
||||
};
|
||||
let mut body: ImportRequest = match read_json(request).await {
|
||||
Ok(body) => body,
|
||||
Err(rejection) => return rejection.respond(),
|
||||
};
|
||||
@@ -630,10 +644,11 @@ async fn preview(services: &Services, user_id: i64, db: &Database, request: Requ
|
||||
"API sources are listed by /api/imports/providers/{provider}/playlists",
|
||||
);
|
||||
}
|
||||
let library = match parse_upload(&body) {
|
||||
let library = match parse_upload(&body.provider, std::mem::take(&mut body.files)) {
|
||||
Ok(library) => library,
|
||||
Err(rejection) => return rejection.respond(),
|
||||
};
|
||||
drop(permit);
|
||||
let pool = services.pool().await?;
|
||||
let history = match store::import_history(
|
||||
&mut *pool.acquire().await.map_err(db_error)?,
|
||||
@@ -671,18 +686,26 @@ async fn create(
|
||||
db: &Database,
|
||||
request: Request,
|
||||
) -> Response {
|
||||
let body: ImportRequest = match read_json(request).await {
|
||||
let Ok(permit) = UPLOADS.acquire().await else {
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "imports are unavailable");
|
||||
};
|
||||
let mut body: ImportRequest = match read_json(request).await {
|
||||
Ok(body) => body,
|
||||
Err(rejection) => return rejection.respond(),
|
||||
};
|
||||
let library = match body.source() {
|
||||
SourceType::File => match parse_upload(&body.provider, std::mem::take(&mut body.files)) {
|
||||
Ok(library) => Some(library),
|
||||
Err(rejection) => return rejection.respond(),
|
||||
},
|
||||
SourceType::Api => None,
|
||||
};
|
||||
drop(permit);
|
||||
let (config, _) = AppConfig::load_with_db(db).await;
|
||||
let mut handle = None;
|
||||
let new = match body.source() {
|
||||
SourceType::File => {
|
||||
let library = match parse_upload(&body) {
|
||||
Ok(library) => library,
|
||||
Err(rejection) => return rejection.respond(),
|
||||
};
|
||||
// Only a file import has a parsed library.
|
||||
let new = match library {
|
||||
Some(library) => {
|
||||
let playlists =
|
||||
match select_file_playlists(&library, &body.selection, &body.confirm_similar) {
|
||||
Ok(playlists) => playlists,
|
||||
@@ -697,7 +720,7 @@ async fn create(
|
||||
playlists,
|
||||
}
|
||||
}
|
||||
SourceType::Api => {
|
||||
None => {
|
||||
if body.provider != spotify_api::PROVIDER || !spotify_api::is_configured(&config) {
|
||||
return error(StatusCode::BAD_REQUEST, "this source has no API import");
|
||||
}
|
||||
@@ -1438,10 +1461,16 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(request.source(), SourceType::File);
|
||||
assert!(matches!(request.files[0].data, FileData::Text(_)));
|
||||
assert!(matches!(request.files[1].data, FileData::Json(_)));
|
||||
assert!(request.federated_search);
|
||||
assert!(request.confirm_similar.is_empty());
|
||||
// Text is decoded; JSON is passed on as written.
|
||||
let files: Vec<InputFile> = request
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|file| file.into_input().unwrap())
|
||||
.collect();
|
||||
assert_eq!(files[0].data, br#"{"playlists": []}"#);
|
||||
assert_eq!(files[1].data, br#"{"tracks":[]}"#);
|
||||
|
||||
assert_eq!(
|
||||
rejection(json_request("text/plain", b"{}".to_vec())).await,
|
||||
@@ -1490,6 +1519,14 @@ mod tests {
|
||||
assert!(require_json(&form(Some("Application/JSON; charset=utf-8"))).is_ok());
|
||||
}
|
||||
|
||||
fn raw(value: &impl Serialize) -> Box<RawValue> {
|
||||
serde_json::value::to_raw_value(value).unwrap()
|
||||
}
|
||||
|
||||
fn upload(request: ImportRequest) -> Result<ImportedLibrary, Rejection> {
|
||||
parse_upload(&request.provider, request.files)
|
||||
}
|
||||
|
||||
fn export_request(selection: &[&str]) -> ImportRequest {
|
||||
ImportRequest {
|
||||
provider: "spotify".into(),
|
||||
@@ -1497,14 +1534,14 @@ mod tests {
|
||||
files: vec![
|
||||
UploadedFile {
|
||||
name: "Spotify Account Data/Playlist1.json".into(),
|
||||
data: FileData::Json(json!({"playlists": [
|
||||
data: raw(&json!({"playlists": [
|
||||
{"name": "One", "items": [{"track": {"trackName": "A", "artistName": "X"}}]},
|
||||
{"name": "Two", "items": [{"episode": {"episodeName": "E"}}]}
|
||||
]})),
|
||||
},
|
||||
UploadedFile {
|
||||
name: "Spotify Account Data/StreamingHistory_music_0.json".into(),
|
||||
data: FileData::Text("[]".into()),
|
||||
data: raw(&"[]"),
|
||||
},
|
||||
],
|
||||
selection: selection.iter().map(|key| (*key).to_owned()).collect(),
|
||||
@@ -1515,7 +1552,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn selections_keep_source_order_and_reject_unknown_playlists() {
|
||||
let library = parse_upload(&export_request(&[])).unwrap();
|
||||
let library = upload(export_request(&[])).unwrap();
|
||||
let keys = adapters::source_keys(&library);
|
||||
let selected = select_file_playlists(
|
||||
&library,
|
||||
@@ -1547,12 +1584,36 @@ mod tests {
|
||||
fn uploads_without_export_files_are_rejected() {
|
||||
let mut request = export_request(&[]);
|
||||
request.files.remove(0);
|
||||
assert!(parse_upload(&request).is_err());
|
||||
assert!(upload(request).is_err());
|
||||
let mut request = export_request(&[]);
|
||||
request.provider = "unknown".into();
|
||||
assert!(parse_upload(&request).is_err());
|
||||
assert!(upload(request).is_err());
|
||||
let mut empty = export_request(&[]);
|
||||
empty.files[0].data = FileData::Json(json!({"playlists": []}));
|
||||
assert!(parse_upload(&empty).is_err(), "an export without playlists");
|
||||
empty.files[0].data = raw(&json!({"playlists": []}));
|
||||
assert!(upload(empty).is_err(), "an export without playlists");
|
||||
}
|
||||
|
||||
/// Tiny hand-made entries are refused before they become parsed tracks.
|
||||
#[test]
|
||||
fn uploads_with_too_many_entries_are_refused() {
|
||||
let items = format!(
|
||||
r#"{{"playlists": [{{"name": "Many", "items": [{}]}}]}}"#,
|
||||
vec!["0"; adapters::MAX_ENTRIES + 1].join(",")
|
||||
);
|
||||
let mut request = export_request(&[]);
|
||||
request.files[0].data = RawValue::from_string(items).unwrap();
|
||||
let rejection = upload(request).expect_err("refused");
|
||||
assert_eq!(rejection.status, StatusCode::PAYLOAD_TOO_LARGE);
|
||||
// The limit counts the whole upload, as text or JSON.
|
||||
let half = vec![r#"{"a":0}"#; adapters::MAX_ENTRIES / 2 + 1].join(",");
|
||||
let mut request = export_request(&[]);
|
||||
request.files[0].data = raw(&format!(r#"{{"playlists": [{{"items": [{half}]}}]}}"#));
|
||||
request.files[1] = UploadedFile {
|
||||
name: "YourLibrary.json".into(),
|
||||
data: RawValue::from_string(format!(r#"{{"tracks": [{half}]}}"#)).unwrap(),
|
||||
};
|
||||
let rejection = upload(request).expect_err("refused");
|
||||
assert_eq!(rejection.status, StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user