lib: library lists say what each cover is cached under

PdfListItem, ComicTreeItem (with ComicShelf::cover for a series' card) and
music's LibraryEntry carry a cover_key: the hashes of the blobs the cover is
drawn from, set only while they are stored here. A frontend that caches covers
by it gets a new key when a cover changes or arrives through sync, rather than
the old picture. LibraryEntry::has_cover becomes cover_key, and an artist's key
is its portrait's or its mosaic's covers'.

Comics read every first page's key in bulk alongside the availability roll-up,
choosing the first page the way list_comic_pages does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WsxkM2ja42H2h5BPRexf2r
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-10-04 04:44:34 -07:00
1 parent f8fad97f81
commit 2e394cadc0
6 files changed
+205 -62

No files matched your search

+1 -1
View File
@@ -481,7 +481,7 @@ impl MusicView {
let targets: Vec<(DocumentID, LibraryEntryKind)> = self
.library_rows
.iter()
.filter(|e| e.has_cover && !self.covers.contains_key(&e.id))
.filter(|e| e.cover_key.is_some() && !self.covers.contains_key(&e.id))
.map(|e| (e.id.clone(), e.kind))
.collect();
+23
View File
@@ -81,6 +81,29 @@ pub(crate) fn primary_blob_ref(
artifact_store.batch(|tx| artifact_store.get_blob_ref(tx, doc_id, ArtifactKind::PrimaryContent))
}
/// What a frontend caches a library card's cover under, when the cover is
/// drawn from the blobs `refs` point at: their hashes, joined. A cover that
/// changes through sync points at a different blob, so it arrives with a new
/// key rather than hitting the old picture's cache entry.
///
/// `None` unless every one of those blobs is stored here. The cover loaders
/// read local bytes only, so until then a card draws its placeholder; the
/// reload that follows the bytes arriving finds a key, and that is what makes
/// the card ask again.
pub(crate) fn cover_key<'a>(
blob_store: &BlobStore,
refs: impl IntoIterator<Item = &'a BlobRef>,
) -> Option<String> {
let mut hashes = Vec::new();
for blob_ref in refs {
if !blob_store.exists(&blob_ref.blob_hash) {
return None;
}
hashes.push(blob_ref.blob_hash.to_string());
}
(!hashes.is_empty()).then(|| hashes.join("+"))
}
/// Read the blob `blob_ref` points at from this node's blob store.
pub(crate) fn load_blob(
blob_store: &BlobStore,
+129 -31
View File
@@ -38,7 +38,9 @@ use zip::ZipArchive;
use chrono::{Duration, Utc};
use crate::agents::RECENT_WINDOW_DAYS;
use crate::agents::blob_document::{import_blob_document, load_blob_if_local, primary_blob_ref};
use crate::agents::blob_document::{
cover_key, import_blob_document, load_blob_if_local, primary_blob_ref,
};
use crate::agents::library_tree::library_tree;
use crate::agents::pictures::write_image_properties;
use crate::agents::reading::reading_page;
@@ -49,7 +51,7 @@ use crate::documents::import::{
};
use crate::documents::{
Artifact, ArtifactKind, ArtifactValue, BlobRef, Document, DocumentAvailability, DocumentID,
DocumentType, LatestReadChild, PropertyKind, PropertyValue, Timestamp,
DocumentType, LatestReadChild, Property, PropertyKind, PropertyValue, Timestamp,
document_availability_bulk,
};
use crate::jobs::ProgressReporter;
@@ -895,6 +897,19 @@ pub struct ComicTreeItem {
/// For a `Collection`: the child opened most recently beneath it, if one
/// is recorded (see [`latest_read_child`]). Always `None` for a `Comic`.
pub latest_read_child: Option<DocumentID>,
/// For a `Comic`: what its cover — the first page — is cached under, or
/// `None` while that page's bytes are on another node (see
/// [`cover_key`]). Always `None` for a `Collection`, which borrows a
/// comic's: ask [`ComicShelf::cover`].
pub cover_key: Option<String>,
}
/// A library card's cover: the comic whose first page it is, and the key it
/// is cached under.
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
pub struct ComicCover {
pub comic: DocumentID,
pub key: String,
}
/// Build the full comics hierarchy — every `Comic` document and the
@@ -915,7 +930,9 @@ pub fn build_comic_tree_nodes(store: &Store) -> Result<Vec<ComicTreeItem>, Docum
(n.id.clone(), expected.unwrap_or(0))
})
.collect();
let rolled_up = comic_availabilities(store, &comics);
let pages = pages_by_comic(store, comics.iter().map(|(id, _)| id).collect());
let rolled_up = comic_availabilities(store, &comics, &pages);
let mut cover_keys = comic_cover_keys(store, &pages);
Ok(nodes
.into_iter()
.map(|n| ComicTreeItem {
@@ -930,6 +947,7 @@ pub fn build_comic_tree_nodes(store: &Store) -> Result<Vec<ComicTreeItem>, Docum
.is_collection
.then(|| latest_read_child(&store.artifact_store, &n.id))
.flatten(),
cover_key: cover_keys.remove(&n.id),
id: n.id,
title: n.title,
parent_id: n.parent_id,
@@ -1106,6 +1124,14 @@ impl ComicShelf {
}
}
/// `id`'s cover as something to load and cache — [`Self::cover_comic`]
/// with that comic's [`ComicTreeItem::cover_key`]. `None` while the
/// first page's bytes are on another node.
pub fn cover(&self, id: DocumentID) -> Option<ComicCover> {
let comic = self.node(&self.cover_comic(id)?)?;
Some(ComicCover { comic: comic.id.clone(), key: comic.cover_key.clone()? })
}
/// `id`'s top-level ancestor — the series root, or `id` itself for a
/// standalone comic. Reading direction lives there, so a whole series
/// shares one setting however many volumes sit between root and chapter.
@@ -1156,6 +1182,83 @@ pub fn save_reading_direction(
})
}
/// The page documents of every comic in `wanted`, in no particular order, from
/// one read of the library's `Image` documents. A failed read leaves every
/// comic out, which callers read as unavailable and coverless.
fn pages_by_comic(
store: &Store,
wanted: HashSet<&DocumentID>,
) -> HashMap<DocumentID, Vec<Document>> {
let doc_store = &store.doc_store;
let pages = doc_store.batch(|tx| doc_store.list_documents_by_type(tx, &DocumentType::Image));
let mut by_comic: HashMap<DocumentID, Vec<Document>> = HashMap::new();
for page in pages.unwrap_or_else(|e| {
log::warn!("comics: could not list page documents: {e}");
Vec::new()
}) {
if let Some(comic) = page.parent_id.clone().filter(|parent| wanted.contains(parent)) {
by_comic.entry(comic).or_default().push(page);
}
}
by_comic
}
/// Each comic's [`ComicTreeItem::cover_key`]: that of its first page's blob.
/// "First" is [`list_comic_pages`]' first — lowest `Order`, then oldest — but
/// chosen over properties and blob refs read for the whole library at once.
fn comic_cover_keys(
store: &Store,
pages_by_comic: &HashMap<DocumentID, Vec<Document>>,
) -> HashMap<DocumentID, String> {
let all_pages: Vec<DocumentID> =
pages_by_comic.values().flatten().map(|page| page.id.clone()).collect();
let doc_store = &store.doc_store;
let props = doc_store
.batch(|tx| doc_store.list_properties_for_documents(tx, &all_pages))
.unwrap_or_else(|e| {
log::warn!("comics: could not read page properties for covers: {e}");
HashMap::new()
});
// First page -> its comic.
let first_pages: HashMap<DocumentID, &DocumentID> = pages_by_comic
.iter()
.filter_map(|(comic, pages)| {
let first =
pages.iter().min_by_key(|p| (page_order(props.get(&p.id)), p.created_at))?;
Some((first.id.clone(), comic))
})
.collect();
let first_ids: Vec<DocumentID> = first_pages.keys().cloned().collect();
let artifact_store = &store.artifact_store;
let refs = artifact_store
.batch(|tx| artifact_store.list_blob_refs_for_documents(tx, &first_ids))
.unwrap_or_else(|e| {
log::warn!("comics: could not read cover blob refs: {e}");
HashMap::new()
});
refs.into_iter()
.filter_map(|(page, refs)| {
let content = refs
.iter()
.find_map(|(kind, r)| (*kind == ArtifactKind::PrimaryContent).then_some(r));
Some(((*first_pages.get(&page)?).clone(), cover_key(&store.blob_store, content)?))
})
.collect()
}
/// A page's place in its comic: its `Order`, or after every ordered page for
/// one without.
fn page_order(props: Option<&Vec<Property>>) -> u32 {
props
.into_iter()
.flatten()
.find_map(|p| match (&p.kind, &p.value) {
(PropertyKind::Order, PropertyValue::U32(n)) => Some(*n),
_ => None,
})
.unwrap_or(u32::MAX)
}
/// Roll a whole comic's page set up into one [`DocumentAvailability`]: the
/// worst of its pages' own availabilities, floored at
/// [`Remote`](DocumentAvailability::Remote) whenever the number of synced page
@@ -1169,26 +1272,15 @@ pub fn save_reading_direction(
/// blob, and any artifacts such as a caption, all fetched).
///
/// For every comic in `comics` at once — each paired with the page count it
/// expects — so a library costs one read of the page documents and one bulk
/// availability check, not three queries per comic. A failed read leaves the
/// comics it covers out of the answer, which callers read as unavailable.
/// expects — from [`pages_by_comic`]'s one read of the page documents and one
/// bulk availability check, not three queries per comic.
fn comic_availabilities(
store: &Store,
comics: &[(DocumentID, u32)],
pages_by_comic: &HashMap<DocumentID, Vec<Document>>,
) -> HashMap<DocumentID, DocumentAvailability> {
let wanted: HashSet<&DocumentID> = comics.iter().map(|(id, _)| id).collect();
let doc_store = &store.doc_store;
let pages = doc_store.batch(|tx| doc_store.list_documents_by_type(tx, &DocumentType::Image));
let mut pages_by_comic: HashMap<DocumentID, Vec<DocumentID>> = HashMap::new();
for page in pages.unwrap_or_else(|e| {
log::warn!("comics: could not list page documents: {e}");
Vec::new()
}) {
if let Some(comic) = page.parent_id.filter(|parent| wanted.contains(parent)) {
pages_by_comic.entry(comic).or_default().push(page.id);
}
}
let all_pages: Vec<DocumentID> = pages_by_comic.values().flatten().cloned().collect();
let all_pages: Vec<DocumentID> =
pages_by_comic.values().flatten().map(|page| page.id.clone()).collect();
let artifact_store = &store.artifact_store;
let page_availability = artifact_store
.batch(|tx| {
@@ -1209,8 +1301,11 @@ fn comic_availabilities(
let pages_outstanding = pages.is_empty() || pages.len() as u32 != *expected;
let availability = pages
.iter()
.map(|id| {
page_availability.get(id).copied().unwrap_or(DocumentAvailability::Unavailable)
.map(|page| {
page_availability
.get(&page.id)
.copied()
.unwrap_or(DocumentAvailability::Unavailable)
})
.chain(pages_outstanding.then_some(DocumentAvailability::Remote))
.max()
@@ -1254,15 +1349,7 @@ pub fn list_comic_pages(
let mut pages: Vec<(DocumentID, u32)> = page_ids
.into_iter()
.map(|id| {
let order = props_by_doc
.get(&id)
.into_iter()
.flatten()
.find_map(|p| match (&p.kind, &p.value) {
(PropertyKind::Order, PropertyValue::U32(n)) => Some(*n),
_ => None,
})
.unwrap_or(u32::MAX);
let order = page_order(props_by_doc.get(&id));
(id, order)
})
.collect();
@@ -1831,10 +1918,17 @@ mod tests {
}
assert_eq!(page_count(&store.doc_store, comic_id).unwrap(), 3);
let pages_of = pages_by_comic(store, HashSet::from([comic_id]));
assert_eq!(
comic_availabilities(store, &[(comic_id.clone(), 3)])[comic_id],
comic_availabilities(store, &[(comic_id.clone(), 3)], &pages_of)[comic_id],
DocumentAvailability::Local
);
// The cover is cached under the first page's blob.
let first = get_blob_ref(&store.artifact_store, &pages[0], ArtifactKind::PrimaryContent);
assert_eq!(
comic_cover_keys(store, &pages_of)[comic_id],
first.unwrap().blob_hash.to_string()
);
assert_eq!(
load_comic_cover_bytes(
&store.blob_store,
@@ -2203,6 +2297,7 @@ mod tests {
created_at: Timestamp(Utc::now()),
reading_direction: None,
latest_read_child: None,
cover_key: None,
}
}
@@ -2296,6 +2391,9 @@ mod tests {
assert_eq!(chapter_2_node.order, Some(2));
// Nothing in the ensemble is known to hold the page we just deleted.
assert_eq!(chapter_2_node.availability, DocumentAvailability::Unavailable);
// Its cover is that missing page, so there's nothing to draw; Chapter 1's is here.
assert_eq!(chapter_2_node.cover_key, None);
assert!(chapter_1.cover_key.is_some());
// Record a peer holding it and the same chapter becomes streamable.
store
+26 -25
View File
@@ -29,7 +29,7 @@ use uuid::Uuid;
use crate::agents::audio_player::{AudioError, AudioPlayer};
#[cfg(feature = "multimedia")]
use crate::agents::blob_document::primary_blob_ref;
use crate::agents::blob_document::{import_blob_document, load_blob};
use crate::agents::blob_document::{cover_key, import_blob_document, load_blob};
use crate::agents::ensure_document;
use crate::agents::library_tree::{LibraryTreeItem, library_tree, sort_for_display};
#[cfg(feature = "multimedia")]
@@ -1146,9 +1146,12 @@ pub struct LibraryEntry {
/// [`Local`](DocumentAvailability::Local) for the container levels, which
/// have nothing to download.
pub availability: DocumentAvailability,
/// Set on albums that carry cover art, so a UI knows there is a thumbnail
/// worth fetching without querying per row.
pub has_cover: bool,
/// What this row's art is cached under, so a UI knows there is a thumbnail
/// worth fetching without querying per row: an album's cover, or an
/// artist's portrait or mosaic (see [`artist_art`]). `None` for a track,
/// for a row with no art, and while the art's bytes are on another node —
/// see [`cover_key`].
pub cover_key: Option<String>,
}
/// Which level of the derived library to list.
@@ -1195,20 +1198,13 @@ pub fn library_entries(store: &Store, level: &LibraryLevel) -> Result<Vec<Librar
kind: LibraryEntryKind::Artist,
availability: DocumentAvailability::Local,
// An artist's art is derived (a portrait tag, or a mosaic of
// its albums' covers), so "has art" is only knowable by
// resolving it — see `artist_art`. `albums > 0` is the cheap
// gate: an artist with no albums can have no mosaic.
has_cover: albums > 0
|| store
.artifact_store
.batch(|tx| {
store.artifact_store.get_blob_ref(
tx,
&artist.id,
ArtifactKind::Thumbnail,
)
})?
.is_some(),
// its albums' covers), so its key is only knowable by
// resolving it — which costs a read of its albums.
cover_key: match artist_art(store, &artist.id, MOSAIC_TILES)? {
ArtistArt::Portrait(portrait) => cover_key(&store.blob_store, [&portrait]),
ArtistArt::Covers(covers) => cover_key(&store.blob_store, &covers),
ArtistArt::None => None,
},
id: artist.id,
});
}
@@ -1244,7 +1240,7 @@ pub fn library_entries(store: &Store, level: &LibraryLevel) -> Result<Vec<Librar
subtitle,
kind: LibraryEntryKind::Album,
availability: DocumentAvailability::Local,
has_cover: store
cover_key: store
.artifact_store
.batch(|tx| {
store.artifact_store.get_blob_ref(
@@ -1253,7 +1249,7 @@ pub fn library_entries(store: &Store, level: &LibraryLevel) -> Result<Vec<Librar
ArtifactKind::Thumbnail,
)
})?
.is_some(),
.and_then(|cover| cover_key(&store.blob_store, [&cover])),
id: edge.to_id,
},
));
@@ -1308,7 +1304,7 @@ pub fn library_entries(store: &Store, level: &LibraryLevel) -> Result<Vec<Librar
subtitle: secs.map(format_duration).unwrap_or_default(),
kind: LibraryEntryKind::Track,
availability,
has_cover: false,
cover_key: None,
id: edge.to_id,
},
));
@@ -1366,7 +1362,9 @@ pub fn artist_art(store: &Store, artist_id: &DocumentID, max_covers: usize) -> R
let albums = library_entries(store, &LibraryLevel::Albums { artist_id: artist_id.clone() })?;
let mut covers = Vec::new();
store.artifact_store.batch(|tx| {
for album in albums.iter().filter(|a| a.has_cover) {
// Only covers stored here: a tile whose bytes are elsewhere can't be
// drawn, and the next album along can.
for album in albums.iter().filter(|a| a.cover_key.is_some()) {
if covers.len() == max_covers {
break;
}
@@ -2759,9 +2757,12 @@ mod tests {
import_track(store, "art", &tag);
build_library(store, test_node(), None).unwrap();
let artist = library_entries(store, &LibraryLevel::Artists).unwrap()[0].id.clone();
let albums = library_entries(store, &LibraryLevel::Albums { artist_id: artist }).unwrap();
assert!(albums[0].has_cover, "so a UI knows there is a thumbnail worth fetching");
let artist = library_entries(store, &LibraryLevel::Artists).unwrap().remove(0);
let albums =
library_entries(store, &LibraryLevel::Albums { artist_id: artist.id }).unwrap();
assert!(albums[0].cover_key.is_some(), "so a UI knows there is a thumbnail worth fetching");
// One album's mosaic is that album's cover, so it caches under the same key.
assert_eq!(artist.cover_key, albums[0].cover_key);
}
#[rstest]
+25 -4
View File
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::path::Path;
use crate::p2p::admission::EnsembleEndpoint;
@@ -6,14 +7,14 @@ use log::warn;
use rusqlite::Transaction;
use crate::agents::blob_document::{
ImportError, import_blob_document, load_blob_if_local, primary_blob_ref,
ImportError, cover_key, import_blob_document, load_blob_if_local, primary_blob_ref,
};
use crate::content_fetch::{self, ContentFetchError};
use crate::copy;
use crate::documents::import::ImportTarget;
use crate::documents::{
BlobRef, DocumentAvailability, DocumentID, DocumentType, PropertyKind, PropertyValue,
Timestamp, document_availability_bulk,
ArtifactKind, BlobRef, DocumentAvailability, DocumentID, DocumentType, PropertyKind,
PropertyValue, Timestamp, document_availability_bulk,
};
use crate::jobs::runner::JobRunner;
use crate::node::NodePubkey;
@@ -159,6 +160,10 @@ pub struct PdfListItem {
/// [`copy::pdf_library::secondary_line`] — so neither frontend picks its
/// own words for it.
pub subtitle: String,
/// What the cover — the first page, rendered — is cached under; `None`
/// while the PDF's bytes are on another node. See
/// [`cover_key`](crate::agents::blob_document::cover_key).
pub cover_key: Option<String>,
}
/// Build the PDF library: every `Pdf` document, sorted alphabetically by title.
@@ -176,6 +181,12 @@ pub fn build_pdf_nodes(store: &Store) -> Result<Vec<PdfListItem>, DocumentStoreE
)
.unwrap_or_default();
let mut properties = store.doc_store.list_properties_for_documents(tx, &ids)?;
// A cover is a nicety: a failed read costs the covers, not the list.
let mut blob_refs =
store.artifact_store.list_blob_refs_for_documents(tx, &ids).unwrap_or_else(|e| {
warn!("pdf: could not read the library's blob refs: {e}");
HashMap::new()
});
docs.into_iter()
.map(|doc| {
@@ -200,6 +211,12 @@ pub fn build_pdf_nodes(store: &Store) -> Result<Vec<PdfListItem>, DocumentStoreE
subtitle: copy::pdf_library::secondary_line(page_count, &doc.created_at, now),
created_at: doc.created_at,
page_count,
cover_key: blob_refs.remove(&doc.id).and_then(|refs| {
let content = refs.iter().find_map(|(kind, r)| {
(*kind == ArtifactKind::PrimaryContent).then_some(r)
});
cover_key(&store.blob_store, content)
}),
})
})
.collect::<Result<_, DocumentStoreError>>()
@@ -521,7 +538,6 @@ mod tests {
use rstest::rstest;
use tempfile::TempDir;
use crate::documents::ArtifactKind;
use crate::stores::node_content_status::ContentKey;
use crate::test_support::{TestStore, get_blob_ref, initialized_store, node, test_node};
@@ -783,6 +799,11 @@ mod tests {
// No node is known to hold the vanished ciphertext, so the entry is
// marked unavailable rather than merely not-downloaded.
assert_eq!(by_id(&missing_id).availability, DocumentAvailability::Unavailable);
// A cover is drawn from bytes held here, so only the local one has a key.
let local_ref =
get_blob_ref(&store.artifact_store, &local_id, ArtifactKind::PrimaryContent);
assert_eq!(by_id(&local_id).cover_key, Some(local_ref.unwrap().blob_hash.to_string()));
assert_eq!(by_id(&missing_id).cover_key, None);
// Evidence that a peer holds it flips the same entry to streamable.
store
+1 -1
View File
@@ -57,7 +57,7 @@ impl MusicFfi {
}
/// Image bytes for one library row that reported
/// [`music::LibraryEntry::has_cover`], ready to hand to a platform decoder.
/// [`music::LibraryEntry::cover_key`], ready to hand to a platform decoder.
///
/// An album's art is its own stored `Thumbnail`, returned untouched. An
/// artist has no art of its own, so this resolves the layering