ffi: drop SyncNodeCore::with_store for a plain store() binding (F9)

with_store(|store| body) only called f(&self.store()), so every one of its
~115 call sites paid a closure, an Ok(..) wrap and an extra indent for
nothing. Bind `let store = self.core.store();` once per method instead and
let `?` work directly. Mechanical; no behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-09-28 10:17:55 -07:00
1 parent b55b682c8e
commit b98cc54651
14 files changed
+831 -982

No files matched your search

+72 -89
View File
@@ -34,17 +34,17 @@ impl ComicsFfi {
/// the consumer groups by [`comics::ComicTreeItem::parent_id`] and sorts each level by
/// [`comics::ComicTreeItem::order`] to drill in and out.
pub fn list(&self) -> Result<Vec<comics::ComicTreeItem>, SyncError> {
self.core.with_store(|store| Ok(comics::build_comic_tree_nodes(store)?))
let store = self.core.store();
Ok(comics::build_comic_tree_nodes(&store)?)
}
/// A comic's expected total page count (from its `OrderTotal` metadata),
/// which can exceed the number of pages currently synced locally — see
/// [`Self::list_page_ids`].
pub fn page_count(&self, comic_id: String) -> Result<u32, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::page_count(&store.doc_store, &doc_id)?)
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::page_count(&store.doc_store, &doc_id)?)
}
/// The document ids of the comic's page images, in reading order; load
@@ -54,27 +54,25 @@ impl ComicsFfi {
/// [`Self::get_page_bytes`] streams. Can be shorter than
/// [`Self::page_count`] while pages are still syncing in.
pub fn list_page_ids(&self, comic_id: String) -> Result<Vec<String>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::list_comic_pages(&store.doc_store, &doc_id)?
.into_iter()
.map(|id| id.to_string())
.collect())
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::list_comic_pages(&store.doc_store, &doc_id)?
.into_iter()
.map(|id| id.to_string())
.collect())
}
/// The raw (still-encoded) image bytes of the comic's first page, for use
/// as a library cover thumbnail. Errors if no page has synced in yet.
pub fn get_cover_bytes(&self, comic_id: String) -> Result<Vec<u8>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::load_comic_cover_bytes(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&doc_id,
)?)
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::load_comic_cover_bytes(
&store.blob_store,
&store.doc_store,
&store.artifact_store,
&doc_id,
)?)
}
/// One page's raw (still-encoded) image bytes: the local blob store
@@ -163,27 +161,25 @@ impl ComicsFfi {
) -> Result<Vec<String>, SyncError> {
let ids =
page_ids.iter().map(|id| id.parse::<DocumentID>()).collect::<Result<Vec<_>, _>>()?;
self.core.with_store(|store| {
Ok(comics::pages_needing_prefetch(
&store.artifact_store,
&store.blob_store,
&ids,
current_index as usize,
comics::PREFETCH_AHEAD,
)
.into_iter()
.map(|id| id.to_string())
.collect())
})
let store = self.core.store();
Ok(comics::pages_needing_prefetch(
&store.artifact_store,
&store.blob_store,
&ids,
current_index as usize,
comics::PREFETCH_AHEAD,
)
.into_iter()
.map(|id| id.to_string())
.collect())
}
/// Read a comic's display metadata (series, issue title, number, writer,
/// summary, page count) back from its document properties.
pub fn get_metadata(&self, comic_id: String) -> Result<comics::ComicMetadata, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::comic_metadata(&store.doc_store, &doc_id)?)
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::comic_metadata(&store.doc_store, &doc_id)?)
}
/// The reader's last-viewed page (0-based) for this comic, or `None` when
@@ -194,23 +190,21 @@ impl ComicsFfi {
/// caller building an in-progress filter should treat `None` and `Some(0)`
/// alike rather than reading meaning into the distinction.
pub fn get_reading_progress(&self, comic_id: String) -> Result<Option<u32>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
let artifact = store.artifact_store.batch(|tx| {
store.artifact_store.get_artifact(tx, &doc_id, ArtifactKind::ReadingPosition)
})?;
Ok(artifact.and_then(|a| a.value.try_as_reading_position().map(|s| s.current_page)))
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
let artifact = store.artifact_store.batch(|tx| {
store.artifact_store.get_artifact(tx, &doc_id, ArtifactKind::ReadingPosition)
})?;
Ok(artifact.and_then(|a| a.value.try_as_reading_position().map(|s| s.current_page)))
}
/// Persist the reader's current page (0-based) for this comic.
pub fn set_reading_progress(&self, comic_id: String, page: u32) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
comics::save_reading_page(&store.artifact_store, &doc_id, page, local_node)?;
Ok(())
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
comics::save_reading_page(&store.artifact_store, &doc_id, page, local_node)?;
Ok(())
}
/// `node_id`'s own explicit reading-direction setting, if any — resolve
@@ -221,10 +215,9 @@ impl ComicsFfi {
&self,
node_id: String,
) -> Result<Option<comics::ReadingDirection>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = node_id.parse()?;
Ok(comics::reading_direction(&store.doc_store, &doc_id)?)
})
let store = self.core.store();
let doc_id: DocumentID = node_id.parse()?;
Ok(comics::reading_direction(&store.doc_store, &doc_id)?)
}
/// Set `node_id`'s explicit reading-direction setting — conventionally
@@ -236,20 +229,18 @@ impl ComicsFfi {
direction: comics::ReadingDirection,
) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
let doc_id: DocumentID = node_id.parse()?;
comics::save_reading_direction(&store.doc_store, &doc_id, direction, local_node)?;
Ok(())
})
let store = self.core.store();
let doc_id: DocumentID = node_id.parse()?;
comics::save_reading_direction(&store.doc_store, &doc_id, direction, local_node)?;
Ok(())
}
/// The id of the child issue last opened under a series `Collection`, if
/// any — the "continue reading" entry point for a multi-issue series.
pub fn get_latest_read_child(&self, parent_id: String) -> Result<Option<String>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = parent_id.parse()?;
Ok(comics::latest_read_child(&store.artifact_store, &doc_id).map(|id| id.to_string()))
})
let store = self.core.store();
let doc_id: DocumentID = parent_id.parse()?;
Ok(comics::latest_read_child(&store.artifact_store, &doc_id).map(|id| id.to_string()))
}
/// Record `child_id` as the latest-read child of the series `parent_id`.
@@ -259,50 +250,42 @@ impl ComicsFfi {
child_id: String,
) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
let parent: DocumentID = parent_id.parse()?;
let child: DocumentID = child_id.parse()?;
comics::save_latest_read_child(&store.artifact_store, &parent, child, local_node)?;
Ok(())
})
let store = self.core.store();
let parent: DocumentID = parent_id.parse()?;
let child: DocumentID = child_id.parse()?;
comics::save_latest_read_child(&store.artifact_store, &parent, child, local_node)?;
Ok(())
}
/// List a comic's bookmarks, ordered by page. Shares the `Bookmarks`
/// artifact kind (and [`BookmarkInfo`] shape) with PDFs.
pub fn list_bookmarks(&self, comic_id: String) -> Result<Vec<BookmarkInfo>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::list_bookmarks(&store.artifact_store, &doc_id)
.into_iter()
.map(|b| BookmarkInfo {
id: b.id,
page: b.page,
label: b.label.unwrap_or_default(),
})
.collect())
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
Ok(comics::list_bookmarks(&store.artifact_store, &doc_id)
.into_iter()
.map(|b| BookmarkInfo { id: b.id, page: b.page, label: b.label.unwrap_or_default() })
.collect())
}
/// Add a bookmark at `page` (0-based). The new bookmark's id comes back
/// from a subsequent [`Self::list_bookmarks`].
pub fn add_bookmark(&self, comic_id: String, page: u32) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
comics::add_bookmark(&store.artifact_store, &doc_id, page, local_node)?;
Ok(())
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
comics::add_bookmark(&store.artifact_store, &doc_id, page, local_node)?;
Ok(())
}
/// Delete a bookmark by its id, recording a tombstone so the removal
/// propagates and the bookmark does not resurrect from a peer.
pub fn delete_bookmark(&self, comic_id: String, bookmark_id: String) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
let doc_id: DocumentID = comic_id.parse()?;
comics::delete_bookmark(&store.artifact_store, &doc_id, &bookmark_id, local_node)?;
Ok(())
})
let store = self.core.store();
let doc_id: DocumentID = comic_id.parse()?;
comics::delete_bookmark(&store.artifact_store, &doc_id, &bookmark_id, local_node)?;
Ok(())
}
/// Import a `.cbz` archive (already read into memory) as a new `Comic`
+19 -20
View File
@@ -51,22 +51,21 @@ impl CredentialsFfi {
/// Every service this app knows how to hold a credential for, and what is
/// stored for each. One read, so a screen cannot render half a picture.
pub fn services(&self) -> Result<Vec<ServiceCredential>, SyncError> {
self.core.with_store(|store| {
let statuses = credentials::credential_status(store)?;
Ok(ServiceId::all()
.iter()
.map(|&id| {
let status = statuses.get(&id).cloned().unwrap_or(CredentialStatus::Missing);
ServiceCredential {
id,
display_name: id.display_name().to_string(),
fields: id.fields().iter().map(|f| (*f).to_string()).collect(),
status_line: copy::credentials::status_line(id, &status),
status,
}
})
.collect())
})
let store = self.core.store();
let statuses = credentials::credential_status(&store)?;
Ok(ServiceId::all()
.iter()
.map(|&id| {
let status = statuses.get(&id).cloned().unwrap_or(CredentialStatus::Missing);
ServiceCredential {
id,
display_name: id.display_name().to_string(),
fields: id.fields().iter().map(|f| (*f).to_string()).collect(),
status_line: copy::credentials::status_line(id, &status),
status,
}
})
.collect())
}
/// Seal one field of a service's credential with the ensemble's vault key.
@@ -81,9 +80,8 @@ impl CredentialsFfi {
value: String,
) -> Result<(), SyncError> {
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
Ok(credentials::set_credential_field(store, service, &field, &value, local_node)?)
})
let store = self.core.store();
Ok(credentials::set_credential_field(&store, service, &field, &value, local_node)?)
}
/// Forget a service's key on every node in the ensemble.
@@ -92,6 +90,7 @@ impl CredentialsFfi {
/// this is a deletion that travels. The confirmation before it says so —
/// [`copy::credentials::clear_warning`].
pub fn clear(&self, service: ServiceId) -> Result<(), SyncError> {
self.core.with_store(|store| Ok(credentials::clear_credential(store, service)?))
let store = self.core.store();
Ok(credentials::clear_credential(&store, service)?)
}
}
+322 -370
View File
@@ -44,22 +44,21 @@ impl DocumentsFfi {
document_types: Vec<String>,
date_filter: Option<String>,
) -> Result<Vec<DocumentItem>, SyncError> {
self.core.with_store(|store| {
let parsed_types =
document_types.iter().filter_map(|s| DocumentType::from_str(s).ok()).collect();
let params = SearchParams {
search_query,
document_types: parsed_types,
date_filter,
only_roots: false,
include_hidden: false,
};
store
.batch(|tx| store.doc_store.search_documents(tx, &params))?
.iter()
.map(|d| doc_to_item(store, d))
.collect()
})
let store = self.core.store();
let parsed_types =
document_types.iter().filter_map(|s| DocumentType::from_str(s).ok()).collect();
let params = SearchParams {
search_query,
document_types: parsed_types,
date_filter,
only_roots: false,
include_hidden: false,
};
store
.batch(|tx| store.doc_store.search_documents(tx, &params))?
.iter()
.map(|d| doc_to_item(&store, d))
.collect()
}
/// Keyset-paginated document search for list views. Reads one page at a time
@@ -92,117 +91,100 @@ impl DocumentsFfi {
cursor: Option<DocumentCursor>,
limit: u32,
) -> Result<DocumentPage, SyncError> {
self.core.with_store(|store| {
let parsed_types =
document_types.iter().filter_map(|s| DocumentType::from_str(s).ok()).collect();
let params = SearchParams {
search_query,
document_types: parsed_types,
date_filter,
only_roots,
include_hidden,
};
let store = self.core.store();
let parsed_types =
document_types.iter().filter_map(|s| DocumentType::from_str(s).ok()).collect();
let params = SearchParams {
search_query,
document_types: parsed_types,
date_filter,
only_roots,
include_hidden,
};
let (rows, context_rows, next_cursor) = store.batch(|tx| {
let (rows, next_cursor) = store.doc_store.search_document_items_page(
tx,
&params,
cursor.as_ref(),
limit,
)?;
// Ancestors come back in the same transaction as the matches
// they explain, so a consumer can't render a page whose context
// is one write out of date with it.
let context_rows = if params.is_filtered() {
let ids: Vec<String> = rows.iter().map(|r| r.id.clone()).collect();
store.doc_store.ancestors_of(tx, &ids)?
} else {
Vec::new()
};
Ok::<_, crate::stores::document::DocumentStoreError>((
rows,
context_rows,
next_cursor,
))
})?;
let annotate = |rows: Vec<crate::stores::document::DocumentListItem>| {
size_annotated_items(
store,
rows.into_iter().map(|item| {
(
item.id,
item.doc_type,
item.title,
item.created_at,
item.parent_id,
item.child_count,
)
}),
)
let (rows, context_rows, next_cursor) = store.batch(|tx| {
let (rows, next_cursor) =
store.doc_store.search_document_items_page(tx, &params, cursor.as_ref(), limit)?;
// Ancestors come back in the same transaction as the matches
// they explain, so a consumer can't render a page whose context
// is one write out of date with it.
let context_rows = if params.is_filtered() {
let ids: Vec<String> = rows.iter().map(|r| r.id.clone()).collect();
store.doc_store.ancestors_of(tx, &ids)?
} else {
Vec::new()
};
Ok(DocumentPage {
items: annotate(rows)?,
context: annotate(context_rows)?,
next_cursor,
})
})
Ok::<_, crate::stores::document::DocumentStoreError>((rows, context_rows, next_cursor))
})?;
let annotate = |rows: Vec<crate::stores::document::DocumentListItem>| {
size_annotated_items(
&store,
rows.into_iter().map(|item| {
(
item.id,
item.doc_type,
item.title,
item.created_at,
item.parent_id,
item.child_count,
)
}),
)
};
Ok(DocumentPage { items: annotate(rows)?, context: annotate(context_rows)?, next_cursor })
}
/// Direct children of `parent_id`, for expanding a turnstile in a
/// hierarchical document list. Not paginated — a single document's
/// direct children are expected to be small enough to load in one shot.
pub fn list_children(&self, parent_id: String) -> Result<Vec<DocumentItem>, SyncError> {
self.core.with_store(|store| {
let id = parent_id.parse::<DocumentID>()?;
let rows = store.batch(|tx| {
let children = store.doc_store.list_children(tx, &id)?;
children
.iter()
.map(|d| {
let title = store.doc_store.get_title(tx, &d.id)?.unwrap_or_default();
let child_count = store.doc_store.count_children(tx, &d.id)?;
Ok((
d.id.to_string(),
d.doc_type,
title,
d.created_at.to_rfc3339(),
d.parent_id.as_ref().map(|p| p.to_string()),
child_count,
))
})
.collect::<std::result::Result<Vec<_>, DocumentStoreError>>()
})?;
size_annotated_items(store, rows.into_iter())
})
let store = self.core.store();
let id = parent_id.parse::<DocumentID>()?;
let rows = store.batch(|tx| {
let children = store.doc_store.list_children(tx, &id)?;
children
.iter()
.map(|d| {
let title = store.doc_store.get_title(tx, &d.id)?.unwrap_or_default();
let child_count = store.doc_store.count_children(tx, &d.id)?;
Ok((
d.id.to_string(),
d.doc_type,
title,
d.created_at.to_rfc3339(),
d.parent_id.as_ref().map(|p| p.to_string()),
child_count,
))
})
.collect::<std::result::Result<Vec<_>, DocumentStoreError>>()
})?;
size_annotated_items(&store, rows.into_iter())
}
pub fn get(&self, document_id: String) -> Result<Option<DocumentItem>, SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
match store.batch(|tx| store.doc_store.get_document(tx, &id))? {
Some(doc) => Ok(Some(doc_to_item(store, &doc)?)),
None => Ok(None),
}
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
match store.batch(|tx| store.doc_store.get_document(tx, &id))? {
Some(doc) => Ok(Some(doc_to_item(&store, &doc)?)),
None => Ok(None),
}
}
pub fn list_properties(
&self,
document_id: String,
) -> Result<Vec<DocumentPropertyItem>, SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
let props = store.batch(|tx| store.doc_store.list_properties(tx, &id))?;
Ok(props
.into_iter()
.map(|p| DocumentPropertyItem {
kind: p.kind.type_name().to_string(),
value: format_property_value(&p.value),
modified_at: p.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
})
.collect())
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
let props = store.batch(|tx| store.doc_store.list_properties(tx, &id))?;
Ok(props
.into_iter()
.map(|p| DocumentPropertyItem {
kind: p.kind.type_name().to_string(),
value: format_property_value(&p.value),
modified_at: p.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
})
.collect())
}
/// The Placement table for one document: what its subtree amounts to, and
@@ -222,84 +204,76 @@ impl DocumentsFfi {
document_id: String,
) -> Result<DocumentPlacementView, SyncError> {
let id = document_id.parse::<DocumentID>()?;
self.core.with_store(|store| {
let placement = content_ledger::document_placement(store, &id)?;
let local = store.settings_store.local_node_pubkey()?;
let timezone = store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))
.ok()
.flatten();
let tz = timezone.as_ref().and_then(|s| s.timezone);
let local_name = timezone.and_then(|s| s.node_name);
let (local_name, local_name_is_placeholder) =
node_display::resolve(local_name.as_deref());
let store = self.core.store();
let placement = content_ledger::document_placement(&store, &id)?;
let local = store.settings_store.local_node_pubkey()?;
let timezone =
store.settings_store.batch(|tx| store.settings_store.load_settings(tx)).ok().flatten();
let tz = timezone.as_ref().and_then(|s| s.timezone);
let local_name = timezone.and_then(|s| s.node_name);
let (local_name, local_name_is_placeholder) = node_display::resolve(local_name.as_deref());
let override_for_doc = store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.get(tx, &id))?;
let override_for_doc = store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.get(tx, &id))?;
let mut rows = vec![DocumentPlacementRow {
node_id_hex: local.map(|n| n.to_hex()).unwrap_or_default(),
display_name: local_name,
name_is_placeholder: local_name_is_placeholder,
is_this_node: true,
let mut rows = vec![DocumentPlacementRow {
node_id_hex: local.map(|n| n.to_hex()).unwrap_or_default(),
display_name: local_name,
name_is_placeholder: local_name_is_placeholder,
is_this_node: true,
content_line: copy::placement_content(
Some(placement.here.files),
placement.files_total,
),
confirmed_at: None,
version_line: String::new(),
sync_override: override_for_doc,
override_known: true,
}];
let records: HashMap<NodePubkey, _> = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?
.into_iter()
.map(|r| (r.node_pubkey, r))
.collect();
let membership = store.settings_store.membership()?;
let peers = match membership {
Some(m) => store.peer_node_store.batch(|tx| {
store.peer_node_store.get_peer_nodes_for_ensemble(tx, &m.ensemble_pubkey)
})?,
None => Vec::new(),
};
for peer in peers {
let node = NodePubkey(peer.node_pubkey);
if Some(node) == local {
continue;
}
let holding = placement.peers.get(&node);
let (display_name, name_is_placeholder) =
node_display::resolve(peer.display_name.as_deref());
rows.push(DocumentPlacementRow {
node_id_hex: node.to_hex(),
display_name,
name_is_placeholder,
is_this_node: false,
content_line: copy::placement_content(
Some(placement.here.files),
holding.map(|h| h.files),
placement.files_total,
),
confirmed_at: None,
version_line: String::new(),
sync_override: override_for_doc,
override_known: true,
}];
let records: HashMap<NodePubkey, _> = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?
.into_iter()
.map(|r| (r.node_pubkey, r))
.collect();
let membership = store.settings_store.membership()?;
let peers = match membership {
Some(m) => store.peer_node_store.batch(|tx| {
store.peer_node_store.get_peer_nodes_for_ensemble(tx, &m.ensemble_pubkey)
})?,
None => Vec::new(),
};
for peer in peers {
let node = NodePubkey(peer.node_pubkey);
if Some(node) == local {
continue;
}
let holding = placement.peers.get(&node);
let (display_name, name_is_placeholder) =
node_display::resolve(peer.display_name.as_deref());
rows.push(DocumentPlacementRow {
node_id_hex: node.to_hex(),
display_name,
name_is_placeholder,
is_this_node: false,
content_line: copy::placement_content(
holding.map(|h| h.files),
placement.files_total,
),
confirmed_at: holding
.and_then(|h| h.confirmed_at)
.map(|at| at.format_display(tz)),
version_line: version_line(records.get(&node), tz),
sync_override: None,
override_known: false,
});
}
Ok(DocumentPlacementView {
files_total: placement.files_total,
summary_line: copy::placement_summary(placement.files_total, placement.bytes_total),
rows,
})
confirmed_at: holding.and_then(|h| h.confirmed_at).map(|at| at.format_display(tz)),
version_line: version_line(records.get(&node), tz),
sync_override: None,
override_known: false,
});
}
Ok(DocumentPlacementView {
files_total: placement.files_total,
summary_line: copy::placement_summary(placement.files_total, placement.bytes_total),
rows,
})
}
@@ -307,35 +281,31 @@ impl DocumentsFfi {
&self,
document_id: String,
) -> Result<Vec<DocumentNodeStatusItem>, SyncError> {
let local_pubkey = self
.core
.with_store(|store| Ok(store.settings_store.local_node_pubkey()?))
.ok()
.flatten();
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
let records = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?;
let peer_names =
build_peer_name_lookup(&store.settings_store, &store.peer_node_store, local_pubkey);
Ok(records
.into_iter()
.map(|r| {
let hex = r.node_pubkey.to_hex();
let is_local = local_pubkey == Some(r.node_pubkey);
let node_name = peer_names.get(&hex).cloned().unwrap_or_default();
DocumentNodeStatusItem {
node_id_short: copy::short_id(&hex),
node_id_full: hex,
node_name,
presence: NodePresence::from(&r.presence),
observed_at: r.observed_at.0.format("%b %d, %Y %H:%M").to_string(),
is_local,
}
})
.collect())
})
let store = self.core.store();
let local_pubkey = store.settings_store.local_node_pubkey().ok().flatten();
let id = document_id.parse::<DocumentID>()?;
let records = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?;
let peer_names =
build_peer_name_lookup(&store.settings_store, &store.peer_node_store, local_pubkey);
Ok(records
.into_iter()
.map(|r| {
let hex = r.node_pubkey.to_hex();
let is_local = local_pubkey == Some(r.node_pubkey);
let node_name = peer_names.get(&hex).cloned().unwrap_or_default();
DocumentNodeStatusItem {
node_id_short: copy::short_id(&hex),
node_id_full: hex,
node_name,
presence: NodePresence::from(&r.presence),
observed_at: r.observed_at.0.format("%b %d, %Y %H:%M").to_string(),
is_local,
}
})
.collect())
}
/// This document's **inline** artifacts: the ones whose value lives in the
@@ -356,146 +326,134 @@ impl DocumentsFfi {
&self,
document_id: String,
) -> Result<Vec<DocumentArtifactItem>, SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
let (artifacts, stubs) = store.artifact_store.batch(|tx| {
Ok::<_, crate::stores::artifact::ArtifactStoreError>((
store.artifact_store.list_artifacts(tx, &id)?,
store.artifact_store.list_artifact_stubs(tx, &id)?,
))
})?;
let mut items: Vec<DocumentArtifactItem> = artifacts
.into_iter()
.filter(|a| a.kind().storage() == Storage::Inline)
.map(|a| {
let size_bytes =
serde_json::to_vec(&a.value).map(|v| v.len() as u64).unwrap_or(0);
DocumentArtifactItem {
id: a.id.to_string(),
kind: a.kind().type_name().to_string(),
summary: format_artifact_value(&a.value),
modified_at: a.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
size_bytes,
present_locally: true,
}
})
.collect();
let held_kinds: Vec<_> = items.iter().map(|i| i.kind.clone()).collect();
items.extend(stubs.into_iter().map(|s| DocumentArtifactItem {
id: s.id.to_string(),
kind: s.kind.type_name().to_string(),
summary: artifact_stub_summary(
s.kind,
s.size_bytes,
held_kinds.iter().any(|k| k == s.kind.type_name()),
),
modified_at: s.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
size_bytes: s.size_bytes,
present_locally: false,
}));
// Kind first so related rows stay together, then id so the order
// is stable across calls. Kind alone isn't enough: collection
// kinds have several rows sharing one kind, and SQLite returns
// them in no guaranteed order, so they'd swap places every time
// the screen reloads. Same rule the daemon snapshot and desktop
// use.
items.sort_by(|a, b| (&a.kind, &a.id).cmp(&(&b.kind, &b.id)));
Ok(items)
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
let (artifacts, stubs) = store.artifact_store.batch(|tx| {
Ok::<_, crate::stores::artifact::ArtifactStoreError>((
store.artifact_store.list_artifacts(tx, &id)?,
store.artifact_store.list_artifact_stubs(tx, &id)?,
))
})?;
let mut items: Vec<DocumentArtifactItem> = artifacts
.into_iter()
.filter(|a| a.kind().storage() == Storage::Inline)
.map(|a| {
let size_bytes = serde_json::to_vec(&a.value).map(|v| v.len() as u64).unwrap_or(0);
DocumentArtifactItem {
id: a.id.to_string(),
kind: a.kind().type_name().to_string(),
summary: format_artifact_value(&a.value),
modified_at: a.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
size_bytes,
present_locally: true,
}
})
.collect();
let held_kinds: Vec<_> = items.iter().map(|i| i.kind.clone()).collect();
items.extend(stubs.into_iter().map(|s| DocumentArtifactItem {
id: s.id.to_string(),
kind: s.kind.type_name().to_string(),
summary: artifact_stub_summary(
s.kind,
s.size_bytes,
held_kinds.iter().any(|k| k == s.kind.type_name()),
),
modified_at: s.modified_at.0.format("%b %d, %Y %H:%M").to_string(),
size_bytes: s.size_bytes,
present_locally: false,
}));
// Kind first so related rows stay together, then id so the order
// is stable across calls. Kind alone isn't enough: collection
// kinds have several rows sharing one kind, and SQLite returns
// them in no guaranteed order, so they'd swap places every time
// the screen reloads. Same rule the daemon snapshot and desktop
// use.
items.sort_by(|a, b| (&a.kind, &a.id).cmp(&(&b.kind, &b.id)));
Ok(items)
}
pub fn list_blob_refs(
&self,
document_id: String,
) -> Result<Vec<DocumentBlobRefItem>, SyncError> {
let local_pubkey = self
.core
.with_store(|store| Ok(store.settings_store.local_node_pubkey()?))
.ok()
.flatten();
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
let refs =
store.artifact_store.batch(|tx| store.artifact_store.list_blob_refs(tx, &id))?;
let node_records = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?;
let peer_names =
build_peer_name_lookup(&store.settings_store, &store.peer_node_store, local_pubkey);
let mut items = store.node_content_status_store.batch(|tx| {
Ok::<_, crate::stores::node_content_status::NodeContentStatusError>(
refs.into_iter()
.map(|(kind, r)| {
let key = ContentKey::Blob(r.blob_hash.clone());
let released_at =
store.content_release_store.released_at(tx, &key).ok().flatten();
let node_statuses = node_records
.iter()
.map(|nr| {
let hex = nr.node_pubkey.to_hex();
let is_local = local_pubkey == Some(nr.node_pubkey);
let node_name =
peer_names.get(&hex).cloned().unwrap_or_default();
let evidence = store
.node_content_status_store
.presence_of(tx, &nr.node_pubkey, &key)
.ok()
.flatten();
let (presence, ts) = blob_presence_for_node(
nr,
local_pubkey,
&r,
&store.blob_store,
evidence,
released_at,
);
DocumentNodeStatusItem {
node_id_short: copy::short_id(&hex),
node_id_full: hex,
node_name,
presence,
observed_at: ts.0.format("%b %d, %Y %H:%M").to_string(),
is_local,
}
})
.collect();
DocumentBlobRefItem {
kind: kind.type_name().to_string(),
blob_hash: r.blob_hash.to_string(),
size_bytes: r.size_bytes,
present_locally: store.blob_store.exists(&r.blob_hash),
node_statuses,
}
})
.collect::<Vec<DocumentBlobRefItem>>(),
)
})?;
// Kind first, then hash — the same ordering `list_artifacts` and
// the daemon snapshot use, so a document's rows don't reshuffle
// between reloads when several attachments share a kind.
items.sort_by(|a, b| (&a.kind, &a.blob_hash).cmp(&(&b.kind, &b.blob_hash)));
Ok(items)
})
let store = self.core.store();
let local_pubkey = store.settings_store.local_node_pubkey().ok().flatten();
let id = document_id.parse::<DocumentID>()?;
let refs = store.artifact_store.batch(|tx| store.artifact_store.list_blob_refs(tx, &id))?;
let node_records = store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.list_nodes_for_document(tx, &id))?;
let peer_names =
build_peer_name_lookup(&store.settings_store, &store.peer_node_store, local_pubkey);
let mut items = store.node_content_status_store.batch(|tx| {
Ok::<_, crate::stores::node_content_status::NodeContentStatusError>(
refs.into_iter()
.map(|(kind, r)| {
let key = ContentKey::Blob(r.blob_hash.clone());
let released_at =
store.content_release_store.released_at(tx, &key).ok().flatten();
let node_statuses = node_records
.iter()
.map(|nr| {
let hex = nr.node_pubkey.to_hex();
let is_local = local_pubkey == Some(nr.node_pubkey);
let node_name = peer_names.get(&hex).cloned().unwrap_or_default();
let evidence = store
.node_content_status_store
.presence_of(tx, &nr.node_pubkey, &key)
.ok()
.flatten();
let (presence, ts) = blob_presence_for_node(
nr,
local_pubkey,
&r,
&store.blob_store,
evidence,
released_at,
);
DocumentNodeStatusItem {
node_id_short: copy::short_id(&hex),
node_id_full: hex,
node_name,
presence,
observed_at: ts.0.format("%b %d, %Y %H:%M").to_string(),
is_local,
}
})
.collect();
DocumentBlobRefItem {
kind: kind.type_name().to_string(),
blob_hash: r.blob_hash.to_string(),
size_bytes: r.size_bytes,
present_locally: store.blob_store.exists(&r.blob_hash),
node_statuses,
}
})
.collect::<Vec<DocumentBlobRefItem>>(),
)
})?;
// Kind first, then hash — the same ordering `list_artifacts` and
// the daemon snapshot use, so a document's rows don't reshuffle
// between reloads when several attachments share a kind.
items.sort_by(|a, b| (&a.kind, &a.blob_hash).cmp(&(&b.kind, &b.blob_hash)));
Ok(items)
}
pub fn get_blob_bytes(&self, document_id: String) -> Result<Vec<u8>, SyncError> {
let blob_ref = self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
store
.artifact_store
.batch(|tx| {
store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent)
})?
.ok_or_else(|| SyncError::NotFound {
msg: format!("no primary-content artifact for {document_id}"),
})
})?;
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
let blob_ref = store
.artifact_store
.batch(|tx| store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent))?
.ok_or_else(|| SyncError::NotFound {
msg: format!("no primary-content artifact for {document_id}"),
})?;
// Load outside with_store so a missing blob keeps its typed
// BlobStoreError::NotFound and converts to SyncError::NotFound (rather than
// being stringified into General). Blob unavailability is normal, and the
// Kotlin caller treats NotFound as "return null" instead of crashing.
let store = self.core.store();
store
.blob_store
.load(&blob_ref.blob_hash, &blob_ref.plaintext_hash, blob_ref.vault_id)
@@ -503,17 +461,14 @@ impl DocumentsFfi {
}
pub fn is_blob_local(&self, document_id: String) -> Result<bool, SyncError> {
let blob_ref = self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
Ok(store.artifact_store.batch(|tx| {
store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent)
})?)
})?;
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
let blob_ref = store
.artifact_store
.batch(|tx| store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent))?;
match blob_ref {
None => Ok(false),
Some(r) => self
.core
.with_store(|store| Ok::<bool, SyncError>(store.blob_store.exists(&r.blob_hash))),
Some(r) => Ok(store.blob_store.exists(&r.blob_hash)),
}
}
@@ -536,29 +491,26 @@ impl DocumentsFfi {
output_path: String,
) -> Result<(), SyncError> {
let id: DocumentID = document_id.parse()?;
self.core.with_store(|store| {
let blob_ref = store
.artifact_store
.batch(|tx| {
store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent)
})?
.ok_or_else(|| SyncError::NotFound {
msg: format!("no primary-content artifact for {document_id}"),
})?;
store
.blob_store
.load_to_file(
&blob_ref.blob_hash,
&blob_ref.plaintext_hash,
blob_ref.vault_id,
std::path::Path::new(&output_path),
|_| ControlFlow::Continue(()),
)
.map_err(|e| SyncError::Internal {
msg: format!("decrypt {document_id} to {output_path}: {e}"),
})?;
Ok(())
})
let store = self.core.store();
let blob_ref = store
.artifact_store
.batch(|tx| store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::PrimaryContent))?
.ok_or_else(|| SyncError::NotFound {
msg: format!("no primary-content artifact for {document_id}"),
})?;
store
.blob_store
.load_to_file(
&blob_ref.blob_hash,
&blob_ref.plaintext_hash,
blob_ref.vault_id,
std::path::Path::new(&output_path),
|_| ControlFlow::Continue(()),
)
.map_err(|e| SyncError::Internal {
msg: format!("decrypt {document_id} to {output_path}: {e}"),
})?;
Ok(())
}
/// Write a document's primary content to `output_path` as plaintext — from
+53 -64
View File
@@ -90,16 +90,15 @@ impl EnsembleFfi {
/// which all fail the same way when the node isn't in an ensemble or has
/// no peers recorded yet.
fn ensemble_peer_ids(&self) -> Result<Vec<NodePubkey>, SyncError> {
let peers = self.core.with_store(|store| {
let ensemble_pubkey = store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "not in ensemble".into() })?
.ensemble_pubkey;
Ok(store.peer_node_store.batch(|tx| {
store.peer_node_store.get_peer_nodes_for_ensemble(tx, &ensemble_pubkey)
})?)
})?;
let store = self.core.store();
let ensemble_pubkey = store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "not in ensemble".into() })?
.ensemble_pubkey;
let peers = store
.peer_node_store
.batch(|tx| store.peer_node_store.get_peer_nodes_for_ensemble(tx, &ensemble_pubkey))?;
if peers.is_empty() {
return Err(SyncError::Offline { msg: "no peers available to sync from".into() });
}
@@ -131,16 +130,14 @@ impl EnsembleFfi {
/// A node's announced name, or `None` — including for one this node has
/// never heard from, which is a legitimate thing to hold a revocation for.
fn peer_name(&self, peer: &NodePubkey) -> Option<String> {
self.core
.with_store(|store| {
Ok(crate::node_status::build_peer_name_lookup(
&store.settings_store,
&store.peer_node_store,
store.settings_store.local_node_pubkey().ok().flatten(),
))
})
.ok()
.and_then(|names| names.get(&peer.to_hex()).cloned())
let store = self.core.store();
crate::node_status::build_peer_name_lookup(
&store.settings_store,
&store.peer_node_store,
store.settings_store.local_node_pubkey().ok().flatten(),
)
.get(&peer.to_hex())
.cloned()
}
/// The endpoint, runtime handle and store of the running P2P node, or
@@ -173,19 +170,16 @@ impl EnsembleFfi {
// gossip announcements pick up from settings once this node joins the topic.
// Deliberately not part of the pkarr record it publishes next — that record
// is world-readable (ADR 0044).
self.core.with_store(|store| {
store.settings_store.batch(|tx| store.settings_store.initialize_node(tx))?;
if node_name.is_some() {
store
.settings_store
.batch(|tx| store.settings_store.set_node_name(tx, node_name.clone()))?;
}
Ok(())
})?;
let store = self.core.store();
store.settings_store.batch(|tx| store.settings_store.initialize_node(tx))?;
if node_name.is_some() {
store
.settings_store
.batch(|tx| store.settings_store.set_node_name(tx, node_name.clone()))?;
}
// Async join + pkarr publish. self.core.store() only clones an Arc, so no
// store lock is held across the network I/O.
let store = self.core.store();
let rt = tokio::runtime::Runtime::new()
.map_err(|e| SyncError::Internal { msg: e.to_string() })?;
rt.block_on(crate::ensemble::init::join_existing_ensemble(
@@ -205,10 +199,9 @@ impl EnsembleFfi {
let gossip_neighbor_count = self.get_gossip_neighbor_count();
let known_registry_members =
self.core.p2p.get().map(|p2p| p2p.node.known_registry_members()).unwrap_or_default();
self.core.with_store(|store| {
build_ensemble_status(store, gossip_neighbor_count, &known_registry_members)
.map_err(|e| SyncError::Internal { msg: e.to_string() })
})
let store = self.core.store();
build_ensemble_status(&store, gossip_neighbor_count, &known_registry_members)
.map_err(|e| SyncError::Internal { msg: e.to_string() })
}
/// Returns the number of live gossip neighbors for the current node, or 0 if
@@ -239,13 +232,13 @@ impl EnsembleFfi {
};
(sender, p2p.node.registry_cache_handle(), p2p.runtime.handle().clone())
};
let (ensemble_pubkey, our_node_pubkey) = self.core.with_store(|store| {
let membership = store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "not in an ensemble".into() })?;
Ok((membership.ensemble_pubkey, membership.delegation_cert.node_pubkey))
})?;
let store = self.core.store();
let membership = store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "not in an ensemble".into() })?;
let (ensemble_pubkey, our_node_pubkey) =
(membership.ensemble_pubkey, membership.delegation_cert.node_pubkey);
rt_handle.spawn(async move {
crate::node::do_bootstrap_retry(
&sender,
@@ -264,18 +257,15 @@ impl EnsembleFfi {
return Ok(());
}
let keypair = self.core.with_store(|store| {
store.settings_store.load_keypair()?.ok_or_else(|| SyncError::NotInitialized {
msg: "Node not initialized — no keypair found".into(),
})
})?;
let membership = self.core.with_store(|store| {
store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Not part of any ensemble".into() })
})?;
let store = self.core.store();
let keypair = store.settings_store.load_keypair()?.ok_or_else(|| {
SyncError::NotInitialized { msg: "Node not initialized — no keypair found".into() }
})?;
let membership = store
.settings_store
.membership()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Not part of any ensemble".into() })?;
// The ensemble's key for sealing this node's name in its announcements
// — see `p2p::sealed_name`. Missing it means announcing unnamed, not
// announcing in the clear, so a failure here is logged and carried on
@@ -322,9 +312,9 @@ impl EnsembleFfi {
// identity back onto the network *after* the wipe, which is exactly
// what the reset was for. The store is the authority on who this node
// is, so ask it again before committing.
let still_ours = self
.core
.with_store(|store| Ok(store.settings_store.load_keypair()?))?
let still_ours = store
.settings_store
.load_keypair()?
.is_some_and(|current| current.public_key_hex() == keypair.public_key_hex());
if !still_ours {
log::warn!("Node identity changed while P2P was starting — shutting the new node down");
@@ -362,8 +352,8 @@ impl EnsembleFfi {
let peer: NodePubkey = node_id_hex
.parse()
.map_err(|e| SyncError::InvalidInput { msg: format!("invalid node id: {e}") })?;
let local =
self.core.with_store(|store| Ok(store.settings_store.local_node_pubkey()?))?;
let store = self.core.store();
let local = store.settings_store.local_node_pubkey()?;
if local == Some(peer) {
return Err(SyncError::InvalidInput {
msg: "that is this node — retiring it is a different act, and needs no keyphrase"
@@ -371,7 +361,7 @@ impl EnsembleFfi {
});
}
let record = retire::revoke_peer(&self.core.store(), &peer.0, &keyphrase)?;
let record = retire::revoke_peer(&store, &peer.0, &keyphrase)?;
self.gossip_revocation(&record);
Ok(RevokedNodeInfo {
@@ -714,9 +704,8 @@ impl EnsembleFfi {
/// which warns how much a purge will take with it.
pub fn count_document_descendants(&self, document_id: String) -> Result<u32, SyncError> {
let doc_id = document_id.parse::<DocumentID>()?;
self.core.with_store(|store| {
Ok(store.batch(|tx| store.doc_store.count_descendants(tx, &doc_id))? as u32)
})
let store = self.core.store();
Ok(store.batch(|tx| store.doc_store.count_descendants(tx, &doc_id))? as u32)
}
/// Purge a document (and its descendants): delete it locally, then — best
@@ -729,9 +718,9 @@ impl EnsembleFfi {
let doc_id = document_id.parse::<DocumentID>()?;
let local_node = self.core.local_node_pubkey_required()?;
let purged_ids = self.core.with_store(|store| {
Ok(store.batch(|tx| store.doc_store.purge_recursive(tx, &doc_id, local_node))?)
})?;
let store = self.core.store();
let purged_ids =
store.batch(|tx| store.doc_store.purge_recursive(tx, &doc_id, local_node))?;
let mut broadcast = false;
if let Some(p2p) = self.core.p2p.get()
+7 -11
View File
@@ -118,11 +118,8 @@ impl EvictionFfi {
/// The last-copy guard's buried "allow deleting unverified content"
/// override — off by default. See [`Self::set_allow_unverified_deletion`].
pub fn get_allow_unverified_deletion(&self) -> Result<bool, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.allow_unverified_deletion(tx))?)
})
let store = self.core.store();
Ok(store.settings_store.batch(|tx| store.settings_store.allow_unverified_deletion(tx))?)
}
/// Persist the buried override. Deliberately not surfaced anywhere near
@@ -131,11 +128,10 @@ impl EvictionFfi {
/// moment by a checkbox on the dialog itself," same as desktop's System
/// tab "Danger Zone".
pub fn set_allow_unverified_deletion(&self, allow: bool) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_allow_unverified_deletion(tx, allow))?;
Ok(())
})
let store = self.core.store();
store
.settings_store
.batch(|tx| store.settings_store.set_allow_unverified_deletion(tx, allow))?;
Ok(())
}
}
-1
View File
@@ -419,7 +419,6 @@ impl ImportBatch {
let origin_node = self.core.local_node_pubkey_required()?;
let parent = parent_id.map(|p| p.parse::<DocumentID>()).transpose()?;
let store = self.core.store();
let staged =
StagedFile::write(&store, &staged_name(file_name, mime_type), bytes).map_err(|e| {
SyncError::Internal { msg: format!("could not stage {file_name}: {e}") }
+9 -12
View File
@@ -63,24 +63,21 @@ impl JobsFfi {
}
pub fn list_active_jobs(&self) -> Result<Vec<JobItem>, SyncError> {
self.core.with_store(|store| {
let jobs = store.job_store.batch(|tx| store.job_store.list_active(tx))?;
Ok(jobs_to_items(store, jobs))
})
let store = self.core.store();
let jobs = store.job_store.batch(|tx| store.job_store.list_active(tx))?;
Ok(jobs_to_items(&store, jobs))
}
pub fn list_job_history(&self, limit: u32) -> Result<Vec<JobItem>, SyncError> {
self.core.with_store(|store| {
let jobs = store.job_store.batch(|tx| store.job_store.list_history(tx, limit))?;
Ok(jobs_to_items(store, jobs))
})
let store = self.core.store();
let jobs = store.job_store.batch(|tx| store.job_store.list_history(tx, limit))?;
Ok(jobs_to_items(&store, jobs))
}
pub fn clear_job_history(&self) -> Result<(), SyncError> {
self.core.with_store(|store| {
store.job_store.batch(|tx| store.job_store.clear_history(tx))?;
Ok(())
})
let store = self.core.store();
store.job_store.batch(|tx| store.job_store.clear_history(tx))?;
Ok(())
}
}
+11 -8
View File
@@ -35,7 +35,8 @@ impl MusicFfi {
/// `Collection` groupings that contain at least one. Unsorted and flat —
/// the consumer groups by [`MusicTreeItem::parent_id`] to drill in and out.
pub fn list_tree(&self) -> Result<Vec<music::MusicTreeItem>, SyncError> {
self.core.with_store(|store| Ok(music::build_music_nodes(store)?))
let store = self.core.store();
Ok(music::build_music_nodes(&store)?)
}
/// One level of the tag-derived Artist -> Album -> Track library
@@ -59,7 +60,8 @@ impl MusicFfi {
music::LibraryLevel::Tracks { album_id: album_id.parse()? }
}
};
self.core.with_store(|store| Ok(music::library_entries(store, &level)?))
let store = self.core.store();
Ok(music::library_entries(&store, &level)?)
}
/// Image bytes for one library row that reported
@@ -79,21 +81,22 @@ impl MusicFfi {
kind: music::LibraryEntryKind,
) -> Result<Option<Vec<u8>>, SyncError> {
let id: DocumentID = entry_id.parse()?;
self.core.with_store(|store| match kind {
let store = self.core.store();
match kind {
music::LibraryEntryKind::Track => Ok(None),
music::LibraryEntryKind::Album => Ok(thumbnail_bytes(store, &id)),
music::LibraryEntryKind::Album => Ok(thumbnail_bytes(&store, &id)),
music::LibraryEntryKind::Artist => {
match music::artist_art(store, &id, music::MOSAIC_TILES)? {
music::ArtistArt::Portrait(blob_ref) => Ok(load_blob_bytes(store, &blob_ref)),
match music::artist_art(&store, &id, music::MOSAIC_TILES)? {
music::ArtistArt::Portrait(blob_ref) => Ok(load_blob_bytes(&store, &blob_ref)),
music::ArtistArt::Covers(refs) => {
let covers: Vec<Vec<u8>> =
refs.iter().filter_map(|r| load_blob_bytes(store, r)).collect();
refs.iter().filter_map(|r| load_blob_bytes(&store, r)).collect();
Ok(music::compose_artist_art(&covers).and_then(encode_png))
}
music::ArtistArt::None => Ok(None),
}
}
})
}
}
/// Build the tag-derived library the [`Self::list_library`] levels read:
+32 -49
View File
@@ -62,14 +62,6 @@ impl SyncNodeCore {
self.store.read().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Run `f` against the current store, mapping its error into [`SyncError`].
pub(super) fn with_store<F, R>(&self, f: F) -> Result<R, SyncError>
where
F: FnOnce(&Store) -> Result<R, SyncError>,
{
f(&self.store())
}
/// The running P2P node's endpoint, a runtime handle to block on async
/// calls outside a `run_as_job` closure's own async work, and the
/// current store — the shared preamble for FFI methods that make a live
@@ -111,10 +103,9 @@ impl SyncNodeCore {
}
pub(super) fn local_node_pubkey_required(&self) -> Result<NodePubkey, SyncError> {
self.with_store(|store| {
store.settings_store.local_node_pubkey()?.ok_or_else(|| SyncError::NotInitialized {
msg: "Node not initialized — call initialize_node() first".into(),
})
let store = self.store();
store.settings_store.local_node_pubkey()?.ok_or_else(|| SyncError::NotInitialized {
msg: "Node not initialized — call initialize_node() first".into(),
})
}
@@ -135,9 +126,8 @@ impl SyncNodeCore {
F: FnOnce(&NotebookManager, &Store) -> Result<R, SyncError>,
{
let origin_node = self.local_node_pubkey_required()?;
self.with_store(|store| {
f(&NotebookManager::new(&store.doc_store, &store.artifact_store, origin_node), store)
})
let store = self.store();
f(&NotebookManager::new(&store.doc_store, &store.artifact_store, origin_node), &store)
}
/// Run `f` with a [`ClippingsManager`] bound to the current store and the
@@ -148,9 +138,8 @@ impl SyncNodeCore {
F: FnOnce(&ClippingsManager) -> Result<R, SyncError>,
{
let origin_node = self.local_node_pubkey_required()?;
self.with_store(|store| {
f(&ClippingsManager::new(&store.doc_store, &store.artifact_store, origin_node))
})
let store = self.store();
f(&ClippingsManager::new(&store.doc_store, &store.artifact_store, origin_node))
}
/// Run `f` with a [`HumansManager`] bound to the current store and the local
@@ -160,7 +149,8 @@ impl SyncNodeCore {
F: FnOnce(&HumansManager) -> Result<R, SyncError>,
{
let origin_node = self.local_node_pubkey_required()?;
self.with_store(|store| f(&HumansManager::new(store, origin_node)))
let store = self.store();
f(&HumansManager::new(&store, origin_node))
}
/// Import `bytes` as a new blob-backed document of `doc_type` under
@@ -188,15 +178,14 @@ impl SyncNodeCore {
let label = label.into();
run_one_file_import(&self.job_runner, label, bytes.len() as u64, |progress| {
let stored = self.with_store(|store| {
Ok(store.blob_store.store_reporting(
bytes,
crate::vault::DEFAULT_VAULT_ID,
progress,
)?)
})?;
let store = self.store();
let stored = store.blob_store.store_reporting(
bytes,
crate::vault::DEFAULT_VAULT_ID,
progress,
)?;
let doc_id_str = self.with_store(|store| {
let doc_id_str = {
let doc = Document::new(doc_type, parent.clone(), origin_node);
let doc_id = doc.id.clone();
store.doc_store.batch(|tx| store.doc_store.add_document(tx, doc))?;
@@ -218,16 +207,13 @@ impl SyncNodeCore {
),
)
})?;
Ok(doc_id.to_string())
})?;
doc_id.to_string()
};
let doc_id: DocumentID = doc_id_str.parse()?;
self.with_store(|store| {
Ok(store.node_doc_status_store.batch(|tx| {
store.node_doc_status_store.mark_present(tx, &doc_id, &origin_node)
})?)
})?;
store
.node_doc_status_store
.batch(|tx| store.node_doc_status_store.mark_present(tx, &doc_id, &origin_node))?;
Ok(doc_id_str)
})
}
@@ -241,7 +227,7 @@ impl SyncNodeCore {
///
/// `SyncNode` itself is just a thin wrapper around the shared [`SyncNodeCore`]
/// — it `Deref`s to it so its own methods below can keep referring to
/// `self.store`/`self.with_store(...)`/etc. directly, exactly as if those
/// `self.store()`/`self.job_runner`/etc. directly, exactly as if those
/// fields and helpers still lived on `SyncNode`.
#[derive(uniffi::Object)]
pub struct SyncNode {
@@ -371,16 +357,14 @@ impl SyncNode {
}
pub fn node_initialized(&self) -> Result<bool, SyncError> {
self.with_store(|store| {
Ok(store.settings_store.batch(|tx| store.settings_store.node_initialized(tx))?)
})
let store = self.store();
Ok(store.settings_store.batch(|tx| store.settings_store.node_initialized(tx))?)
}
pub fn initialize_node(&self) -> Result<(), SyncError> {
self.with_store(|store| {
store.settings_store.batch(|tx| store.settings_store.initialize_node(tx))?;
Ok(())
})
let store = self.store();
store.settings_store.batch(|tx| store.settings_store.initialize_node(tx))?;
Ok(())
}
/// Destroy this node: take it off the network, then delete everything the
@@ -420,7 +404,8 @@ impl SyncNode {
// Everything under the store path, not an enumerated subset of it —
// see [`Store::wipe_contents`].
self.with_store(|store| Ok(store.wipe_contents()?))?;
let store = self.store();
store.wipe_contents()?;
// The wipe leaves an empty directory, so this is first-time setup
// again rather than an open.
@@ -458,8 +443,8 @@ mod tests {
node.initialize_node().unwrap();
let doc =
Document::new(DocumentType::Note, None, node.local_node_pubkey_required().unwrap());
node.with_store(|store| Ok(store.batch(|tx| store.doc_store.add_document(tx, doc))?))
.unwrap();
let store = node.store();
store.batch(|tx| store.doc_store.add_document(tx, doc)).unwrap();
let stray = node.store().stream_cache_dir().join("track.mp3");
std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
std::fs::write(&stray, b"decrypted audio").unwrap();
@@ -469,9 +454,7 @@ mod tests {
assert!(!node.node_initialized().unwrap(), "the node must need setting up again");
assert!(!stray.exists(), "plaintext outside the blob store must go too");
assert!(
node.with_store(|store| Ok(store.batch(|tx| store.doc_store.list_documents(tx))?))
.unwrap()
.is_empty()
node.store().batch(|tx| node.store().doc_store.list_documents(tx)).unwrap().is_empty()
);
}
+7 -8
View File
@@ -100,14 +100,13 @@ impl NotebookFfi {
note_id: String,
) -> Result<DocumentAvailability, SyncError> {
let id = note_id.parse::<DocumentID>()?;
self.core.with_store(|store| {
Ok(crate::documents::artifact_availability(
&store.artifact_store,
&store.node_content_status_store,
&id,
crate::documents::ArtifactKind::NoteBody,
)?)
})
let store = self.core.store();
Ok(crate::documents::artifact_availability(
&store.artifact_store,
&store.node_content_status_store,
&id,
crate::documents::ArtifactKind::NoteBody,
)?)
}
/// Abandon a note body no node has claimed and start a fresh, empty one —
+70 -78
View File
@@ -54,17 +54,17 @@ impl PdfFfi {
/// availability and the line the row shows under its title already
/// decided — the same list the desktop draws, from the same function.
pub fn list(&self) -> Result<Vec<pdf::PdfListItem>, SyncError> {
self.core.with_store(|store| Ok(pdf::build_pdf_nodes(store)?))
let store = self.core.store();
Ok(pdf::build_pdf_nodes(&store)?)
}
pub fn get_reading_progress(&self, document_id: String) -> Result<Option<u32>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = document_id.parse()?;
let artifact = store.artifact_store.batch(|tx| {
store.artifact_store.get_artifact(tx, &doc_id, ArtifactKind::ReadingPosition)
})?;
Ok(artifact.and_then(|a| a.value.try_as_reading_position().map(|s| s.current_page)))
})
let store = self.core.store();
let doc_id: DocumentID = document_id.parse()?;
let artifact = store.artifact_store.batch(|tx| {
store.artifact_store.get_artifact(tx, &doc_id, ArtifactKind::ReadingPosition)
})?;
Ok(artifact.and_then(|a| a.value.try_as_reading_position().map(|s| s.current_page)))
}
pub fn set_reading_progress(
@@ -72,21 +72,20 @@ impl PdfFfi {
document_id: String,
current_page: u32,
) -> Result<(), SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = document_id.parse()?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
let store = self.core.store();
let doc_id: DocumentID = document_id.parse()?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
let artifact = Artifact::new(
doc_id,
ArtifactValue::ReadingPosition(ReadingPosition { current_page }),
node_pubkey,
);
store.artifact_store.batch(|tx| store.artifact_store.upsert_artifact(tx, &artifact))?;
Ok(())
})
let artifact = Artifact::new(
doc_id,
ArtifactValue::ReadingPosition(ReadingPosition { current_page }),
node_pubkey,
);
store.artifact_store.batch(|tx| store.artifact_store.upsert_artifact(tx, &artifact))?;
Ok(())
}
/// Write a PDF document's content to `output_path` as plaintext, from the
@@ -148,29 +147,24 @@ impl PdfFfi {
/// List a PDF's bookmarks, ordered by page.
pub fn list_bookmarks(&self, document_id: String) -> Result<Vec<BookmarkInfo>, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = document_id.parse()?;
let mut bookmarks: Vec<BookmarkInfo> = store
.artifact_store
.batch(|tx| {
store.artifact_store.list_artifacts_of_kind(
tx,
&doc_id,
ArtifactKind::Bookmarks,
)
})?
.into_iter()
.filter_map(|a| {
a.value.try_as_bookmark().map(|b| BookmarkInfo {
id: a.id.to_string(),
page: b.page,
label: b.label.unwrap_or_default(),
})
let store = self.core.store();
let doc_id: DocumentID = document_id.parse()?;
let mut bookmarks: Vec<BookmarkInfo> = store
.artifact_store
.batch(|tx| {
store.artifact_store.list_artifacts_of_kind(tx, &doc_id, ArtifactKind::Bookmarks)
})?
.into_iter()
.filter_map(|a| {
a.value.try_as_bookmark().map(|b| BookmarkInfo {
id: a.id.to_string(),
page: b.page,
label: b.label.unwrap_or_default(),
})
.collect();
bookmarks.sort_by_key(|b| (b.page, b.id.clone()));
Ok(bookmarks)
})
})
.collect();
bookmarks.sort_by_key(|b| (b.page, b.id.clone()));
Ok(bookmarks)
}
/// Add a bookmark at `page` with an optional `label`. Returns the new
@@ -181,21 +175,20 @@ impl PdfFfi {
page: u32,
label: Option<String>,
) -> Result<String, SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = document_id.parse()?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
let artifact = Artifact::new(
doc_id,
ArtifactValue::Bookmark(Bookmark { page, label: label.filter(|l| !l.is_empty()) }),
node_pubkey,
);
let id = artifact.id.to_string();
store.artifact_store.batch(|tx| store.artifact_store.upsert_artifact(tx, &artifact))?;
Ok(id)
})
let store = self.core.store();
let doc_id: DocumentID = document_id.parse()?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
let artifact = Artifact::new(
doc_id,
ArtifactValue::Bookmark(Bookmark { page, label: label.filter(|l| !l.is_empty()) }),
node_pubkey,
);
let id = artifact.id.to_string();
store.artifact_store.batch(|tx| store.artifact_store.upsert_artifact(tx, &artifact))?;
Ok(id)
}
/// Delete a bookmark by its `bookmark_id`, recording a tombstone so the
@@ -205,24 +198,23 @@ impl PdfFfi {
document_id: String,
bookmark_id: String,
) -> Result<(), SyncError> {
self.core.with_store(|store| {
let doc_id: DocumentID = document_id.parse()?;
let bookmark_id = uuid::Uuid::parse_str(&bookmark_id)?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
store.artifact_store.batch(|tx| {
store.artifact_store.tombstone_artifact(
tx,
bookmark_id,
&doc_id,
ArtifactKind::Bookmarks,
Timestamp::now(),
node_pubkey,
)
})?;
Ok(())
})
let store = self.core.store();
let doc_id: DocumentID = document_id.parse()?;
let bookmark_id = uuid::Uuid::parse_str(&bookmark_id)?;
let node_pubkey = store
.settings_store
.local_node_pubkey()?
.ok_or_else(|| SyncError::NotInitialized { msg: "Node not initialized".into() })?;
store.artifact_store.batch(|tx| {
store.artifact_store.tombstone_artifact(
tx,
bookmark_id,
&doc_id,
ArtifactKind::Bookmarks,
Timestamp::now(),
node_pubkey,
)
})?;
Ok(())
}
}
+2 -1
View File
@@ -35,7 +35,8 @@ impl PicturesFfi {
/// [`PictureTreeItem::parent_id`](pictures::PictureTreeItem::parent_id),
/// and one that wants a plain list of pictures keeps the leaves.
pub fn list_tree(&self) -> Result<Vec<pictures::PictureTreeItem>, SyncError> {
self.core.with_store(|store| Ok(pictures::build_picture_nodes(store)?))
let store = self.core.store();
Ok(pictures::build_picture_nodes(&store)?)
}
/// An image's bytes, still encoded — from the local blob store if they are
+125 -144
View File
@@ -31,36 +31,33 @@ impl PodcastFfi {
/// needs moved into the store (ADR 0051) — a call now needs a store to
/// unseal them from, which is what this object already has.
pub fn search(&self, query: String) -> Result<String, SyncError> {
self.core.with_store(|store| {
podcast::search_podcasts(store, &query)
.map_err(|e| SyncError::Offline { msg: e.to_string() })
})
let store = self.core.store();
podcast::search_podcasts(&store, &query)
.map_err(|e| SyncError::Offline { msg: e.to_string() })
}
/// Episodes for one feed, from the Podcast Index. See [`search`](Self::search)
/// on why this is a method.
pub fn fetch_episodes(&self, podcast_id: i64, max: i64) -> Result<String, SyncError> {
self.core.with_store(|store| {
podcast::get_podcast_episodes(store, podcast_id, max)
.map_err(|e| SyncError::Offline { msg: e.to_string() })
})
let store = self.core.store();
podcast::get_podcast_episodes(&store, podcast_id, max)
.map_err(|e| SyncError::Offline { msg: e.to_string() })
}
pub fn list_documents(&self) -> Result<Vec<PodcastItem>, SyncError> {
self.core.with_store(|store| {
Ok(podcast::list_podcast_feeds(store)?
.into_iter()
.map(|feed| PodcastItem {
id: feed.document_id.to_string(),
podcast_api_id: feed.api_id,
title: feed.title,
description: feed.description,
author: feed.author,
cover_art_url: feed.cover_art_url,
custom_speed: feed.custom_speed,
})
.collect())
})
let store = self.core.store();
Ok(podcast::list_podcast_feeds(&store)?
.into_iter()
.map(|feed| PodcastItem {
id: feed.document_id.to_string(),
podcast_api_id: feed.api_id,
title: feed.title,
description: feed.description,
author: feed.author,
cover_art_url: feed.cover_art_url,
custom_speed: feed.custom_speed,
})
.collect())
}
/// Persist the user's preferred playback speed for a subscribed feed, so
@@ -69,9 +66,8 @@ impl PodcastFfi {
pub fn save_custom_speed(&self, document_id: String, speed: f32) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let feed_id: DocumentID = document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast::save_custom_speed(store, origin_node, &feed_id, speed)?)
})
let store = self.core.store();
Ok(podcast::save_custom_speed(&store, origin_node, &feed_id, speed)?)
}
/// Return the persisted episode child documents of a podcast feed, newest first.
@@ -80,21 +76,20 @@ impl PodcastFfi {
feed_document_id: String,
) -> Result<Vec<PodcastEpisodeItem>, SyncError> {
let feed_id: DocumentID = feed_document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast::list_feed_episodes(store, &feed_id)?
.into_iter()
.map(|ep| PodcastEpisodeItem {
id: ep.document_id.to_string(),
api_id: ep.api_id,
title: ep.title,
description: ep.description,
stream_url: ep.stream_url,
image_url: ep.image_url.unwrap_or_default(),
pub_date: ep.published_at.map(|ts| ts.0.to_rfc3339()).unwrap_or_default(),
duration_secs: ep.duration_secs,
})
.collect())
})
let store = self.core.store();
Ok(podcast::list_feed_episodes(&store, &feed_id)?
.into_iter()
.map(|ep| PodcastEpisodeItem {
id: ep.document_id.to_string(),
api_id: ep.api_id,
title: ep.title,
description: ep.description,
stream_url: ep.stream_url,
image_url: ep.image_url.unwrap_or_default(),
pub_date: ep.published_at.map(|ts| ts.0.to_rfc3339()).unwrap_or_default(),
duration_secs: ep.duration_secs,
})
.collect())
}
/// Give one episode a child document under its feed, and return the
@@ -114,10 +109,8 @@ impl PodcastFfi {
let episode = new_episode(episode);
self.core.with_store(|store| {
Ok(podcast::ensure_episode_document(store, origin_node, &feed_id, &episode)?
.to_string())
})
let store = self.core.store();
Ok(podcast::ensure_episode_document(&store, origin_node, &feed_id, &episode)?.to_string())
}
/// The document id `api_id`'s episode would have under this feed, whether
@@ -151,22 +144,21 @@ impl PodcastFfi {
api_ids: Vec<String>,
) -> Result<Vec<PodcastEpisodeStateItem>, SyncError> {
let feed_id: DocumentID = feed_document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast::episode_store_state(store, &feed_id, &api_ids)?
.into_iter()
.map(|state| PodcastEpisodeStateItem {
api_id: state.api_id,
document_id: state.document_id.to_string(),
listen_label: copy::listen_state::label(
state.listen_state.as_ref(),
state.duration_secs as f64,
),
listen_state: state.listen_state.unwrap_or(ListenState::NotStarted),
in_queue: state.in_queue,
saved_locally: state.saved_locally,
})
.collect())
})
let store = self.core.store();
Ok(podcast::episode_store_state(&store, &feed_id, &api_ids)?
.into_iter()
.map(|state| PodcastEpisodeStateItem {
api_id: state.api_id,
document_id: state.document_id.to_string(),
listen_label: copy::listen_state::label(
state.listen_state.as_ref(),
state.duration_secs as f64,
),
listen_state: state.listen_state.unwrap_or(ListenState::NotStarted),
in_queue: state.in_queue,
saved_locally: state.saved_locally,
})
.collect())
}
/// Download an episode's audio and keep it, so it plays with no network.
@@ -192,7 +184,6 @@ impl PodcastFfi {
// which is what lets two presses dedup even on the first save.
let document_id = podcast::episode_document_id(&feed_id, &episode.api_id);
let store = self.core.store();
run_as_job_with_progress(
&self.core.job_runner,
JobKind::Import,
@@ -242,8 +233,9 @@ impl PodcastFfi {
cache_dir: String,
) -> Result<Option<String>, SyncError> {
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| {
let Some(blob) = podcast::local_audio_ref(store, &episode_id) else {
let store = self.core.store();
{
let Some(blob) = podcast::local_audio_ref(&store, &episode_id) else {
return Ok(None);
};
let dir = std::path::Path::new(&cache_dir);
@@ -265,7 +257,7 @@ impl PodcastFfi {
})?;
}
Ok(Some(path.to_string_lossy().into_owned()))
})
}
}
/// Drop this node's downloaded copy of an episode, keeping the episode.
@@ -277,7 +269,8 @@ impl PodcastFfi {
/// [`release_episode_audio`](podcast::release_episode_audio).
pub fn release_episode_audio(&self, episode_document_id: String) -> Result<bool, SyncError> {
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| Ok(podcast::release_episode_audio(store, &episode_id)?))
let store = self.core.store();
Ok(podcast::release_episode_audio(&store, &episode_id)?)
}
/// The cross-series play queue, in the order the user put it.
@@ -286,32 +279,27 @@ impl PodcastFfi {
/// whose episode document has since been deleted is omitted rather than
/// erroring — see [`podcast_queue::list_queue`].
pub fn queue_list(&self) -> Result<Vec<PodcastQueueItem>, SyncError> {
self.core.with_store(|store| {
Ok(podcast_queue::list_queue(store)?
.into_iter()
.map(|row| PodcastQueueItem {
listen_label: copy::listen_state::label(
row.listen_state.as_ref(),
row.episode.duration_secs as f64,
),
episode_document_id: row.episode.document_id.to_string(),
episode_api_id: row.episode.api_id,
title: row.episode.title,
description: row.episode.description,
stream_url: row.episode.stream_url,
image_url: row.episode.image_url.unwrap_or_default(),
pub_date: row
.episode
.published_at
.map(|ts| ts.0.to_rfc3339())
.unwrap_or_default(),
duration_secs: row.episode.duration_secs,
feed_document_id: row.feed_id.to_string(),
feed_title: row.feed_title,
saved_locally: row.saved_locally,
})
.collect())
})
let store = self.core.store();
Ok(podcast_queue::list_queue(&store)?
.into_iter()
.map(|row| PodcastQueueItem {
listen_label: copy::listen_state::label(
row.listen_state.as_ref(),
row.episode.duration_secs as f64,
),
episode_document_id: row.episode.document_id.to_string(),
episode_api_id: row.episode.api_id,
title: row.episode.title,
description: row.episode.description,
stream_url: row.episode.stream_url,
image_url: row.episode.image_url.unwrap_or_default(),
pub_date: row.episode.published_at.map(|ts| ts.0.to_rfc3339()).unwrap_or_default(),
duration_secs: row.episode.duration_secs,
feed_document_id: row.feed_id.to_string(),
feed_title: row.feed_title,
saved_locally: row.saved_locally,
})
.collect())
}
/// Put an episode at the back of the queue.
@@ -323,8 +311,7 @@ impl PodcastFfi {
pub fn queue_add(&self, episode_document_id: String) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core
.with_store(|store| Ok(podcast_queue::add_to_queue(store, origin_node, &episode_id)?))
Ok(podcast_queue::add_to_queue(&self.core.store(), origin_node, &episode_id)?)
}
/// Take an episode back out of the queue, leaving a tombstone so the
@@ -333,9 +320,8 @@ impl PodcastFfi {
pub fn queue_remove(&self, episode_document_id: String) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast_queue::remove_from_queue(store, origin_node, &episode_id)?)
})
let store = self.core.store();
Ok(podcast_queue::remove_from_queue(&store, origin_node, &episode_id)?)
}
/// Move an episode one slot toward the front of the queue. A no-op if it
@@ -343,14 +329,16 @@ impl PodcastFfi {
pub fn queue_move_up(&self, episode_document_id: String) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| Ok(podcast_queue::move_up(store, origin_node, &episode_id)?))
let store = self.core.store();
Ok(podcast_queue::move_up(&store, origin_node, &episode_id)?)
}
/// [`queue_move_up`](Self::queue_move_up), toward the back.
pub fn queue_move_down(&self, episode_document_id: String) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| Ok(podcast_queue::move_down(store, origin_node, &episode_id)?))
let store = self.core.store();
Ok(podcast_queue::move_down(&store, origin_node, &episode_id)?)
}
/// `episode_document_id`'s playback state — [`ListenState::NotStarted`]
@@ -364,8 +352,7 @@ impl PodcastFfi {
/// doesn't".
pub fn listen_state(&self, episode_document_id: String) -> Result<ListenState, SyncError> {
let episode_id: DocumentID = episode_document_id.parse()?;
self.core
.with_store(|store| Ok(podcast::load_listen_state(&store.artifact_store, &episode_id)))
Ok(podcast::load_listen_state(&self.core.store().artifact_store, &episode_id))
}
/// Record how far into `episode_document_id` the listener has got.
@@ -382,14 +369,13 @@ impl PodcastFfi {
) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast::save_listen_progress(
&store.artifact_store,
&episode_id,
position_secs,
origin_node,
)?)
})
let store = self.core.store();
Ok(podcast::save_listen_progress(
&store.artifact_store,
&episode_id,
position_secs,
origin_node,
)?)
}
/// Mark `episode_document_id` finished — the episode played to its end.
@@ -401,9 +387,8 @@ impl PodcastFfi {
pub fn save_listen_finished(&self, episode_document_id: String) -> Result<(), SyncError> {
let origin_node = self.core.local_node_pubkey_required()?;
let episode_id: DocumentID = episode_document_id.parse()?;
self.core.with_store(|store| {
Ok(podcast::save_listen_finished(&store.artifact_store, &episode_id, origin_node)?)
})
let store = self.core.store();
Ok(podcast::save_listen_finished(&store.artifact_store, &episode_id, origin_node)?)
}
pub fn subscribe(
@@ -424,15 +409,15 @@ impl PodcastFfi {
cover_art_url: cover_art_uri,
last_fetched_at: parse_rfc3339(&last_updated),
};
self.core.with_store(|store| Ok(podcast::subscribe(store, origin_node, &feed)?.to_string()))
let store = self.core.store();
Ok(podcast::subscribe(&store, origin_node, &feed)?.to_string())
}
pub fn unsubscribe(&self, document_id: String) -> Result<(), SyncError> {
let id: DocumentID = document_id.parse()?;
self.core.with_store(|store| {
store.batch(|tx| store.doc_store.remove_document(tx, &id))?;
Ok(())
})
let store = self.core.store();
store.batch(|tx| store.doc_store.remove_document(tx, &id))?;
Ok(())
}
pub fn store_cover_art(
@@ -442,43 +427,39 @@ impl PodcastFfi {
) -> Result<(), SyncError> {
let id: DocumentID = document_id.parse()?;
let stored = self.core.with_store(|store| {
Ok(store.blob_store.store(&image_bytes, crate::vault::DEFAULT_VAULT_ID)?)
})?;
let store = self.core.store();
let stored = store.blob_store.store(&image_bytes, crate::vault::DEFAULT_VAULT_ID)?;
let local_node = self.core.local_node_pubkey_required()?;
self.core.with_store(|store| {
store.artifact_store.batch(|tx| {
store.artifact_store.upsert_artifact(
tx,
&Artifact::new(
id.clone(),
ArtifactValue::Thumbnail(BlobRef::new(
stored.stored_hash.clone(),
stored.plaintext_hash.clone(),
crate::vault::DEFAULT_VAULT_ID,
image_bytes.len() as u64,
)),
local_node,
),
)
})?;
Ok(())
})
store.artifact_store.batch(|tx| {
store.artifact_store.upsert_artifact(
tx,
&Artifact::new(
id.clone(),
ArtifactValue::Thumbnail(BlobRef::new(
stored.stored_hash.clone(),
stored.plaintext_hash.clone(),
crate::vault::DEFAULT_VAULT_ID,
image_bytes.len() as u64,
)),
local_node,
),
)
})?;
Ok(())
}
pub fn get_cover_art_bytes(&self, document_id: String) -> Result<Option<Vec<u8>>, SyncError> {
let blob_ref = self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
Ok(store
.artifact_store
.batch(|tx| store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::Thumbnail))?)
})?;
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
let blob_ref = store
.artifact_store
.batch(|tx| store.artifact_store.get_blob_ref(tx, &id, ArtifactKind::Thumbnail))?;
match blob_ref {
None => Ok(None),
Some(r) => {
let store = self.core.store();
match store.blob_store.load(&r.blob_hash, &r.plaintext_hash, r.vault_id) {
Ok(bytes) => Ok(Some(bytes)),
// A referenced-but-absent thumbnail is normal (e.g. not yet
+102 -127
View File
@@ -28,62 +28,56 @@ pub struct SettingsFfi {
#[uniffi::export]
impl SettingsFfi {
pub fn get_theme_mode(&self) -> Result<ThemeMode, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.theme_mode)
.unwrap_or_default())
})
let store = self.core.store();
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.theme_mode)
.unwrap_or_default())
}
pub fn set_theme_mode(&self, theme_mode: ThemeMode) -> Result<(), SyncError> {
self.core.with_store(|store| {
// Via the transactional setter — a hand-rolled load-modify-save
// here could clobber concurrent writes to other settings fields.
store.settings_store.batch(|tx| store.settings_store.set_theme_mode(tx, theme_mode))?;
Ok(())
})
let store = self.core.store();
// Via the transactional setter — a hand-rolled load-modify-save
// here could clobber concurrent writes to other settings fields.
store.settings_store.batch(|tx| store.settings_store.set_theme_mode(tx, theme_mode))?;
Ok(())
}
/// The typeface note body copy renders in (ADR 0024). Only the prose face
/// is selectable; the UI and monospace faces are fixed.
pub fn get_prose_font(&self) -> Result<ProseFont, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.prose_font)
.unwrap_or_default())
})
let store = self.core.store();
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.prose_font)
.unwrap_or_default())
}
pub fn set_prose_font(&self, prose_font: ProseFont) -> Result<(), SyncError> {
self.core.with_store(|store| {
store.settings_store.batch(|tx| store.settings_store.set_prose_font(tx, prose_font))?;
Ok(())
})
let store = self.core.store();
store.settings_store.batch(|tx| store.settings_store.set_prose_font(tx, prose_font))?;
Ok(())
}
/// The ground documents are read on — paper, white, or dark — independent
/// of the app's chrome theme (ADR 0032 §5).
pub fn get_reading_surface(&self) -> Result<ReadingSurface, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.reading_surface)
.unwrap_or_default())
})
let store = self.core.store();
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.map(|s| s.reading_surface)
.unwrap_or_default())
}
pub fn set_reading_surface(&self, reading_surface: ReadingSurface) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_reading_surface(tx, reading_surface))?;
Ok(())
})
let store = self.core.store();
store
.settings_store
.batch(|tx| store.settings_store.set_reading_surface(tx, reading_surface))?;
Ok(())
}
/// This node's background sync scheduler settings (master on/off,
@@ -93,18 +87,16 @@ impl SettingsFfi {
/// `rust/gui-app/src/scheduler_driver.rs`'s periodic timer) the same way
/// desktop's "Background sync" settings group does.
pub fn get_scheduler_settings(&self) -> Result<SchedulerSettings, SyncError> {
self.core.with_store(|store| {
Ok(store.settings_store.batch(|tx| store.settings_store.scheduler_settings(tx))?)
})
let store = self.core.store();
Ok(store.settings_store.batch(|tx| store.settings_store.scheduler_settings(tx))?)
}
pub fn set_scheduler_settings(&self, settings: SchedulerSettings) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_scheduler_settings(tx, settings))?;
Ok(())
})
let store = self.core.store();
store
.settings_store
.batch(|tx| store.settings_store.set_scheduler_settings(tx, settings))?;
Ok(())
}
/// Run one full scheduler tick (catalog, catalog-fetch, and content
@@ -157,21 +149,20 @@ impl SettingsFfi {
/// policy change (a change instantly moves both the deficit and the
/// reclaimable figure), not per row.
pub fn get_sync_policies(&self) -> Result<Vec<DocumentSyncPolicy>, SyncError> {
self.core.with_store(|store| {
let ledger = content_ledger(store)?;
Ok(store
.settings_store
.batch(|tx| store.settings_store.sync_policies(tx))?
.into_iter()
.filter(|(doc_type, _)| doc_type.has_blob_content())
.map(|(doc_type, policy)| DocumentSyncPolicy {
doc_type,
display_name: doc_type.display_name().to_string(),
policy,
content: ContentRow::new(ledger.for_type(doc_type)),
})
.collect())
})
let store = self.core.store();
let ledger = content_ledger(&store)?;
Ok(store
.settings_store
.batch(|tx| store.settings_store.sync_policies(tx))?
.into_iter()
.filter(|(doc_type, _)| doc_type.has_blob_content())
.map(|(doc_type, policy)| DocumentSyncPolicy {
doc_type,
display_name: doc_type.display_name().to_string(),
policy,
content: ContentRow::new(ledger.for_type(doc_type)),
})
.collect())
}
/// Persist this node's sync policy for one document type.
@@ -180,12 +171,11 @@ impl SettingsFfi {
doc_type: DocumentType,
policy: SyncPolicy,
) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_sync_policy(tx, doc_type, policy))?;
Ok(())
})
let store = self.core.store();
store
.settings_store
.batch(|tx| store.settings_store.set_sync_policy(tx, doc_type, policy))?;
Ok(())
}
/// This node's Pin/Exclude override for `document_id`, if any explicitly
@@ -195,12 +185,11 @@ impl SettingsFfi {
&self,
document_id: String,
) -> Result<Option<DocumentSyncOverride>, SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
Ok(store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.get(tx, &id))?)
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
Ok(store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.get(tx, &id))?)
}
/// Set this node's override for `document_id`, replacing any existing
@@ -210,52 +199,49 @@ impl SettingsFfi {
document_id: String,
value: DocumentSyncOverride,
) -> Result<(), SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.set(tx, &id, value))?;
Ok(())
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.set(tx, &id, value))?;
Ok(())
}
/// Clear this node's override for `document_id` — the document reverts
/// to following its type's sync policy ("Follow policy" in the picker).
pub fn clear_document_sync_override(&self, document_id: String) -> Result<(), SyncError> {
self.core.with_store(|store| {
let id = document_id.parse::<DocumentID>()?;
store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.clear(tx, &id))?;
Ok(())
})
let store = self.core.store();
let id = document_id.parse::<DocumentID>()?;
store
.document_sync_override_store
.batch(|tx| store.document_sync_override_store.clear(tx, &id))?;
Ok(())
}
pub fn get_public_key_hex(&self) -> Result<String, SyncError> {
self.core.with_store(|store| match store.settings_store.load_keypair()? {
let store = self.core.store();
match store.settings_store.load_keypair()? {
Some(keypair) => Ok(keypair.public_key_hex()),
None => Err(SyncError::NotInitialized {
msg: "Node not initialized — no keypair found".into(),
}),
})
}
}
pub fn get_node_name(&self) -> Result<Option<String>, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.and_then(|s| s.node_name))
})
let store = self.core.store();
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.and_then(|s| s.node_name))
}
pub fn get_timezone(&self) -> Result<Option<String>, SyncError> {
self.core.with_store(|store| {
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.and_then(|s| s.timezone.map(|tz| tz.to_string())))
})
let store = self.core.store();
Ok(store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.and_then(|s| s.timezone.map(|tz| tz.to_string())))
}
pub fn set_timezone(&self, tz: Option<String>) -> Result<(), SyncError> {
@@ -268,20 +254,14 @@ impl SettingsFfi {
),
})?),
};
self.core.with_store(|store| {
store.settings_store.batch(|tx| store.settings_store.set_timezone(tx, timezone))?;
Ok(())
})?;
let store = self.core.store();
store.settings_store.batch(|tx| store.settings_store.set_timezone(tx, timezone))?;
Ok(())
}
pub fn set_node_name(&self, name: Option<String>) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_node_name(tx, name.clone()))?;
Ok(())
})?;
let store = self.core.store();
store.settings_store.batch(|tx| store.settings_store.set_node_name(tx, name.clone()))?;
// If the P2P node is running, re-announce immediately so gossip peers learn the new name.
if let Some(p2p) = self.core.p2p.get()
@@ -294,16 +274,12 @@ impl SettingsFfi {
}
pub fn get_log_config(&self) -> Result<LogConfig, SyncError> {
self.core.with_store(|store| {
let settings = store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.unwrap_or_default();
Ok(LogConfig {
verbosity: settings.log_verbosity,
show_iroh_logs: settings.show_iroh_logs,
})
})
let store = self.core.store();
let settings = store
.settings_store
.batch(|tx| store.settings_store.load_settings(tx))?
.unwrap_or_default();
Ok(LogConfig { verbosity: settings.log_verbosity, show_iroh_logs: settings.show_iroh_logs })
}
pub fn set_log_config(
@@ -311,11 +287,10 @@ impl SettingsFfi {
verbosity: LogVerbosity,
show_iroh_logs: bool,
) -> Result<(), SyncError> {
self.core.with_store(|store| {
store
.settings_store
.batch(|tx| store.settings_store.set_log_config(tx, verbosity, show_iroh_logs))?;
Ok(())
})
let store = self.core.store();
store
.settings_store
.batch(|tx| store.settings_store.set_log_config(tx, verbosity, show_iroh_logs))?;
Ok(())
}
}