app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

profile_refresh.rs (27500B)


      1 use harvestcircle_domain::{PublicKey, SafeError, SafeErrorCode};
      2 use radroots_transport_nostr::RelayEndpoint;
      3 use std::time::Instant;
      4 
      5 use crate::{
      6     ActiveIdentitySnapshot, AppCore, AppSnapshot, CachedProfile, Clock, NostrClient,
      7     ProfileFetchResult, ProfileLoadState, ProfileRefreshStatus, ProfileRepository,
      8     RelayConnectionState, RelayFetchCompleteness, SnapshotRevision, StateTransition,
      9 };
     10 
     11 #[derive(Clone, Debug, Eq, PartialEq)]
     12 pub struct ProfileRefreshPlan {
     13     public_key: PublicKey,
     14     active_identity: ActiveIdentitySnapshot,
     15     relays: Vec<RelayEndpoint>,
     16     expected_revision: SnapshotRevision,
     17 }
     18 
     19 impl ProfileRefreshPlan {
     20     #[must_use]
     21     pub const fn public_key(&self) -> PublicKey {
     22         self.public_key
     23     }
     24 
     25     #[must_use]
     26     pub const fn active_identity(&self) -> &ActiveIdentitySnapshot {
     27         &self.active_identity
     28     }
     29 
     30     #[must_use]
     31     pub fn relays(&self) -> &[RelayEndpoint] {
     32         &self.relays
     33     }
     34 
     35     #[must_use]
     36     pub const fn expected_revision(&self) -> SnapshotRevision {
     37         self.expected_revision
     38     }
     39 }
     40 
     41 impl AppCore {
     42     /// Manually refreshes the active identity's Nostr kind-0 profile.
     43     ///
     44     /// Cached public metadata remains visible while the asynchronous request is
     45     /// running. Calling this command while signed out is an idempotent no-op.
     46     ///
     47     /// # Errors
     48     ///
     49     /// Returns a safe storage or application-state error. Relay and invalid-data
     50     /// failures are represented as nonfatal snapshot state.
     51     pub async fn refresh_active_profile(
     52         &self,
     53         profiles: &(impl ProfileRepository + ?Sized),
     54         client: &(impl NostrClient + ?Sized),
     55         clock: &(impl Clock + ?Sized),
     56         deadline: Instant,
     57     ) -> Result<AppSnapshot, SafeError> {
     58         self.refresh_profile_for_active_identity(profiles, client, clock, deadline)
     59             .await
     60     }
     61 
     62     /// Refreshes the current active identity while retaining any cached profile.
     63     ///
     64     /// Stale results are discarded when the identity is replaced or signed out.
     65     ///
     66     /// # Errors
     67     ///
     68     /// Returns a safe storage or application-state error. Relay and invalid-data
     69     /// failures are represented as nonfatal snapshot state.
     70     async fn refresh_profile_for_active_identity(
     71         &self,
     72         profiles: &(impl ProfileRepository + ?Sized),
     73         client: &(impl NostrClient + ?Sized),
     74         clock: &(impl Clock + ?Sized),
     75         deadline: Instant,
     76     ) -> Result<AppSnapshot, SafeError> {
     77         let Some(plan) = self.begin_profile_refresh()? else {
     78             return Ok(self.snapshot());
     79         };
     80         let result = client
     81             .fetch_profile(plan.public_key(), plan.relays(), deadline)
     82             .await;
     83         self.complete_profile_refresh(&plan, result, profiles, clock)
     84             .await
     85     }
     86 
     87     /// Begins a refresh on the actor and returns the immutable network plan.
     88     ///
     89     /// # Errors
     90     ///
     91     /// Returns a safe state error when the loading transition is invalid.
     92     pub fn begin_profile_refresh(&self) -> Result<Option<ProfileRefreshPlan>, SafeError> {
     93         let Some(active) = self.snapshot().active_identity().cloned() else {
     94             return Ok(None);
     95         };
     96         let public_key = active.identity().public_key();
     97         let loading = self.apply_transition(StateTransition::UpdateActiveIdentity {
     98             expected: public_key,
     99             active_identity: Box::new(ActiveIdentitySnapshot::new(
    100                 active.identity().clone(),
    101                 RelayConnectionState::Connecting,
    102                 ProfileLoadState::Loading,
    103                 active.profile().cloned(),
    104             )),
    105             problem: None,
    106         })?;
    107         Ok(Some(ProfileRefreshPlan {
    108             public_key,
    109             active_identity: active,
    110             relays: loading.relay_configuration().relays().to_vec(),
    111             expected_revision: loading.revision(),
    112         }))
    113     }
    114 
    115     /// Applies a correlated refresh result on the actor.
    116     ///
    117     /// # Errors
    118     ///
    119     /// Returns a safe storage or application-state error. Stale results are
    120     /// discarded without persistence or publication.
    121     pub async fn complete_profile_refresh(
    122         &self,
    123         plan: &ProfileRefreshPlan,
    124         result: Result<ProfileFetchResult, SafeError>,
    125         profiles: &(impl ProfileRepository + ?Sized),
    126         clock: &(impl Clock + ?Sized),
    127     ) -> Result<AppSnapshot, SafeError> {
    128         if !is_current_active(self, plan.public_key()) {
    129             return Ok(self.snapshot());
    130         }
    131 
    132         let current_active = self
    133             .snapshot()
    134             .active_identity()
    135             .cloned()
    136             .ok_or_else(invalid_profile_completion)?;
    137 
    138         match result {
    139             Ok(fetched) => {
    140                 let (candidate, completeness) = fetched.into_parts();
    141                 self.complete_successful_profile_fetch(
    142                     plan,
    143                     current_active,
    144                     candidate,
    145                     completeness,
    146                     profiles,
    147                     clock,
    148                 )
    149                 .await
    150             }
    151             Err(error) => {
    152                 let status = refresh_status(error);
    153                 let snapshot = self.apply_transition(StateTransition::UpdateActiveIdentity {
    154                     expected: plan.public_key(),
    155                     active_identity: Box::new(ActiveIdentitySnapshot::new(
    156                         current_active.identity().clone(),
    157                         RelayConnectionState::Degraded,
    158                         ProfileLoadState::Error(error),
    159                         current_active.profile().cloned(),
    160                     )),
    161                     problem: Some(error),
    162                 })?;
    163                 profiles
    164                     .record_refresh_status(plan.public_key(), clock.now(), status)
    165                     .await?;
    166                 Ok(snapshot)
    167             }
    168         }
    169     }
    170 
    171     async fn complete_successful_profile_fetch(
    172         &self,
    173         plan: &ProfileRefreshPlan,
    174         current_active: ActiveIdentitySnapshot,
    175         candidate: Option<harvestcircle_domain::Kind0ProfileCandidate>,
    176         completeness: RelayFetchCompleteness,
    177         profiles: &(impl ProfileRepository + ?Sized),
    178         clock: &(impl Clock + ?Sized),
    179     ) -> Result<AppSnapshot, SafeError> {
    180         let relay_state = match completeness {
    181             RelayFetchCompleteness::Complete => RelayConnectionState::Connected,
    182             RelayFetchCompleteness::Partial => RelayConnectionState::Degraded,
    183         };
    184         let problem = match completeness {
    185             RelayFetchCompleteness::Complete => None,
    186             RelayFetchCompleteness::Partial => Some(partial_relay_result()),
    187         };
    188         match candidate {
    189             Some(candidate) => {
    190                 let cached = CachedProfile::new(
    191                     candidate.clone(),
    192                     clock.now(),
    193                     ProfileRefreshStatus::Success,
    194                 );
    195                 profiles.save_profile(&cached).await?;
    196                 let winning_profile = profiles.load_profile(plan.public_key()).await?.map_or_else(
    197                     || candidate.metadata().clone(),
    198                     |profile| profile.candidate().metadata().clone(),
    199                 );
    200                 self.apply_transition(StateTransition::UpdateActiveIdentity {
    201                     expected: plan.public_key(),
    202                     active_identity: Box::new(ActiveIdentitySnapshot::new(
    203                         current_active.identity().clone(),
    204                         relay_state,
    205                         ProfileLoadState::Fresh,
    206                         Some(winning_profile),
    207                     )),
    208                     problem,
    209                 })
    210             }
    211             None => self.apply_transition(StateTransition::UpdateActiveIdentity {
    212                 expected: plan.public_key(),
    213                 active_identity: Box::new(ActiveIdentitySnapshot::new(
    214                     current_active.identity().clone(),
    215                     relay_state,
    216                     if current_active.profile().is_some() {
    217                         ProfileLoadState::Cached
    218                     } else {
    219                         ProfileLoadState::Empty
    220                     },
    221                     current_active.profile().cloned(),
    222                 )),
    223                 problem,
    224             }),
    225         }
    226     }
    227 }
    228 
    229 const fn partial_relay_result() -> SafeError {
    230     SafeError::new(
    231         SafeErrorCode::RelayConnectionFailed,
    232         harvestcircle_domain::SafeMessage::new("One or more Nostr relays did not complete."),
    233     )
    234 }
    235 
    236 const fn invalid_profile_completion() -> SafeError {
    237     SafeError::new(
    238         SafeErrorCode::InvalidApplicationState,
    239         harvestcircle_domain::SafeMessage::new("The active profile refresh is no longer valid."),
    240     )
    241 }
    242 
    243 fn is_current_active(core: &AppCore, public_key: PublicKey) -> bool {
    244     core.snapshot()
    245         .active_identity()
    246         .is_some_and(|active| active.identity().public_key() == public_key)
    247 }
    248 
    249 const fn refresh_status(error: SafeError) -> ProfileRefreshStatus {
    250     match error.code() {
    251         SafeErrorCode::InvalidProfileMetadata | SafeErrorCode::ProfileRefreshFailed => {
    252             ProfileRefreshStatus::InvalidData
    253         }
    254         _ => ProfileRefreshStatus::Offline,
    255     }
    256 }
    257 
    258 #[cfg(test)]
    259 mod tests {
    260     use std::sync::Mutex;
    261     use std::time::{Duration, Instant};
    262 
    263     use harvestcircle_domain::{
    264         EventId, Kind0ProfileCandidate, ProfileMetadata, PublicKey, SafeError, SafeErrorCode,
    265         SafeMessage, SecretKeyInput, UnixTimestamp, select_latest_kind0,
    266     };
    267     use radroots_transport_nostr::{RelayAccess, RelayEndpoint, RelayUrlPolicy};
    268 
    269     use crate::{
    270         ActiveIdentitySnapshot, AppCore, BoxFuture, CachedProfile, Clock,
    271         InMemoryIdentityRepository, InMemoryOperationJournal, InMemorySecretStore, NostrClient,
    272         ProfileFetchResult, ProfileLoadState, ProfileRefreshStatus, ProfileRepository,
    273         RelayConfiguration, RelayConnectionState,
    274     };
    275 
    276     #[derive(Default)]
    277     struct MemoryProfiles(Mutex<Option<CachedProfile>>);
    278 
    279     impl ProfileRepository for MemoryProfiles {
    280         fn load_profile(
    281             &self,
    282             _public_key: PublicKey,
    283         ) -> BoxFuture<'_, Result<Option<CachedProfile>, SafeError>> {
    284             Box::pin(async move { Ok(self.0.lock().expect("profiles").clone()) })
    285         }
    286         fn save_profile<'a>(
    287             &'a self,
    288             profile: &'a CachedProfile,
    289         ) -> BoxFuture<'a, Result<(), SafeError>> {
    290             Box::pin(async move {
    291                 let mut cached = self.0.lock().expect("profiles");
    292                 let selected = cached.as_ref().map_or_else(
    293                     || profile.clone(),
    294                     |current| {
    295                         let winner = select_latest_kind0([
    296                             current.candidate().clone(),
    297                             profile.candidate().clone(),
    298                         ])
    299                         .expect("two candidates");
    300                         if &winner == current.candidate() {
    301                             current.clone()
    302                         } else {
    303                             profile.clone()
    304                         }
    305                     },
    306                 );
    307                 *cached = Some(selected);
    308                 Ok(())
    309             })
    310         }
    311         fn record_refresh_status<'a>(
    312             &'a self,
    313             _public_key: PublicKey,
    314             refreshed_at: UnixTimestamp,
    315             status: ProfileRefreshStatus,
    316         ) -> BoxFuture<'a, Result<(), SafeError>> {
    317             Box::pin(async move {
    318                 if let Some(profile) = self.0.lock().expect("profiles").as_mut() {
    319                     *profile =
    320                         CachedProfile::new(profile.candidate().clone(), refreshed_at, status);
    321                 }
    322                 Ok(())
    323             })
    324         }
    325         fn remove_profile(&self, _public_key: PublicKey) -> BoxFuture<'_, Result<(), SafeError>> {
    326             Box::pin(async move {
    327                 *self.0.lock().expect("profiles") = None;
    328                 Ok(())
    329             })
    330         }
    331     }
    332 
    333     struct UnavailableAuditProfiles {
    334         cached: MemoryProfiles,
    335         pending: bool,
    336         started: tokio::sync::Semaphore,
    337     }
    338 
    339     impl ProfileRepository for UnavailableAuditProfiles {
    340         fn load_profile(
    341             &self,
    342             public_key: PublicKey,
    343         ) -> BoxFuture<'_, Result<Option<CachedProfile>, SafeError>> {
    344             self.cached.load_profile(public_key)
    345         }
    346         fn save_profile<'a>(
    347             &'a self,
    348             profile: &'a CachedProfile,
    349         ) -> BoxFuture<'a, Result<(), SafeError>> {
    350             self.cached.save_profile(profile)
    351         }
    352         fn record_refresh_status<'a>(
    353             &'a self,
    354             _public_key: PublicKey,
    355             _at: UnixTimestamp,
    356             _status: ProfileRefreshStatus,
    357         ) -> BoxFuture<'a, Result<(), SafeError>> {
    358             Box::pin(async move {
    359                 self.started.add_permits(1);
    360                 if self.pending {
    361                     std::future::pending::<()>().await;
    362                 }
    363                 Err(SafeError::new(
    364                     SafeErrorCode::ProfileRefreshFailed,
    365                     SafeMessage::new("Audit unavailable."),
    366                 ))
    367             })
    368         }
    369         fn remove_profile(&self, public_key: PublicKey) -> BoxFuture<'_, Result<(), SafeError>> {
    370             self.cached.remove_profile(public_key)
    371         }
    372     }
    373 
    374     #[tokio::test]
    375     async fn nr001_failure_state_precedes_pending_or_failed_audit_persistence() {
    376         for pending in [true, false] {
    377             let profiles = UnavailableAuditProfiles {
    378                 cached: MemoryProfiles::default(),
    379                 pending,
    380                 started: tokio::sync::Semaphore::new(0),
    381             };
    382             let (core, _) = active_core(&profiles.cached, Some("Cached")).await;
    383             let plan = core
    384                 .begin_profile_refresh()
    385                 .expect("begin")
    386                 .expect("active");
    387             let error = SafeError::new(
    388                 SafeErrorCode::RelayConnectionFailed,
    389                 SafeMessage::new("Relay unavailable."),
    390             );
    391             let completion =
    392                 core.complete_profile_refresh(&plan, Err(error), &profiles, &FixedClock);
    393             tokio::pin!(completion);
    394             tokio::select! {
    395                 result = &mut completion => { assert!(!pending); assert!(result.is_err()); }
    396                 permit = profiles.started.acquire(), if pending => { permit.expect("audit entered").forget(); }
    397             }
    398             let snapshot = core.snapshot();
    399             assert_eq!(
    400                 snapshot.active_identity().expect("active").profile_state(),
    401                 ProfileLoadState::Error(error)
    402             );
    403             assert_eq!(
    404                 snapshot
    405                     .active_identity()
    406                     .expect("active")
    407                     .profile()
    408                     .and_then(ProfileMetadata::name),
    409                 Some("Cached")
    410             );
    411             assert_eq!(snapshot.recoverable_problem(), Some(error));
    412         }
    413     }
    414 
    415     struct FixedClock;
    416     impl Clock for FixedClock {
    417         fn now(&self) -> UnixTimestamp {
    418             UnixTimestamp::from_seconds(50).expect("time")
    419         }
    420     }
    421 
    422     struct FixedClient(Result<Option<Kind0ProfileCandidate>, SafeError>);
    423     impl NostrClient for FixedClient {
    424         fn fetch_profile<'a>(
    425             &'a self,
    426             _public_key: PublicKey,
    427             _relays: &'a [RelayEndpoint],
    428             _deadline: std::time::Instant,
    429         ) -> BoxFuture<'a, Result<ProfileFetchResult, SafeError>> {
    430             let result = self.0.clone();
    431             Box::pin(async move { result.map(ProfileFetchResult::complete) })
    432         }
    433     }
    434 
    435     struct BlockingClient {
    436         started: tokio::sync::Semaphore,
    437         release: tokio::sync::Semaphore,
    438         result: Result<Option<Kind0ProfileCandidate>, SafeError>,
    439     }
    440 
    441     impl BlockingClient {
    442         fn new(result: Result<Option<Kind0ProfileCandidate>, SafeError>) -> Self {
    443             Self {
    444                 started: tokio::sync::Semaphore::new(0),
    445                 release: tokio::sync::Semaphore::new(0),
    446                 result,
    447             }
    448         }
    449     }
    450 
    451     impl NostrClient for BlockingClient {
    452         fn fetch_profile<'a>(
    453             &'a self,
    454             _public_key: PublicKey,
    455             _relays: &'a [RelayEndpoint],
    456             _deadline: std::time::Instant,
    457         ) -> BoxFuture<'a, Result<ProfileFetchResult, SafeError>> {
    458             Box::pin(async move {
    459                 self.started.add_permits(1);
    460                 let permit = self.release.acquire().await.expect("release open");
    461                 permit.forget();
    462                 self.result.clone().map(ProfileFetchResult::complete)
    463             })
    464         }
    465     }
    466 
    467     fn profile(public_key: PublicKey, name: &str, timestamp: i64) -> Kind0ProfileCandidate {
    468         Kind0ProfileCandidate::new(
    469             EventId::from_bytes([u8::try_from(timestamp).expect("small timestamp"); 32]),
    470             public_key,
    471             UnixTimestamp::from_seconds(timestamp).expect("time"),
    472             ProfileMetadata::new(Some(name.to_owned()), None, None, None, None).expect("profile"),
    473         )
    474     }
    475 
    476     async fn active_core(
    477         profiles: &MemoryProfiles,
    478         cached_name: Option<&str>,
    479     ) -> (AppCore, PublicKey) {
    480         let relays = RelayConfiguration::new(vec![
    481             RelayEndpoint::new(
    482                 "ws://localhost:8080",
    483                 RelayUrlPolicy::Local,
    484                 RelayAccess::ReadWrite,
    485             )
    486             .expect("relay"),
    487         ])
    488         .expect("relay configuration");
    489         let core = AppCore::in_memory(relays);
    490         let identities = InMemoryIdentityRepository::default();
    491         let secrets = InMemorySecretStore::default();
    492         let journal = InMemoryOperationJournal::default();
    493         core.bootstrap().expect("bootstrap");
    494         let public_key = core
    495             .import_secret_key(
    496                 SecretKeyInput::parse(
    497                     "7e7e9c42a91bfef19fa7ea99d52d8afdb67d893a8fefba1f5cb9793f2107f6d7".to_owned(),
    498                 )
    499                 .expect("secret"),
    500                 &identities,
    501                 &identities,
    502                 &secrets,
    503                 &journal,
    504                 &FixedClock,
    505             )
    506             .await
    507             .expect("import")
    508             .identity()
    509             .public_key();
    510         if let Some(name) = cached_name {
    511             profiles
    512                 .save_profile(&CachedProfile::new(
    513                     profile(public_key, name, 10),
    514                     UnixTimestamp::from_seconds(11).expect("time"),
    515                     ProfileRefreshStatus::Success,
    516                 ))
    517                 .await
    518                 .expect("cache");
    519         }
    520         core.activate_identity(
    521             public_key,
    522             &identities,
    523             &identities,
    524             profiles,
    525             &secrets,
    526             &FixedClock,
    527         )
    528         .await
    529         .expect("activate");
    530         (core, public_key)
    531     }
    532 
    533     #[tokio::test]
    534     async fn refresh_transitions_from_cache_through_loading_to_fresh_profile() {
    535         let profiles = MemoryProfiles::default();
    536         let (core, public_key) = active_core(&profiles, Some("Cached")).await;
    537         assert_eq!(
    538             core.snapshot()
    539                 .active_identity()
    540                 .map(crate::ActiveIdentitySnapshot::profile_state),
    541             Some(ProfileLoadState::Cached)
    542         );
    543         let plan = core
    544             .begin_profile_refresh()
    545             .expect("begin refresh")
    546             .expect("active refresh");
    547         let loading = core.snapshot();
    548         assert_eq!(
    549             loading
    550                 .active_identity()
    551                 .map(crate::ActiveIdentitySnapshot::profile_state),
    552             Some(ProfileLoadState::Loading)
    553         );
    554         assert_eq!(
    555             loading
    556                 .active_identity()
    557                 .map(crate::ActiveIdentitySnapshot::relay_state),
    558             Some(RelayConnectionState::Connecting)
    559         );
    560         let client = FixedClient(Ok(Some(profile(public_key, "Fresh", 20))));
    561         let result = client
    562             .fetch_profile(plan.public_key(), plan.relays(), deadline())
    563             .await;
    564         core.complete_profile_refresh(&plan, result, &profiles, &FixedClock)
    565             .await
    566             .expect("complete refresh");
    567         assert_eq!(
    568             core.snapshot()
    569                 .active_identity()
    570                 .and_then(|active| active.profile())
    571                 .and_then(ProfileMetadata::name),
    572             Some("Fresh")
    573         );
    574     }
    575 
    576     #[tokio::test]
    577     async fn refresh_failure_preserves_cached_profile_as_nonfatal_state() {
    578         let profiles = MemoryProfiles::default();
    579         let (core, public_key) = active_core(&profiles, Some("Cached")).await;
    580         let cached = profile(public_key, "Cached", 10);
    581         let error = SafeError::new(
    582             SafeErrorCode::RelayConnectionFailed,
    583             SafeMessage::new("The relay is offline."),
    584         );
    585 
    586         let snapshot = core
    587             .refresh_profile_for_active_identity(
    588                 &profiles,
    589                 &FixedClient(Err(error)),
    590                 &FixedClock,
    591                 deadline(),
    592             )
    593             .await
    594             .expect("nonfatal refresh");
    595 
    596         assert_eq!(snapshot.recoverable_problem(), Some(error));
    597         assert_eq!(
    598             snapshot
    599                 .active_identity()
    600                 .map(crate::ActiveIdentitySnapshot::relay_state),
    601             Some(RelayConnectionState::Degraded)
    602         );
    603         assert_eq!(
    604             profiles
    605                 .load_profile(public_key)
    606                 .await
    607                 .expect("load")
    608                 .expect("cache")
    609                 .candidate(),
    610             &cached
    611         );
    612     }
    613 
    614     #[tokio::test]
    615     async fn refresh_discards_stale_completion_after_sign_out() {
    616         let profiles = MemoryProfiles::default();
    617         let (core, public_key) = active_core(&profiles, Some("Cached")).await;
    618         let client = BlockingClient::new(Ok(Some(profile(public_key, "Stale", 20))));
    619 
    620         let refresh =
    621             core.refresh_profile_for_active_identity(&profiles, &client, &FixedClock, deadline());
    622         let sign_out = async {
    623             let permit = client.started.acquire().await.expect("refresh starts");
    624             permit.forget();
    625             core.sign_out().expect("sign out");
    626             client.release.add_permits(1);
    627         };
    628         let (result, ()) = tokio::join!(refresh, sign_out);
    629 
    630         assert!(
    631             result
    632                 .expect("stale result is harmless")
    633                 .active_identity()
    634                 .is_none()
    635         );
    636         assert_eq!(
    637             profiles
    638                 .load_profile(public_key)
    639                 .await
    640                 .expect("load")
    641                 .expect("cached")
    642                 .candidate()
    643                 .metadata()
    644                 .name(),
    645             Some("Cached")
    646         );
    647     }
    648 
    649     #[tokio::test]
    650     async fn manual_refresh_is_repeatable_and_signed_out_safe() {
    651         let profiles = MemoryProfiles::default();
    652         let (core, public_key) = active_core(&profiles, None).await;
    653         let first = core
    654             .refresh_active_profile(
    655                 &profiles,
    656                 &FixedClient(Ok(Some(profile(public_key, "First", 10)))),
    657                 &FixedClock,
    658                 deadline(),
    659             )
    660             .await
    661             .expect("first refresh");
    662         let second = core
    663             .refresh_active_profile(
    664                 &profiles,
    665                 &FixedClient(Ok(Some(profile(public_key, "Second", 20)))),
    666                 &FixedClock,
    667                 deadline(),
    668             )
    669             .await
    670             .expect("second refresh");
    671 
    672         assert!(second.revision() > first.revision());
    673         assert_eq!(
    674             second
    675                 .active_identity()
    676                 .and_then(|active| active.profile())
    677                 .and_then(ProfileMetadata::name),
    678             Some("Second")
    679         );
    680         let signed_out = core.sign_out().expect("sign out");
    681         let no_op = core
    682             .refresh_active_profile(&profiles, &FixedClient(Ok(None)), &FixedClock, deadline())
    683             .await
    684             .expect("signed-out no-op");
    685         assert_eq!(no_op, signed_out);
    686     }
    687 
    688     fn deadline() -> Instant {
    689         Instant::now() + Duration::from_secs(5)
    690     }
    691 
    692     #[tokio::test]
    693     async fn partial_relay_success_retains_verified_data_and_marks_degraded_connectivity() {
    694         let profiles = MemoryProfiles::default();
    695         let (core, public_key) = active_core(&profiles, None).await;
    696         let plan = core
    697             .begin_profile_refresh()
    698             .expect("begin")
    699             .expect("active");
    700         let snapshot = core
    701             .complete_profile_refresh(
    702                 &plan,
    703                 Ok(ProfileFetchResult::partial(Some(profile(
    704                     public_key, "Partial", 30,
    705                 )))),
    706                 &profiles,
    707                 &FixedClock,
    708             )
    709             .await
    710             .expect("partial completion");
    711         let active = snapshot.active_identity().expect("active identity");
    712         assert_eq!(active.relay_state(), RelayConnectionState::Degraded);
    713         assert_eq!(active.profile_state(), ProfileLoadState::Fresh);
    714         assert_eq!(
    715             active.profile().and_then(ProfileMetadata::name),
    716             Some("Partial")
    717         );
    718         assert_eq!(
    719             snapshot.recoverable_problem().map(SafeError::code),
    720             Some(SafeErrorCode::RelayConnectionFailed)
    721         );
    722     }
    723 
    724     #[tokio::test]
    725     async fn overlapping_refreshes_keep_the_newest_event_regardless_of_completion_order() {
    726         let profiles = MemoryProfiles::default();
    727         let (core, public_key) = active_core(&profiles, Some("Cached")).await;
    728         let first = core
    729             .begin_profile_refresh()
    730             .expect("first")
    731             .expect("active");
    732         let second = core
    733             .begin_profile_refresh()
    734             .expect("second")
    735             .expect("active");
    736 
    737         core.complete_profile_refresh(
    738             &second,
    739             Ok(ProfileFetchResult::complete(Some(profile(
    740                 public_key, "Newest", 30,
    741             )))),
    742             &profiles,
    743             &FixedClock,
    744         )
    745         .await
    746         .expect("newest completes first");
    747         let final_snapshot = core
    748             .complete_profile_refresh(
    749                 &first,
    750                 Ok(ProfileFetchResult::complete(Some(profile(
    751                     public_key, "Older", 20,
    752                 )))),
    753                 &profiles,
    754                 &FixedClock,
    755             )
    756             .await
    757             .expect("older completes last");
    758 
    759         assert_eq!(
    760             final_snapshot
    761                 .active_identity()
    762                 .and_then(ActiveIdentitySnapshot::profile)
    763                 .and_then(ProfileMetadata::name),
    764             Some("Newest")
    765         );
    766         assert_eq!(
    767             profiles
    768                 .load_profile(public_key)
    769                 .await
    770                 .expect("cache")
    771                 .expect("profile")
    772                 .candidate()
    773                 .metadata()
    774                 .name(),
    775             Some("Newest")
    776         );
    777     }
    778 }