Skip to content

Commit 294c8c8

Browse files
authored
perf(desktop): move observer-feed archive and decrypt commands off main thread (#3415)
Opening the agent observer feed could beachball the app. In Tauri 2, a sync (`pub fn`) command body runs on the **main thread** — only `async fn` commands run on the runtime pool. Five commands on the observer-feed open path were sync, so panel open ran SQLite I/O and secp256k1 work on the macOS main thread: | Command | Main-thread work | |---|---| | `decrypt_observer_event` | Schnorr ID + signature verify, then NIP-44 decrypt — once per frame | | `read_archived_observer_events_for_channel` | Opens the archive DB, runs the channel-index JOIN, returns up to 200 raw JSON blobs per page | | `read_unindexed_observer_rows` | Opens the DB, returns **all** not-yet-indexed kind-24200 rows in one shot | | `index_observer_channel_id` | Opens the DB, loops N upserts | | `delete_save_subscription` | Opens the DB, one delete | Eager hydration loads up to 10 pages × 200 frames on panel open, so that's up to 10 main-thread DB reads plus up to 2,000 sequential verify+decrypt calls before any scrolling. The one-shot backfill makes it worse on the first open after history accumulates: one read of every unindexed row, a decrypt per row, then a batch upsert — all on the main thread, and all proportional to archive size. The four archive commands now route their DB work through the existing `run_archive_db_task` helper (`spawn_blocking` + `open_db`), matching `list_save_subscriptions`, `read_archived_events`, and `archive_events` directly around them. `decrypt_observer_event` becomes `async fn` + `tauri::async_runtime::spawn_blocking`, with `state.signing_keys()` extracted before the spawn since `State` is not `Send` — the same pattern `sign_event` uses from #1222. No frontend changes: `invoke` is already promise-based, so the TS wrappers in `tauriArchive.ts` and `tauriObserver.ts` are unchanged. This removes the freeze, not the work. Eager hydration still takes the same wall time — the feed shows a loading state instead of blocking the UI. Batching the per-frame decrypt IPC (2,000 round-trips into one command) would cut the latency itself; that's deliberately out of scope here. Signed-off-by: Will Pfleger <[email protected]>
1 parent f7a3988 commit 294c8c8

2 files changed

Lines changed: 69 additions & 55 deletions

File tree

‎desktop/src-tauri/src/archive/mod.rs‎

Lines changed: 52 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -483,21 +483,23 @@ pub async fn list_save_subscriptions(
483483
/// Does NOT purge already-archived event data — retention is decoupled in v1.
484484
/// GC of orphaned event rows happens in P4 purge commands, not here.
485485
#[tauri::command]
486-
pub fn delete_save_subscription(
486+
pub async fn delete_save_subscription(
487487
state: State<'_, AppState>,
488488
scope_type: ScopeType,
489489
scope_value: String,
490490
) -> Result<bool, String> {
491491
let identity_pk = identity_pubkey(&state)?;
492492
let relay_url = relay_ws_url_with_override(&state);
493-
let conn = open_db()?;
494-
store::delete_save_subscription(
495-
&conn,
496-
&identity_pk,
497-
&relay_url,
498-
scope_type.as_str(),
499-
&scope_value,
500-
)
493+
run_archive_db_task(move |conn| {
494+
store::delete_save_subscription(
495+
conn,
496+
&identity_pk,
497+
&relay_url,
498+
scope_type.as_str(),
499+
&scope_value,
500+
)
501+
})
502+
.await
501503
}
502504

503505
// ── read_archived_events ─────────────────────────────────────────────────────
@@ -516,7 +518,7 @@ pub fn delete_save_subscription(
516518
/// newest-first order. Compound cursor `(before_created_at, before_id)` works
517519
/// identically to `read_archived_events`.
518520
#[tauri::command]
519-
pub fn read_archived_observer_events_for_channel(
521+
pub async fn read_archived_observer_events_for_channel(
520522
state: State<'_, AppState>,
521523
channel_id: String,
522524
before_created_at: Option<i64>,
@@ -525,16 +527,18 @@ pub fn read_archived_observer_events_for_channel(
525527
) -> Result<Vec<String>, String> {
526528
let identity_pk = identity_pubkey(&state)?;
527529
let relay_url = relay_ws_url_with_override(&state);
528-
let conn = open_db()?;
529-
store::read_archived_observer_events_for_channel(
530-
&conn,
531-
&identity_pk,
532-
&relay_url,
533-
&channel_id,
534-
before_created_at,
535-
before_id.as_deref(),
536-
limit.unwrap_or(DEFAULT_READ_LIMIT),
537-
)
530+
run_archive_db_task(move |conn| {
531+
store::read_archived_observer_events_for_channel(
532+
conn,
533+
&identity_pk,
534+
&relay_url,
535+
&channel_id,
536+
before_created_at,
537+
before_id.as_deref(),
538+
limit.unwrap_or(DEFAULT_READ_LIMIT),
539+
)
540+
})
541+
.await
538542
}
539543

540544
// ── index_observer_channel_id ─────────────────────────────────────────────────
@@ -548,24 +552,26 @@ pub fn read_archived_observer_events_for_channel(
548552
///
549553
/// Idempotent: rows that are already indexed are left unchanged.
550554
#[tauri::command]
551-
pub fn index_observer_channel_id(
555+
pub async fn index_observer_channel_id(
552556
state: State<'_, AppState>,
553557
entries: Vec<ObserverChannelIndexEntry>,
554558
) -> Result<(), String> {
555559
let identity_pk = identity_pubkey(&state)?;
556560
let relay_url = relay_ws_url_with_override(&state);
557-
let conn = open_db()?;
558-
for entry in &entries {
559-
store::upsert_observer_channel_index(
560-
&conn,
561-
&identity_pk,
562-
&relay_url,
563-
&entry.event_id,
564-
entry.channel_id.as_deref(),
565-
entry.created_at,
566-
)?;
567-
}
568-
Ok(())
561+
run_archive_db_task(move |conn| {
562+
for entry in &entries {
563+
store::upsert_observer_channel_index(
564+
conn,
565+
&identity_pk,
566+
&relay_url,
567+
&entry.event_id,
568+
entry.channel_id.as_deref(),
569+
entry.created_at,
570+
)?;
571+
}
572+
Ok(())
573+
})
574+
.await
569575
}
570576

571577
/// A single (event_id, channel_id?, created_at) record used by
@@ -591,21 +597,23 @@ pub struct ObserverChannelIndexEntry {
591597
/// Together these constitute the one-shot idempotent backfill required by the
592598
/// Slice 1 acceptance criteria (Thufir Pass 4).
593599
#[tauri::command]
594-
pub fn read_unindexed_observer_rows(
600+
pub async fn read_unindexed_observer_rows(
595601
state: State<'_, AppState>,
596602
) -> Result<Vec<RawObserverRow>, String> {
597603
let identity_pk = identity_pubkey(&state)?;
598604
let relay_url = relay_ws_url_with_override(&state);
599-
let conn = open_db()?;
600-
let rows = store::read_unindexed_observer_rows(&conn, &identity_pk, &relay_url)?;
601-
Ok(rows
602-
.into_iter()
603-
.map(|(id, raw_json, created_at)| RawObserverRow {
604-
id,
605-
raw_json,
606-
created_at,
607-
})
608-
.collect())
605+
run_archive_db_task(move |conn| {
606+
let rows = store::read_unindexed_observer_rows(conn, &identity_pk, &relay_url)?;
607+
Ok(rows
608+
.into_iter()
609+
.map(|(id, raw_json, created_at)| RawObserverRow {
610+
id,
611+
raw_json,
612+
created_at,
613+
})
614+
.collect())
615+
})
616+
.await
609617
}
610618

611619
/// Wire type returned by `read_unindexed_observer_rows`.

‎desktop/src-tauri/src/commands/identity.rs‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -135,23 +135,29 @@ pub async fn sign_event(
135135
}
136136

137137
#[tauri::command]
138-
pub fn decrypt_observer_event(
138+
pub async fn decrypt_observer_event(
139139
event_json: String,
140140
state: State<'_, AppState>,
141141
) -> Result<serde_json::Value, String> {
142142
let keys = state.signing_keys()?;
143-
let event = Event::from_json(event_json).map_err(|error| format!("invalid event: {error}"))?;
144143

145-
// Defense-in-depth: verify event ID and signature before decrypting.
146-
if !event.verify_id() {
147-
return Err("observer event has invalid ID".into());
148-
}
149-
if !event.verify_signature() {
150-
return Err("observer event has invalid signature".into());
151-
}
144+
tauri::async_runtime::spawn_blocking(move || {
145+
let event =
146+
Event::from_json(event_json).map_err(|error| format!("invalid event: {error}"))?;
152147

153-
buzz_core_pkg::observer::decrypt_observer_payload(&keys, &event)
154-
.map_err(|error| format!("decrypt observer event failed: {error}"))
148+
// Defense-in-depth: verify event ID and signature before decrypting.
149+
if !event.verify_id() {
150+
return Err("observer event has invalid ID".into());
151+
}
152+
if !event.verify_signature() {
153+
return Err("observer event has invalid signature".into());
154+
}
155+
156+
buzz_core_pkg::observer::decrypt_observer_payload(&keys, &event)
157+
.map_err(|error| format!("decrypt observer event failed: {error}"))
158+
})
159+
.await
160+
.map_err(|e| format!("spawn_blocking failed: {e}"))?
155161
}
156162

157163
#[tauri::command]

0 commit comments

Comments
 (0)