Skip to content

Commit a1af8ac

Browse files
tellahoCarl
authored andcommitted
fix(pairing): linearize recovery commit invalidation
Co-authored-by: Taylor Ho <[email protected]> Signed-off-by: Taylor Ho <[email protected]>
1 parent bd23abe commit a1af8ac

1 file changed

Lines changed: 63 additions & 26 deletions

File tree

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

Lines changed: 63 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,16 @@ enum PairingMode {
4343
struct PairingTaskContext {
4444
mode: PairingMode,
4545
generation: Arc<AtomicU64>,
46+
generation_fence: Arc<std::sync::Mutex<()>>,
4647
task_generation: u64,
4748
}
4849

4950
/// Managed Tauri state for an active pairing session.
5051
pub struct PairingHandle {
5152
session: Arc<tokio::sync::Mutex<Option<PairingSession>>>,
5253
generation: Arc<AtomicU64>,
54+
/// Linearizes cancellation/replacement against recovered identity commits.
55+
generation_fence: Arc<std::sync::Mutex<()>>,
5356
/// Serializes session setup so an older start cannot resume after relay
5457
/// discovery and overwrite a newer session's shared state.
5558
start_lock: tokio::sync::Mutex<()>,
@@ -67,6 +70,7 @@ impl PairingHandle {
6770
Self {
6871
session: Arc::new(tokio::sync::Mutex::new(None)),
6972
generation: Arc::new(AtomicU64::new(0)),
73+
generation_fence: Arc::new(std::sync::Mutex::new(())),
7074
start_lock: tokio::sync::Mutex::new(()),
7175
cancel: std::sync::Mutex::new(None),
7276
outbound_tx: std::sync::Mutex::new(None),
@@ -110,10 +114,8 @@ async fn start_pairing_session(
110114
mode: PairingMode,
111115
) -> Result<String, String> {
112116
let _start_guard = pairing.start_lock.lock().await;
113-
let task_generation = pairing
114-
.generation
115-
.fetch_add(1, Ordering::SeqCst)
116-
.wrapping_add(1);
117+
let task_generation =
118+
invalidate_pairing_generation(&pairing.generation, &pairing.generation_fence)?;
117119
if let Some(token) = pairing.cancel.lock().map_err(|e| e.to_string())?.take() {
118120
token.cancel();
119121
}
@@ -165,6 +167,7 @@ async fn start_pairing_session(
165167
PairingTaskContext {
166168
mode,
167169
generation: Arc::clone(&pairing.generation),
170+
generation_fence: Arc::clone(&pairing.generation_fence),
168171
task_generation,
169172
},
170173
cancel,
@@ -228,7 +231,7 @@ pub async fn cancel_pairing(pairing: State<'_, PairingHandle>) -> Result<(), Str
228231
// Invalidate the task before waiting for its session lock. Recovery may be
229232
// blocked on identity persistence after releasing this lock, and must see
230233
// cancellation before crossing the durable commit boundary.
231-
pairing.generation.fetch_add(1, Ordering::SeqCst);
234+
invalidate_pairing_generation(&pairing.generation, &pairing.generation_fence)?;
232235
if let Some(token) = pairing.cancel.lock().map_err(|e| e.to_string())?.take() {
233236
token.cancel();
234237
}
@@ -405,6 +408,7 @@ async fn pairing_ws_task_inner(
405408
app,
406409
payload,
407410
&context.generation,
411+
&context.generation_fence,
408412
context.task_generation,
409413
)
410414
.await;
@@ -459,16 +463,18 @@ async fn import_recovered_identity(
459463
app: &AppHandle,
460464
nsec: Zeroizing<String>,
461465
generation: &Arc<AtomicU64>,
466+
generation_fence: &Arc<std::sync::Mutex<()>>,
462467
task_generation: u64,
463468
) -> Result<(), String> {
464469
let app = app.clone();
465470
let generation = Arc::clone(generation);
471+
let generation_fence = Arc::clone(generation_fence);
466472
tokio::task::spawn_blocking(move || {
467473
let keys = nostr::Keys::parse(nsec.trim())
468474
.map_err(|e| format!("Phone sent an invalid identity: {e}"))?;
469475
let state = app.state::<AppState>();
470476
let _mutation_guard = state.identity_mutation.lock().map_err(|e| e.to_string())?;
471-
commit_recovery_if_current(&generation, task_generation, || {
477+
commit_recovery_if_current(&generation, &generation_fence, task_generation, || {
472478
let data_dir = app
473479
.path()
474480
.app_data_dir()
@@ -498,11 +504,21 @@ fn ensure_pairing_task_is_current(
498504
}
499505
}
500506

507+
fn invalidate_pairing_generation(
508+
generation: &AtomicU64,
509+
generation_fence: &std::sync::Mutex<()>,
510+
) -> Result<u64, String> {
511+
let _fence = generation_fence.lock().map_err(|e| e.to_string())?;
512+
Ok(generation.fetch_add(1, Ordering::SeqCst).wrapping_add(1))
513+
}
514+
501515
fn commit_recovery_if_current<T>(
502516
generation: &AtomicU64,
517+
generation_fence: &std::sync::Mutex<()>,
503518
task_generation: u64,
504519
commit: impl FnOnce() -> Result<T, String>,
505520
) -> Result<T, String> {
521+
let _fence = generation_fence.lock().map_err(|e| e.to_string())?;
506522
ensure_pairing_task_is_current(generation, task_generation)?;
507523
commit()
508524
}
@@ -776,8 +792,8 @@ mod pairing_generation_tests {
776792

777793
use super::{
778794
clear_pairing_session_if_current, commit_recovery_if_current,
779-
recovery_result_after_completion, validate_recovery_payload_type, PairingHandle,
780-
PairingSession, PayloadType,
795+
invalidate_pairing_generation, recovery_result_after_completion,
796+
validate_recovery_payload_type, PairingHandle, PairingSession, PayloadType,
781797
};
782798

783799
#[tokio::test]
@@ -811,7 +827,8 @@ mod pairing_generation_tests {
811827
let generation = AtomicU64::new(2);
812828
let committed = std::sync::atomic::AtomicBool::new(false);
813829

814-
let result = commit_recovery_if_current(&generation, 1, || {
830+
let generation_fence = std::sync::Mutex::new(());
831+
let result = commit_recovery_if_current(&generation, &generation_fence, 1, || {
815832
committed.store(true, Ordering::SeqCst);
816833
Ok(())
817834
});
@@ -824,28 +841,48 @@ mod pairing_generation_tests {
824841
}
825842

826843
#[test]
827-
fn cancelled_recovery_waiting_for_mutation_cannot_commit_identity() {
844+
fn invalidation_after_check_waits_for_identity_commit() {
828845
let generation = Arc::new(AtomicU64::new(7));
829-
let mutation = Arc::new(std::sync::Mutex::new(()));
830-
let blocker = mutation.lock().expect("lock identity mutation");
831-
let (started_tx, started_rx) = std::sync::mpsc::channel();
832-
let task_generation = 7;
833-
let task_mutation = Arc::clone(&mutation);
834-
let task_generation_state = Arc::clone(&generation);
846+
let generation_fence = Arc::new(std::sync::Mutex::new(()));
847+
let (checked_tx, checked_rx) = std::sync::mpsc::channel();
848+
let (finish_tx, finish_rx) = std::sync::mpsc::channel();
849+
let committed = Arc::new(std::sync::atomic::AtomicBool::new(false));
850+
851+
let recovery_generation = Arc::clone(&generation);
852+
let recovery_fence = Arc::clone(&generation_fence);
853+
let recovery_committed = Arc::clone(&committed);
835854
let recovery = std::thread::spawn(move || {
836-
started_tx.send(()).expect("signal recovery started");
837-
let _guard = task_mutation.lock().expect("wait for identity mutation");
838-
commit_recovery_if_current(&task_generation_state, task_generation, || Ok(()))
855+
commit_recovery_if_current(&recovery_generation, &recovery_fence, 7, || {
856+
checked_tx.send(()).expect("signal generation checked");
857+
finish_rx.recv().expect("release identity commit");
858+
recovery_committed.store(true, Ordering::SeqCst);
859+
Ok(())
860+
})
839861
});
840862

841-
started_rx.recv().expect("recovery started");
842-
generation.fetch_add(1, Ordering::SeqCst);
843-
drop(blocker);
863+
checked_rx.recv().expect("generation checked");
864+
let invalidation_generation = Arc::clone(&generation);
865+
let invalidation_fence = Arc::clone(&generation_fence);
866+
let (attempted_tx, attempted_rx) = std::sync::mpsc::channel();
867+
let (invalidated_tx, invalidated_rx) = std::sync::mpsc::channel();
868+
let invalidation = std::thread::spawn(move || {
869+
attempted_tx.send(()).expect("signal invalidation attempt");
870+
let next = invalidate_pairing_generation(&invalidation_generation, &invalidation_fence)
871+
.expect("invalidate generation");
872+
invalidated_tx.send(next).expect("signal invalidated");
873+
});
844874

845-
assert_eq!(
846-
recovery.join().expect("recovery task").unwrap_err(),
847-
"Pairing session was superseded or cancelled"
848-
);
875+
attempted_rx.recv().expect("invalidation attempted");
876+
assert!(invalidated_rx
877+
.recv_timeout(Duration::from_millis(50))
878+
.is_err());
879+
assert!(!committed.load(Ordering::SeqCst));
880+
881+
finish_tx.send(()).expect("finish identity commit");
882+
recovery.join().expect("recovery task").unwrap();
883+
assert!(committed.load(Ordering::SeqCst));
884+
assert_eq!(invalidated_rx.recv().expect("invalidation completed"), 8);
885+
invalidation.join().expect("invalidation task");
849886
}
850887

851888
#[test]

0 commit comments

Comments
 (0)