//! The phone's `music.capture` (`crates/cotton-ffi/src/phone/songs.rs`,//! `write_songs`), spoken to the object over HTTPS instead of written into a//! phone's own database: the same rows, decided the same way, from the same//! `cotton_core::music` rules.//!//! Per file, in album order: its bytes hashed into its song key//! (`<db>/music/<sha256>.<ext>`); the same key already a song's is `here`;//! the same song in another file (artist, title and album alike, lengths//! within two seconds) keeps the better file — this one takes the row's place//! (`better`: file, format, duration, bitrate, sample rate and path patched)//! or is not kept (`worse`); else its artist (the credit's primary artist) and//! its album (keyed on album artist and title, a field its songs bring filling//! only what the album lacks, the cover too) are found or made, and the song's//! row is made. A file that is no song's is `refused`.//!//! What the object already holds is read once, at the start (`list_records`//! of song, music_album and artist), and kept up to date as the run writes,//! so a song decided later in the run sees the ones before it. The bytes go//! up before the row that names them, skipped when the object holds the key//! already, so a run cut short is run again and resumes: what came in is//! `here` on the second run.use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};use cotton_core::media::keys::{media_limits, song_content_type, MediaKind, SONG_EXTENSIONS};use cotton_core::music::m3u;use cotton_core::music::{album_fields, album_key, better, fold, primary_artist, same_song, song_from, song_row, sort_name_of, SongFacts};use cotton_core::rules::shell_lines::LineSet;use serde_json::{json, Map, Value};usesuper::read::{embedded_cover, picture_kind};usesuper::walk::{by_album, lists_in, read, songs_in, CoverFrom, Found, SongIn};usecrate::ids;usecrate::object::{Act, ObjectClient, ObjectError};pubconst SONG_TABLE: &str = "song";pubconst ALBUM_TABLE: &str = "music_album";pubconst ARTIST_TABLE: &str = "artist";/// A named list of songs, and each song in it (the kit's groups).pubconst LIST_TABLE: &str = "record_group";pubconst MEMBER_TABLE: &str = "group_member";/// A live row as the object lists it: its columns, and its `id`.pubtypeRow = Map<String, Value>;/// The object as the import needs it. [`ObjectClient`] is the real one;/// [`Memory`] holds rows and keys in memory (a dry run, and the tests).pubtraitObject {/// The database's id, which every media key starts with.fn database_id(&self) -> Result<String, ObjectError>;/// Every live row of `table`, each with its `id`.fn rows(&self, table: &str) -> Result<Vec<Row>, ObjectError>;/// One row of `table` as the object holds it NOW, with its `id`: what a long run judges "only if empty" on just/// before it writes, never the library it read when it opened (STALE WRITES 2, 25 Nov 2026).fn row_now(&self, table: &str, id: &str) -> Result<Option<Row>, ObjectError> {Ok(self.rows(table)?.into_iter().find(|row| row.get("id").and_then(Value::as_str) == Some(id))) }fn media_held(&self, key: &str) -> Result<bool, ObjectError>;/// The file at `path`, `size` bytes, under `key`.fn put_file(&self, key: &str, path: &Path, size: u64, content_type: &str) -> Result<(), ObjectError>;fn put_bytes(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<(), ObjectError>;fn create(&self, table: &str, id: &str, data: &Row) -> Result<(), ObjectError>;fn update(&self, table: &str, id: &str, patch: &Row) -> Result<(), ObjectError>;}#[derive(Debug, thiserror::Error)]pubenumImportError { #[error(transparent)]Object(#[from] ObjectError), #[error("{0}")]Refused(String), #[error("{path}: {error}")]Io { path: PathBuf, error: std::io::Error },}fn io(path: &Path) -> implFnOnce(std::io::Error) -> ImportError + '_ {move |error| ImportError::Io { path: path.to_path_buf(), error }}/// What became of one file: as `music.capture` answers each song.#[derive(Debug, Clone, PartialEq, serde::Serialize)]#[serde(rename_all = "camelCase")]pubstructOutcome {pub source_path: String,/// `added`, `here`, `better`, `worse` or `refused`.pub outcome: &'static str, #[serde(skip_serializing_if = "Option::is_none")]pub id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")]pub key: Option<String>,/// The file a `better` one took the place of, which can go. #[serde(skip_serializing_if = "Option::is_none")]pub replaced: Option<String>,pub title: String,pub line: String,}/// What became of one playlist file found in the folder.#[derive(Debug, Clone, PartialEq, serde::Serialize)]#[serde(rename_all = "camelCase")]pubstructListOutcome {pub source_path: String,/// The list's name: its file's.pub name: String,/// The list's id, made by this run or held by that name.pub id: String,pub made: bool,/// The songs appended to it, in the file's order.pub appended: usize,/// The entries no song was found for.pub skipped: usize,}/// The whole run.#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]pubstructReport {pub songs: Vec<Outcome>,pub lists: Vec<ListOutcome>,pub albums_made: usize,pub artists_made: usize,pub covers_sent: usize,pub bytes_sent: u64,pub said: String,}implReport {pubfn count(&self, outcome: &str) -> usize {self.songs.iter().filter(|song| song.outcome == outcome).count() }}/// The extension a song key ends in, from the file's own (`key_ext` in/// songs.rs).pubfn key_ext(source_path: &str) -> Option<&'static str> {let ext = Path::new(source_path).extension()?.to_str()?.to_ascii_lowercase();let ext = match ext.as_str() {"aif" | "aifc" => "aiff","wave" => "wav","oga" => "ogg", other => other, }; SONG_EXTENSIONS.iter().copied().find(|known| *known == ext)}/// A fresh row id, a v4 UUID, as the phone's producer path mints one.fn new_id() -> String {letmut bytes: [u8; 16] = rand::random(); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;let hex = hex::encode(bytes); format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])}fn text_of(row: &Row, key: &str) -> String { row.get(key).and_then(Value::as_str).unwrap_or_default().to_string()}/// A link column's id: the id itself, or `{ id }`.fn link_of(row: &Row, key: &str) -> Option<String> {match row.get(key)? {Value::String(id) if !id.is_empty() => Some(id.clone()),Value::Object(link) => link.get("id").and_then(Value::as_str).map(str::to_string), _ => None, }}fn whole_of(row: &Row, key: &str) -> Option<u32> {let value = row.get(key)?; value.as_u64().map(|n| n as u32).or_else(|| value.as_f64().map(|n| n as u32))}fn empty(row: &Row, key: &str) -> bool { row.get(key).is_none_or(|value| value.is_null() || value.as_str() == Some(""))}fn put(data: &mutRow, key: &str, value: Option<Value>) {ifletSome(value) = value { data.insert(key.to_string(), value); }}/// What the object holds of the music kit, indexed as the phone's queries/// read it: a song by its file and by its folded title, an album by its key,/// an artist by its folded name.#[derive(Debug, Default)]structHeld { songs: Vec<Row>, by_file: HashMap<String, usize>, by_title: HashMap<String, Vec<usize>>, albums: HashMap<String, Row>, album_by_key: HashMap<String, String>, artists: HashMap<String, String>,}implHeld {fn load(object: &dynObject) -> Result<Held, ImportError> {letmut held = Held::default();for row in object.rows(ARTIST_TABLE)? { held.artists.entry(fold(&text_of(&row, "name"))).or_insert_with(|| text_of(&row, "id")); }for row in object.rows(ALBUM_TABLE)? { held.add_album(row); }for row in object.rows(SONG_TABLE)? { held.add_song(row); }Ok(held) }fn add_album(&mutself, row: Row) {let id = text_of(&row, "id");self.album_by_key.entry(album_key(&text_of(&row, "artist_name"), &text_of(&row, "title"))).or_insert_with(|| id.clone());self.albums.insert(id, row); }fn add_song(&mutself, row: Row) {let at = self.songs.len();let file = text_of(&row, "file");if !file.is_empty() {self.by_file.entry(file).or_insert(at); }self.by_title.entry(fold(&text_of(&row, "title"))).or_default().push(at);self.songs.push(row); }fn patch_song(&mutself, at: usize, patch: &Row) {let old = text_of(&self.songs[at], "file");ifself.by_file.get(&old) == Some(&at) {self.by_file.remove(&old); }for (key, value) in patch {self.songs[at].insert(key.clone(), value.clone()); }self.by_file.insert(text_of(&self.songs[at], "file"), at); }/// The title of the album a song links, read through the link.fn album_title(&self, song: &Row) -> String { link_of(song, "album").and_then(|id| self.albums.get(&id)).map(|album| text_of(album, "title")).unwrap_or_default() }}/// One run's state: the object, what it holds, and the words said.pubstructImporter<'a> { object: &'a dynObject, database_id: String, today: String, held: Held, lines: LineSet,/// Cover keys this run found held or sent, so a key is asked about once. covers: HashSet<String>, report: Report,}impl<'a> Importer<'a> {/// Read what the object holds: its id, its songs, albums and artists.pubfn open(object: &'a dynObject, today: &str) -> Result<Importer<'a>, ImportError> {let lines = LineSet::shipped("music").ok_or_else(|| ImportError::Refused("the kit ships no music lines".to_string()))?;let database_id = object.database_id()?;let held = Held::load(object)?;Ok(Importer { object, database_id, today: today.to_string(), held, lines, covers: HashSet::new(), report: Report::default() }) }fn say(&self, name: &str, fills: &[(&str, &str)]) -> Result<String, ImportError> {self.lines.say(name, fills).ok_or_else(|| ImportError::Refused(format!("the music set says no line {name}"))) }fn outcome(&self, song: &SongIn, outcome: &'static str, title: &str, line: String) -> Outcome {Outcome { source_path: song.source_path.clone(), outcome, id: None, key: None, replaced: None, title: title.to_string(), line } }/// One album's songs, in order, each answered.pubfn album(&mutself, songs: &[SongIn], each: &mutdynFnMut(&Outcome)) -> Result<(), ImportError> {for song in songs {let outcome = self.song(song)?; each(&outcome);self.report.songs.push(outcome); }Ok(()) }/// The run's answer, with what it says as a whole.pubfn finish(mutself) -> Result<Report, ImportError> {let added = self.report.count("added");self.report.said = matchself.report.songs.as_slice() { [one] => one.line.clone(), _ if added > 0 => self.say("intake.added_many", &[("count", &added.to_string())])?, songs => songs.first().map(|song| song.line.clone()).unwrap_or_default(), };Ok(self.report) }fn refused(&self, song: &SongIn, name: &str) -> Result<Outcome, ImportError> {Ok(self.outcome(song, "refused", name, self.say("intake.refused", &[("name", name)])?)) }/// The song's bytes up under `key`, unless the object holds them already.fn send_song(&mutself, key: &str, path: &Path, size: u64, content_type: &str) -> Result<(), ImportError> {if !self.object.media_held(key)? {self.object.put_file(key, path, size, content_type)?;self.report.bytes_sent += size; }Ok(()) }fn song(&mutself, song: &SongIn) -> Result<Outcome, ImportError> {let name = song.source_path.rsplit('/').next().unwrap_or(&song.source_path).to_string();letSome(ext) = key_ext(&song.source_path) else { returnself.refused(song, &name) };letSome(facts) = song_from(&song.tags, &song.source_path, ext) else { returnself.refused(song, &name) };let content_type = song_content_type(ext).ok_or_else(|| ImportError::Refused(format!("a .{ext} song carries no type")))?;// 1. THE BYTES, content-addressed: the same file twice is one object.let (sha256, size) = ids::sha256_of_file(&song.path).map_err(io(&song.path))?;if size > media_limits(MediaKind::Song).max_bytes {let line = format!("{name} is over the {} MB a song may be.", media_limits(MediaKind::Song).max_bytes / 1024 / 1024);returnOk(self.outcome(song, "refused", &name, line)); }let key = ids::song_key(&self.database_id, &sha256, ext);// 2. The same bytes are a song already: already here.ifletSome(&at) = self.held.by_file.get(&key) {let row = &self.held.songs[at];let title = text_of(row, "title");letmut outcome = self.outcome(song, "here", &title, self.say("intake.here", &[("title", &title)])?); outcome.id = Some(text_of(row, "id")); outcome.key = Some(key);returnOk(outcome); }// 3. The same song in another file: the better one is kept.let album_title = facts.album_title.clone().unwrap_or_default();let artist_name = facts.artist_name.clone().unwrap_or_default();let twin = self.held.by_title.get(&fold(&facts.title)).into_iter().flatten().copied().find(|&at| {let row = &self.held.songs[at];let held = (text_of(row, "artist_name"), text_of(row, "title"), self.held.album_title(row), row.get("duration").and_then(Value::as_f64)); same_song((&artist_name, &facts.title, &album_title, facts.duration), (&held.0, &held.1, &held.2, held.3)) });ifletSome(at) = twin {let row = self.held.songs[at].clone();let id = text_of(&row, "id");let held_format = text_of(&row, "format");if !better(&facts.format, facts.bitrate, &held_format, whole_of(&row, "bitrate")) {letmut outcome = self.outcome(song, "worse", &facts.title, self.say("intake.worse", &[("title", &facts.title)])?); outcome.id = Some(id);returnOk(outcome); }self.send_song(&key, &song.path, size, content_type)?;letmut patch = Row::new(); patch.insert("file".into(), Value::from(key.clone())); patch.insert("format".into(), Value::from(facts.format.clone())); put(&mut patch, "duration", facts.duration.map(Value::from)); put(&mut patch, "bitrate", facts.bitrate.map(Value::from)); put(&mut patch, "sample_rate", facts.sample_rate.map(Value::from)); patch.insert("path".into(), Value::from(facts.path.clone()));self.object.update(SONG_TABLE, &id, &patch)?;self.held.patch_song(at, &patch);let format = held_format.to_uppercase();let line = self.say("intake.better", &[("title", &facts.title), ("format", &format)])?;letmut outcome = self.outcome(song, "better", &facts.title, line); outcome.id = Some(id); outcome.key = Some(key); outcome.replaced = Some(text_of(&row, "file"));returnOk(outcome); }// 4. Its bytes, its artist and album, found or made, then the song.self.send_song(&key, &song.path, size, content_type)?;let artist = match facts.artist_name.as_deref() {Some(credit) => {// The sort tag is the credit's: it names this artist only when the credit is them alone.let primary = primary_artist(credit);let sort = song.tags.artist_sort.as_deref().filter(|_| fold(primary) == fold(credit));Some(self.artist_of(primary, song.tags.mb_artist.as_deref(), sort)?) }None => None, };let album = match facts.album_title.as_deref() {Some(title) => Some(self.album_of(&facts, title, song)?),None => None, };let id = new_id();letmut row = song_row(&facts, &key, artist, album, &self.today);self.object.create(SONG_TABLE, &id, &row)?; row.insert("id".into(), Value::from(id.clone()));self.held.add_song(row);letmut outcome = self.outcome(song, "added", &facts.title, self.say("intake.added", &[("title", &facts.title)])?); outcome.id = Some(id); outcome.key = Some(key);Ok(outcome) }/// A playlist file found in the folder, as a list of songs/// (`cotton_core::music::m3u`): named after its file, each entry found by/// its path relative to the list then by its file name among this run's/// songs and those held, the rest skipped and counted. A list held by/// that name only grows: the songs it lacks are appended in the file's/// order. Run after the songs, so this run's are found.pubfn list(&mutself, found: &Found) -> Result<ListOutcome, ImportError> {let bytes = std::fs::read(&found.path).map_err(io(&found.path))?;let entries = m3u::entries(&m3u::text_of(&bytes));let name = m3u::list_name(&found.source_path);// This run's files first: a file whose bytes were a song already is// that song, wherever the held row says it came in.letmut songs: Vec<(String, String)> = self.report.songs.iter().filter_map(|song| Some((song.source_path.clone(), song.id.clone()?))).collect(); songs.extend(self.held.songs.iter().map(|row| (text_of(row, "path"), text_of(row, "id"))).filter(|(path, id)| !path.is_empty() && !id.is_empty()));let resolved = m3u::resolve(&found.source_path, &entries, &songs);let held = self.object.rows(LIST_TABLE)?.into_iter().find(|row| text_of(row, "table_id") == SONG_TABLE && fold(&text_of(row, "name")) == fold(&name));let (id, made, members) = match held {Some(row) => {let id = text_of(&row, "id");letmut members: Vec<(f64, String)> = self .object .rows(MEMBER_TABLE)? .into_iter() .filter(|member| link_of(member, "group").as_deref() == Some(id.as_str())) .map(|member| (member.get("place").and_then(Value::as_f64).unwrap_or(0.0), text_of(&member, "record_id"))) .collect(); members.sort_by(|a, b| a.0.total_cmp(&b.0)); (id, false, members) }None => {let id = new_id();letmut data = Row::new(); data.insert("table_id".into(), Value::from(SONG_TABLE)); data.insert("name".into(), Value::from(name.clone()));self.object.create(LIST_TABLE, &id, &data)?; (id, true, Vec::new()) } };let held_ids: Vec<String> = members.iter().map(|(_, id)| id.clone()).collect();letmut place = members.last().map_or(0.0, |(place, _)| *place);let appended = m3u::to_append(&held_ids, &resolved.songs);for song in &appended { place += 1.0;letmut data = Row::new(); data.insert("group".into(), Value::from(id.clone())); data.insert("record_id".into(), Value::from(song.clone())); data.insert("place".into(), Value::from(place));self.object.create(MEMBER_TABLE, &new_id(), &data)?; }let outcome = ListOutcome { source_path: found.source_path.clone(), name, id, made, appended: appended.len(), skipped: resolved.skipped };self.report.lists.push(outcome.clone());Ok(outcome) }/// The artist named `name`, found by its folded name or made.fn artist_of(&mutself, name: &str, mb_artist: Option<&str>, sort: Option<&str>) -> Result<String, ImportError> {let folded = fold(name);ifletSome(id) = self.held.artists.get(&folded) {returnOk(id.clone()); }letmut data = Row::new(); data.insert("name".into(), Value::from(name.trim())); data.insert("sort_name".into(), Value::from(sort_name_of(name, sort))); put(&mut data, "mb_artist", mb_artist.map(Value::from));let id = new_id();self.object.create(ARTIST_TABLE, &id, &data)?;self.report.artists_made += 1;self.held.artists.insert(folded, id.clone());Ok(id) }/// The cover's key in the object, sent when it is not held; `None` when/// the song brings no picture an album's cover may be.fn cover(&mutself, song: &SongIn) -> Result<Option<String>, ImportError> {let bytes = match &song.cover {Some(CoverFrom::Embedded(path)) => embedded_cover(path),Some(CoverFrom::Folder(path)) => Some(std::fs::read(path).map_err(io(path))?),None => None, };letSome(bytes) = bytes else { returnOk(None) };letSome((ext, content_type)) = picture_kind(&bytes) else { returnOk(None) };let key = ids::photo_key(&self.database_id, &ids::sha256_hex(&bytes), ext);if !self.covers.contains(&key) {if !self.object.media_held(&key)? {self.object.put_bytes(&key, bytes, content_type)?;self.report.covers_sent += 1; }self.covers.insert(key.clone()); }Ok(Some(key)) }/// The album keyed on its album artist and title, found or made; a cover/// or a field its songs bring fills only what it lacks.fn album_of(&mutself, facts: &SongFacts, title: &str, song: &SongIn) -> Result<String, ImportError> {let album_artist = facts.album_artist.clone().or(facts.artist_name.clone()).unwrap_or_default();let keyed = album_key(&album_artist, title);let tags = &song.tags;ifletSome(id) = self.held.album_by_key.get(&keyed).cloned() {letmut row = self.held.albums.get(&id).cloned().unwrap_or_default();let wants = |row: &Row| empty(row, "cover") || album_fields(facts, tags).iter().any(|(key, _)| empty(row, key));// What the library read at the start says is empty is judged again on the album as it is now: a cover or// a field the owner set during a long import stays his (STALE WRITES 2, 25 Nov 2026).if wants(&row) {ifletSome(now) = self.object.row_now(ALBUM_TABLE, &id)? { row = now;self.held.albums.insert(id.clone(), row.clone()); } }letmut patch = Row::new();if empty(&row, "cover") { put(&mut patch, "cover", self.cover(song)?.map(Value::from)); }for (key, value) in album_fields(facts, tags) {if empty(&row, key) { patch.insert(key.into(), value); } }if !patch.is_empty() {self.object.update(ALBUM_TABLE, &id, &patch)?;ifletSome(held) = self.held.albums.get_mut(&id) { held.extend(patch); } }returnOk(id); }let artist = if album_artist.is_empty() { None } else { Some(self.artist_of(&album_artist, tags.mb_album_artist.as_deref(), tags.album_artist_sort.as_deref())?) };letmut data = Row::new(); data.insert("title".into(), Value::from(title.trim())); put(&mut data, "artist", artist.map(Value::from));if !album_artist.is_empty() { data.insert("artist_name".into(), Value::from(album_artist.clone())); } put(&mut data, "cover", self.cover(song)?.map(Value::from)); put(&mut data, "compilation", tags.compilation.filter(|on| *on).map(Value::from)); data.extend(album_fields(facts, tags).into_iter().map(|(key, value)| (key.to_string(), value))); data.insert("added_on".into(), Value::from(self.today.clone()));let id = new_id();self.object.create(ALBUM_TABLE, &id, &data)?;self.report.albums_made += 1; data.insert("id".into(), Value::from(id.clone()));self.held.add_album(data);Ok(id) }}/// A folder's songs read, gathered by album, and its playlist files, ready/// to bring in.pubfn read_folder(folder: &Path) -> Result<(Vec<Vec<SongIn>>, Vec<Found>), ImportError> {if !folder.is_dir() {returnErr(ImportError::Refused(format!("{} is not a folder", folder.display()))); }let found = songs_in(folder).map_err(io(folder))?;let lists = lists_in(folder).map_err(io(folder))?;if found.is_empty() && lists.is_empty() {let line = LineSet::shipped("music").and_then(|lines| lines.say("intake.folder_empty", &[])).unwrap_or_else(|| "That folder holds no songs.".to_string());returnErr(ImportError::Refused(line)); }Ok((by_album(found.iter().map(read).collect()), lists))}/// The whole verb: `folder`'s songs into `object`, album by album, `each`/// told of every file as it is answered; then its playlist files as lists.pubfn import_folder(object: &dynObject, folder: &Path, today: &str, each: &mutdynFnMut(&Outcome)) -> Result<Report, ImportError> {letmut importer = Importer::open(object, today)?;let (albums, lists) = read_folder(folder)?;for album in albums { importer.album(&album, each)?; }for list in &lists { importer.list(list)?; } importer.finish()}// ── the object over HTTPS ───────────────────────────────────────────────────/// The most records one `list_records` page answers.const PAGE: u64 = 5000;implObjectforObjectClient {fn database_id(&self) -> Result<String, ObjectError> {ObjectClient::database_id(self) }fn rows(&self, table: &str) -> Result<Vec<Row>, ObjectError> {letmut rows = Vec::new();// A device reads its own rows and opens the sealed ones (an artist's name) here.ifletSome(held) = self.device_rows(table) {for record in held? {letmut row = record.get("data").and_then(Value::as_object).cloned().unwrap_or_default(); row.insert("id".into(), record["id"].clone()); rows.push(row); }returnOk(rows); }letmut page = 0u64;loop {let answer = self.tool("list_records", &json!({ "table": table, "page": page, "limit": PAGE }))?;for record in answer.get("records").and_then(Value::as_array).into_iter().flatten() {letmut row = record.get("data").and_then(Value::as_object).cloned().unwrap_or_default();ifletSome(id) = record.get("id") { row.insert("id".into(), id.clone()); } rows.push(row); }match answer.get("next_page").and_then(Value::as_u64) {Some(next) if next > page => page = next, _ => returnOk(rows), } } }fn row_now(&self, table: &str, id: &str) -> Result<Option<Row>, ObjectError> {matchObjectClient::row_now(self, table, id) {Some(now) => Ok(now?.map(|mut row| { row.insert("id".into(), Value::from(id)); row })),None => Ok(self.rows(table)?.into_iter().find(|row| row.get("id").and_then(Value::as_str) == Some(id))), } }fn media_held(&self, key: &str) -> Result<bool, ObjectError> {// A person's file held in the clear is not held: it goes up again, sealed.ifcrate::object::is_person_key(key) {returnOk(self.media_type(key)?.is_some_and(|held| crate::object::is_sealed_type(&held))); }ObjectClient::media_held(self, key) }fn put_file(&self, key: &str, path: &Path, size: u64, content_type: &str) -> Result<(), ObjectError> {self.put_person_file(key, path, size, content_type).map(|_| ()) }fn put_bytes(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<(), ObjectError> {self.put_person_bytes(key, bytes, content_type).map(|_| ()) }fn create(&self, table: &str, id: &str, data: &Row) -> Result<(), ObjectError> {self.act(Act::Create, table, id, &Value::Object(data.clone())).map(|_| ()) }fn update(&self, table: &str, id: &str, patch: &Row) -> Result<(), ObjectError> {self.act(Act::Update, table, id, &Value::Object(patch.clone())).map(|_| ()) }}// ── the object in memory ────────────────────────────────────────────────────/// An object held in memory: rows by table, media keys, and every write in/// order. A dry run brings a folder into an empty one; the tests seed it.#[derive(Debug, Default)]pubstructMemory {pub database_id: String,pub rows: std::cell::RefCell<HashMap<String, Vec<Row>>>,pub media: std::cell::RefCell<HashMap<String, (u64, String)>>,/// `create song <id>`, `update music_album <id>`, `put <key>`, in order.pub writes: std::cell::RefCell<Vec<String>>,}implMemory {pubfn new(database_id: &str) -> Memory {Memory { database_id: database_id.to_string(), ..Memory::default() } }/// A row the object holds before the run.pubfn seed(&self, table: &str, row: Value) {let row = row.as_object().cloned().expect("a row is an object");self.rows.borrow_mut().entry(table.to_string()).or_default().push(row); }pubfn table(&self, table: &str) -> Vec<Row> {self.rows.borrow().get(table).cloned().unwrap_or_default() }}implObjectforMemory {fn database_id(&self) -> Result<String, ObjectError> {Ok(self.database_id.clone()) }fn rows(&self, table: &str) -> Result<Vec<Row>, ObjectError> {Ok(self.table(table)) }fn media_held(&self, key: &str) -> Result<bool, ObjectError> {Ok(self.media.borrow().contains_key(key)) }fn put_file(&self, key: &str, _path: &Path, size: u64, content_type: &str) -> Result<(), ObjectError> {self.media.borrow_mut().insert(key.to_string(), (size, content_type.to_string()));self.writes.borrow_mut().push(format!("put {key}"));Ok(()) }fn put_bytes(&self, key: &str, bytes: Vec<u8>, content_type: &str) -> Result<(), ObjectError> {self.media.borrow_mut().insert(key.to_string(), (bytes.len() as u64, content_type.to_string()));self.writes.borrow_mut().push(format!("put {key}"));Ok(()) }fn create(&self, table: &str, id: &str, data: &Row) -> Result<(), ObjectError> {letmut row = data.clone(); row.insert("id".into(), Value::from(id));self.rows.borrow_mut().entry(table.to_string()).or_default().push(row);self.writes.borrow_mut().push(format!("create {table} {id}"));Ok(()) }fn update(&self, table: &str, id: &str, patch: &Row) -> Result<(), ObjectError> {letmut rows = self.rows.borrow_mut();let row = rows .get_mut(table) .and_then(|rows| rows.iter_mut().find(|row| row.get("id").and_then(Value::as_str) == Some(id))) .ok_or_else(|| ObjectError::Refused { status: 404, code: "no_such_record".into(), message: format!("no {table} {id}") })?; row.extend(patch.clone());self.writes.borrow_mut().push(format!("update {table} {id}"));Ok(()) }}#[cfg(test)]mod tests {usesuper::*; #[test]fn a_key_ends_in_the_extension_its_song_kind_names() { assert_eq!(key_ext("A/B/01 x.AIF"), Some("aiff")); assert_eq!(key_ext("x.oga"), Some("ogg")); assert_eq!(key_ext("x.flac"), Some("flac")); assert_eq!(key_ext("x.txt"), None); } #[test]fn a_row_id_is_a_v4_uuid() {let id = new_id(); assert_eq!(id.len(), 36); assert_eq!(&id[14..15], "4"); assert_ne!(id, new_id()); }}