field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

runtime.rs (46215B)


      1 use std::sync::Arc;
      2 #[path = "author_visibility.rs"]
      3 mod author_visibility;
      4 pub use author_visibility::{
      5     FfiAuthorVisibility, FfiAuthorVisibilityEntry, FfiAuthorVisibilityPolicy,
      6 };
      7 #[path = "cache_cleanup.rs"]
      8 mod cache_cleanup;
      9 #[path = "key_removal.rs"]
     10 mod key_removal;
     11 pub use cache_cleanup::FfiMediaCacheCleanup;
     12 #[path = "backup/runtime.rs"]
     13 mod backup;
     14 #[path = "restore/runtime.rs"]
     15 mod restore;
     16 pub use restore::{FfiRestoreStore, restore_local_application_backup};
     17 #[path = "revision.rs"]
     18 mod revision;
     19 pub use revision::FfiRevisionSourceRequest;
     20 
     21 #[path = "composer/runtime.rs"]
     22 mod composer;
     23 #[path = "draft_inventory/runtime.rs"]
     24 mod draft_inventory;
     25 #[path = "recovery_completion.rs"]
     26 mod recovery_completion;
     27 #[path = "recovery_inventory/runtime.rs"]
     28 mod recovery_inventory;
     29 #[path = "recovery_schedule.rs"]
     30 mod recovery_schedule;
     31 #[path = "recovery_status.rs"]
     32 mod recovery_status;
     33 pub use recovery_completion::{FfiRecoveryCompletionReceipt, FfiRecoveryUploadReceipt};
     34 pub use recovery_schedule::FfiNativeRecoverySchedule;
     35 pub use recovery_status::{FfiNativeRecoveryReason, FfiNativeRecoveryStatus};
     36 #[path = "submission/runtime.rs"]
     37 mod submission;
     38 
     39 use tera_core::runtime::product_surface::{
     40     LocalNetworkRelayPolicy, Phase1AddIntent, Phase1ExistingDraft, Phase1MediaCachePolicy,
     41     Phase1QueueIntent, Phase1ReviseIntent, ReplaceMobileSettings, TodayPageRequest,
     42     phase1_new_addressable_identifier, phase1_operation_now_unix_ms,
     43 };
     44 
     45 use crate::FfiRevisionStatusRecord;
     46 use crate::dto::PreparedMedia;
     47 use crate::operations::{
     48     FfiIdentityCommandRecord, FfiMediaCacheStatusRecord, FfiMediaOperation,
     49     FfiMobileSettingsRecord, FfiProfileMetadataInputRecord, FfiProfileStatusRecord,
     50     FfiReplaceSettingsRecord, FfiRevisionInputRecord, FfiSettingsTransitionRecord,
     51     FfiVerifiedMediaArtifactRecord, decode_artifact_id, decode_configuration,
     52     decode_reference_fingerprint,
     53 };
     54 use crate::signer::HostSignerAdapter;
     55 use crate::subscription::SubscriptionHub;
     56 use crate::{
     57     FfiAddDraftInput, FfiAddSchemaRecord, FfiBlossomConfigurationRecord,
     58     FfiBlossomEndpointAuthority, FfiBlossomEvidenceRecord, FfiBlossomHostKind,
     59     FfiBlossomUploadInput, FfiBlossomUploadIntent, FfiCapabilityRecord, FfiCardAddParityRecord,
     60     FfiDraftStatusRecord, FfiIdentityStatusRecord, FfiLocalNetworkRecord, FfiMeRecord,
     61     FfiQueuePolicyRecord, FfiRelayStatusReportRecord, FfiRetractionDraftInput,
     62     FfiRuntimeChangeKind, FfiRuntimeInfoRecord, FfiSearchResultRecord, FfiShutdownRecord,
     63     FfiStorageStatusRecord, FfiSubscriptionHandle, FfiTodayPageRecord, FfiTodayProjectionUpdate,
     64     FfiTodayRefreshRecord, FfiTodaySyncRecord, TeraAppError, TeraHostSigner, TeraRuntimeObserver,
     65     add_schemas, decode_id,
     66 };
     67 
     68 #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)]
     69 pub enum ProtectedDataAvailability {
     70     Available,
     71     Unavailable,
     72 }
     73 
     74 impl From<ProtectedDataAvailability> for tera_core::runtime::store::ProtectedDataAvailability {
     75     fn from(value: ProtectedDataAvailability) -> Self {
     76         match value {
     77             ProtectedDataAvailability::Available => Self::Available,
     78             ProtectedDataAvailability::Unavailable => Self::Unavailable,
     79         }
     80     }
     81 }
     82 
     83 /// Native boundary object delegating all product behavior to the ordinary Rust core.
     84 #[derive(uniffi::Object)]
     85 pub struct TeraRuntime {
     86     inner: tera_core::TeraRuntime,
     87     has_host_signer: bool,
     88     subscriptions: Arc<SubscriptionHub>,
     89 }
     90 
     91 #[cfg_attr(not(coverage_nightly), uniffi::export(async_runtime = "tokio"))]
     92 impl TeraRuntime {
     93     #[cfg_attr(not(coverage_nightly), uniffi::constructor)]
     94     pub async fn open(
     95         application_support_directory: String,
     96         public_key_hex: String,
     97         source_generation_hex: String,
     98         source_generation_created_at_unix_ms: u64,
     99         protected_data: ProtectedDataAvailability,
    100     ) -> Result<Self, TeraAppError> {
    101         build_runtime(
    102             application_support_directory,
    103             public_key_hex,
    104             source_generation_hex,
    105             source_generation_created_at_unix_ms,
    106             protected_data,
    107             None,
    108             RuntimeOpenOptions::default(),
    109         )
    110         .await
    111     }
    112 
    113     #[cfg_attr(not(coverage_nightly), uniffi::constructor)]
    114     pub async fn with_host_signer(
    115         application_support_directory: String,
    116         public_key_hex: String,
    117         source_generation_hex: String,
    118         source_generation_created_at_unix_ms: u64,
    119         protected_data: ProtectedDataAvailability,
    120         host_signer: Box<dyn TeraHostSigner>,
    121     ) -> Result<Self, TeraAppError> {
    122         build_runtime(
    123             application_support_directory,
    124             public_key_hex,
    125             source_generation_hex,
    126             source_generation_created_at_unix_ms,
    127             protected_data,
    128             Some(host_signer),
    129             RuntimeOpenOptions::default(),
    130         )
    131         .await
    132     }
    133 
    134     pub async fn shutdown(&self) -> Result<FfiShutdownRecord, TeraAppError> {
    135         self.subscriptions.close();
    136         let result = self
    137             .inner
    138             .shutdown()
    139             .await
    140             .map(Into::into)
    141             .map_err(Into::into);
    142         if result.is_ok() {
    143             self.subscriptions.drain().await;
    144         }
    145         result
    146     }
    147 
    148     pub fn uptime_millis(&self) -> i64 {
    149         self.inner.uptime_millis()
    150     }
    151 
    152     pub fn info(&self) -> FfiRuntimeInfoRecord {
    153         self.inner.info().into()
    154     }
    155 
    156     pub fn info_json(&self) -> String {
    157         self.inner.info_json()
    158     }
    159 
    160     pub fn set_app_info_platform(
    161         &self,
    162         platform: Option<String>,
    163         bundle_id: Option<String>,
    164         version: Option<String>,
    165         build_number: Option<String>,
    166         build_sha: Option<String>,
    167     ) {
    168         self.inner
    169             .set_app_info_platform(platform, bundle_id, version, build_number, build_sha);
    170     }
    171 
    172     pub fn identity_status(&self) -> Result<FfiIdentityStatusRecord, TeraAppError> {
    173         let public_key = self
    174             .inner
    175             .authenticated_store_public_key_hex()
    176             .ok_or_else(|| {
    177                 TeraAppError::failure(
    178                     "identity_unavailable",
    179                     "identity",
    180                     true,
    181                     &["unlock_identity"],
    182                     "The active identity is unavailable.",
    183                 )
    184             })?;
    185         Ok(FfiIdentityStatusRecord {
    186             schema_version: crate::MOBILE_FFI_SCHEMA_VERSION,
    187             public_key,
    188             host_signer_configured: self.has_host_signer,
    189         })
    190     }
    191 
    192     pub fn sdk_capabilities(&self) -> Vec<FfiCapabilityRecord> {
    193         self.inner
    194             .sdk_capabilities()
    195             .into_iter()
    196             .map(Into::into)
    197             .collect()
    198     }
    199 
    200     pub async fn sdk_storage_status(&self) -> Result<FfiStorageStatusRecord, TeraAppError> {
    201         self.inner
    202             .sdk_storage_status()
    203             .await
    204             .map(Into::into)
    205             .map_err(Into::into)
    206     }
    207 
    208     pub fn sdk_relay_status(&self) -> Result<Option<FfiRelayStatusReportRecord>, TeraAppError> {
    209         self.inner
    210             .sdk_relay_status()
    211             .map(|value| value.map(Into::into))
    212             .map_err(Into::into)
    213     }
    214 
    215     pub fn sdk_blossom_configuration(
    216         &self,
    217     ) -> Result<Option<FfiBlossomConfigurationRecord>, TeraAppError> {
    218         self.inner
    219             .sdk_blossom_configuration()
    220             .map(|value| value.map(Into::into))
    221             .map_err(Into::into)
    222     }
    223 
    224     pub fn sdk_blossom_evidence(&self) -> Result<Option<FfiBlossomEvidenceRecord>, TeraAppError> {
    225         self.inner
    226             .sdk_blossom_evidence()
    227             .map(|value| value.map(Into::into))
    228             .map_err(Into::into)
    229     }
    230 
    231     pub async fn probe_blossom(&self) -> Result<FfiBlossomEvidenceRecord, TeraAppError> {
    232         let evidence = self
    233             .inner
    234             .probe_blossom()
    235             .await
    236             .map(Into::into)
    237             .map_err(TeraAppError::from)?;
    238         self.subscriptions.notify(FfiRuntimeChangeKind::Media, None);
    239         Ok(evidence)
    240     }
    241 
    242     pub fn subscribe_changes(
    243         &self,
    244         observer: Box<dyn TeraRuntimeObserver>,
    245     ) -> Result<Arc<FfiSubscriptionHandle>, TeraAppError> {
    246         self.subscriptions.subscribe(observer)
    247     }
    248 
    249     pub async fn configure_public_relays(
    250         &self,
    251         writable_relays: Vec<String>,
    252     ) -> Result<(), TeraAppError> {
    253         self.inner
    254             .configure_public_relays(writable_relays)
    255             .await
    256             .map_err(TeraAppError::from)?;
    257         self.subscriptions.notify(FfiRuntimeChangeKind::Relay, None);
    258         Ok(())
    259     }
    260 
    261     pub async fn configure_simulator_relays(
    262         &self,
    263         loopback_relays: Vec<String>,
    264     ) -> Result<(), TeraAppError> {
    265         self.inner
    266             .configure_simulator_relays(loopback_relays)
    267             .await
    268             .map_err(TeraAppError::from)?;
    269         self.subscriptions.notify(FfiRuntimeChangeKind::Relay, None);
    270         Ok(())
    271     }
    272 
    273     pub async fn configure_device_relays(
    274         &self,
    275         writable_relays: Vec<String>,
    276     ) -> Result<(), TeraAppError> {
    277         self.inner
    278             .configure_device_relays(writable_relays)
    279             .await
    280             .map_err(TeraAppError::from)?;
    281         self.subscriptions.notify(FfiRuntimeChangeKind::Relay, None);
    282         Ok(())
    283     }
    284 
    285     pub async fn configure_blossom(
    286         &self,
    287         host_kind: FfiBlossomHostKind,
    288         endpoint_authority: FfiBlossomEndpointAuthority,
    289         primary_origin: String,
    290         fallback_origins: Vec<String>,
    291     ) -> Result<(), TeraAppError> {
    292         self.inner
    293             .configure_blossom(
    294                 host_kind.into(),
    295                 endpoint_authority.into(),
    296                 primary_origin,
    297                 fallback_origins,
    298             )
    299             .await
    300             .map_err(TeraAppError::from)?;
    301         self.subscriptions.notify(FfiRuntimeChangeKind::Media, None);
    302         Ok(())
    303     }
    304 
    305     pub fn phase1_card_add_parity(&self) -> Vec<FfiCardAddParityRecord> {
    306         self.inner
    307             .phase1_card_add_parity()
    308             .into_iter()
    309             .map(|value| FfiCardAddParityRecord {
    310                 schema_version: crate::MOBILE_FFI_SCHEMA_VERSION,
    311                 card_type: value.card_type.into(),
    312                 command_type: value.add_command_type.into(),
    313             })
    314             .collect()
    315     }
    316 
    317     pub fn phase1_add_schemas(&self) -> Vec<FfiAddSchemaRecord> {
    318         add_schemas()
    319     }
    320 
    321     pub fn phase1_local_network(
    322         &self,
    323         context: FfiLocalNetworkRecord,
    324     ) -> Result<FfiLocalNetworkRecord, TeraAppError> {
    325         self.local_network(context).map(Into::into)
    326     }
    327 
    328     pub async fn phase1_today_page(
    329         &self,
    330         context: FfiLocalNetworkRecord,
    331         limit: u16,
    332         as_of_unix_s: Option<u64>,
    333         cursor: Option<String>,
    334         viewer_time_zone: Option<String>,
    335     ) -> Result<FfiTodayPageRecord, TeraAppError> {
    336         if as_of_unix_s.is_some() == cursor.is_some()
    337             || viewer_time_zone.is_some() != as_of_unix_s.is_some()
    338         {
    339             return Err(TeraAppError::invalid_argument("invalid_today_page_request"));
    340         }
    341         let context = self.local_network(context)?;
    342         let request = match cursor {
    343             Some(cursor) => TodayPageRequest::after(limit, cursor),
    344             None => TodayPageRequest::first(
    345                 limit,
    346                 as_of_unix_s
    347                     .ok_or_else(|| TeraAppError::invalid_argument("today_as_of_required"))?,
    348                 viewer_time_zone
    349                     .as_deref()
    350                     .ok_or_else(|| TeraAppError::invalid_argument("today_viewer_zone_required"))?,
    351             ),
    352         };
    353         self.inner
    354             .phase1_today_page(&context, request)
    355             .await
    356             .map(Into::into)
    357             .map_err(Into::into)
    358     }
    359 
    360     pub async fn phase1_today_thread_page(
    361         &self,
    362         context: FfiLocalNetworkRecord,
    363         limit: u16,
    364         cursor: String,
    365     ) -> Result<crate::FfiTodayThreadPageRecord, TeraAppError> {
    366         let context = self.local_network(context)?;
    367         self.inner
    368             .phase1_today_thread_page(&context, limit, &cursor)
    369             .await
    370             .map(Into::into)
    371             .map_err(Into::into)
    372     }
    373 
    374     /// Reconcile displayed identities against current application visibility.
    375     pub async fn phase1_today_reconcile(
    376         &self,
    377         context: FfiLocalNetworkRecord,
    378         as_of_unix_s: u64,
    379         card_ids: Vec<String>,
    380         expected_generation: Option<u64>,
    381         viewer_time_zone: String,
    382     ) -> Result<FfiTodayPageRecord, TeraAppError> {
    383         let context = self.local_network(context)?;
    384         let current = self
    385             .inner
    386             .phase1_today_reconcile(
    387                 &context,
    388                 as_of_unix_s,
    389                 &card_ids,
    390                 expected_generation,
    391                 &viewer_time_zone,
    392             )
    393             .await?;
    394         Ok(FfiTodayPageRecord {
    395             calendar: current.calendar.into(),
    396             schema_version: crate::TODAY_PAGE_FFI_SCHEMA_VERSION,
    397             projection_generation: current.projection_generation,
    398             as_of_unix_s,
    399             items: current.items.into_iter().map(Into::into).collect(),
    400             next_cursor: None,
    401         })
    402     }
    403 
    404     pub async fn phase1_refresh_today(
    405         &self,
    406         context: FfiLocalNetworkRecord,
    407         now_unix_s: u64,
    408         update: FfiTodayProjectionUpdate,
    409     ) -> Result<FfiTodayRefreshRecord, TeraAppError> {
    410         let context = self.local_network(context)?;
    411         let receipt = self
    412             .inner
    413             .phase1_refresh_today(&context, now_unix_s, update.into())
    414             .await
    415             .map_err(TeraAppError::from)?;
    416         self.subscriptions
    417             .notify_context(FfiRuntimeChangeKind::Today, Some(&context), None);
    418         Ok(receipt.into())
    419     }
    420 
    421     pub async fn phase1_sync_today(
    422         &self,
    423         context: FfiLocalNetworkRecord,
    424         now_unix_s: u64,
    425         update: FfiTodayProjectionUpdate,
    426     ) -> Result<FfiTodaySyncRecord, TeraAppError> {
    427         let context = self.local_network(context)?;
    428         let receipt = self
    429             .inner
    430             .phase1_sync_today(&context, now_unix_s, update.into())
    431             .await
    432             .map_err(TeraAppError::from)?;
    433         self.subscriptions
    434             .notify_context(FfiRuntimeChangeKind::Today, Some(&context), None);
    435         Ok(receipt.into())
    436     }
    437 
    438     pub async fn phase1_backfill_today(
    439         &self,
    440         context: FfiLocalNetworkRecord,
    441         now_unix_s: u64,
    442         cursor: String,
    443     ) -> Result<FfiTodaySyncRecord, TeraAppError> {
    444         let context = self.local_network(context)?;
    445         let receipt = self
    446             .inner
    447             .phase1_backfill_today(&context, now_unix_s, &cursor)
    448             .await
    449             .map_err(TeraAppError::from)?;
    450         self.subscriptions
    451             .notify_context(FfiRuntimeChangeKind::Today, Some(&context), None);
    452         Ok(receipt.into())
    453     }
    454 
    455     pub async fn phase1_search(
    456         &self,
    457         context: FfiLocalNetworkRecord,
    458         query: String,
    459         limit: u16,
    460         as_of_unix_s: u64,
    461         viewer_time_zone: String,
    462     ) -> Result<Vec<FfiSearchResultRecord>, TeraAppError> {
    463         let context = self.local_network(context)?;
    464         self.inner
    465             .phase1_search(&context, &query, limit, as_of_unix_s, &viewer_time_zone)
    466             .await
    467             .map(|results| results.into_iter().map(Into::into).collect())
    468             .map_err(Into::into)
    469     }
    470 
    471     pub async fn phase1_me(
    472         &self,
    473         context: FfiLocalNetworkRecord,
    474         as_of_unix_s: u64,
    475         viewer_time_zone: String,
    476     ) -> Result<FfiMeRecord, TeraAppError> {
    477         let context = self.local_network(context)?;
    478         let public_key = self
    479             .inner
    480             .authenticated_store_public_key_hex()
    481             .ok_or_else(|| {
    482                 TeraAppError::failure(
    483                     "identity_unavailable",
    484                     "identity",
    485                     true,
    486                     &["unlock_identity"],
    487                     "The active identity is unavailable.",
    488                 )
    489             })?;
    490         self.inner
    491             .phase1_me(&context, &public_key, as_of_unix_s, &viewer_time_zone)
    492             .await
    493             .map(Into::into)
    494             .map_err(Into::into)
    495     }
    496 
    497     pub fn phase1_validate_add_draft(
    498         &self,
    499         input: FfiAddDraftInput,
    500         authored_at_unix_s: u64,
    501     ) -> Result<(), TeraAppError> {
    502         let blossom = self.inner.sdk_blossom_slot().map_err(TeraAppError::from)?;
    503         input
    504             .command_and_media(authored_at_unix_s, blossom.as_ref())
    505             .map(|_| ())
    506     }
    507 
    508     /// Saves one new or existing Add form while Rust owns all identity and
    509     /// timestamp policy. Addressable identifiers are generated when omitted.
    510     pub async fn phase1_save_add_intent(
    511         &self,
    512         mut input: FfiAddDraftInput,
    513         existing_draft_id: Option<String>,
    514         expected_revision: Option<u64>,
    515     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    516         if input.identifier.is_none()
    517             && matches!(
    518                 input.command_type,
    519                 crate::FfiAddCommandType::CreateEvent
    520                     | crate::FfiAddCommandType::CreateFoodAvailability
    521             )
    522         {
    523             input.identifier = Some(phase1_new_addressable_identifier());
    524         }
    525         let authored_at_unix_s =
    526             phase1_operation_now_unix_ms().map_err(TeraAppError::from)? / 1_000;
    527         let blossom = self.inner.sdk_blossom_slot().map_err(TeraAppError::from)?;
    528         let (command, media, form) =
    529             input.command_media_and_form(authored_at_unix_s, blossom.as_ref())?;
    530         let existing = match (existing_draft_id, expected_revision) {
    531             (Some(draft_id), Some(revision)) => Some(
    532                 Phase1ExistingDraft::new(decode_id(&draft_id, "invalid_draft_id")?, revision)
    533                     .map_err(TeraAppError::from)?,
    534             ),
    535             (None, None) => None,
    536             _ => {
    537                 return Err(TeraAppError::invalid_argument("invalid_existing_draft"));
    538             }
    539         };
    540         let status = self
    541             .inner
    542             .phase1_save_add_intent(
    543                 Phase1AddIntent::new(command, media, form, existing).map_err(TeraAppError::from)?,
    544             )
    545             .await
    546             .map_err(TeraAppError::from)?;
    547         let draft_id = hex::encode(status.draft().draft_id().as_bytes());
    548         self.subscriptions
    549             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    550         Ok(status.into())
    551     }
    552 
    553     #[allow(clippy::too_many_arguments)]
    554     pub async fn phase1_save_draft(
    555         &self,
    556         draft_id: String,
    557         input: FfiAddDraftInput,
    558         authored_at_unix_s: u64,
    559         expected_revision: Option<u64>,
    560         persisted_at_unix_ms: u64,
    561     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    562         let blossom = self.inner.sdk_blossom_slot().map_err(TeraAppError::from)?;
    563         let (command, media, form) =
    564             input.command_media_and_form(authored_at_unix_s, blossom.as_ref())?;
    565         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    566         let status = self
    567             .inner
    568             .phase1_save_draft_with_form(
    569                 decoded_id,
    570                 command,
    571                 authored_at_unix_s,
    572                 media,
    573                 form,
    574                 expected_revision,
    575                 persisted_at_unix_ms,
    576             )
    577             .await
    578             .map_err(TeraAppError::from)?;
    579         self.subscriptions
    580             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    581         Ok(status.into())
    582     }
    583 
    584     pub async fn phase1_save_retraction_draft(
    585         &self,
    586         draft_id: String,
    587         input: FfiRetractionDraftInput,
    588         authored_at_unix_s: u64,
    589         persisted_at_unix_ms: u64,
    590     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    591         if input.schema_version != crate::MOBILE_FFI_SCHEMA_VERSION {
    592             return Err(TeraAppError::invalid_argument("unsupported_schema_version"));
    593         }
    594         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    595         let command_type = match input.command_type {
    596             crate::FfiAddCommandType::CreateUpdate => {
    597                 tera_core::runtime::product_surface::AddCommandType::CreateUpdate
    598             }
    599             crate::FfiAddCommandType::CreatePhotoUpdate => {
    600                 tera_core::runtime::product_surface::AddCommandType::CreatePhotoUpdate
    601             }
    602             crate::FfiAddCommandType::CreateAsk => {
    603                 tera_core::runtime::product_surface::AddCommandType::CreateAsk
    604             }
    605             crate::FfiAddCommandType::CreateEvent => {
    606                 tera_core::runtime::product_surface::AddCommandType::CreateEvent
    607             }
    608             crate::FfiAddCommandType::CreateFoodAvailability => {
    609                 tera_core::runtime::product_surface::AddCommandType::CreateFoodAvailability
    610             }
    611         };
    612         let card_id = tera_core::runtime::product_surface::CardId::parse(&input.target_card_id)
    613             .map_err(|_| TeraAppError::invalid_argument("invalid_card_id"))?;
    614         let status = self
    615             .inner
    616             .phase1_save_retraction_draft(
    617                 decoded_id,
    618                 command_type,
    619                 card_id,
    620                 &input.target_event_id,
    621                 input.target_kind,
    622                 input.target_address.as_deref(),
    623                 &input.reason,
    624                 authored_at_unix_s,
    625                 persisted_at_unix_ms,
    626             )
    627             .await
    628             .map_err(TeraAppError::from)?;
    629         self.subscriptions
    630             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    631         Ok(status.into())
    632     }
    633 
    634     pub async fn phase1_draft_status(
    635         &self,
    636         draft_id: String,
    637     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    638         self.inner
    639             .phase1_draft_status(decode_id(&draft_id, "invalid_draft_id")?)
    640             .await
    641             .map(Into::into)
    642             .map_err(Into::into)
    643     }
    644 
    645     pub async fn phase1_draft_heads(
    646         &self,
    647         limit: u16,
    648     ) -> Result<Vec<FfiDraftStatusRecord>, TeraAppError> {
    649         self.inner
    650             .phase1_draft_heads(limit)
    651             .await
    652             .map(|values| values.into_iter().map(Into::into).collect())
    653             .map_err(Into::into)
    654     }
    655 
    656     pub async fn phase1_queue_draft(
    657         &self,
    658         draft_id: String,
    659         expected_revision: u64,
    660         policy: FfiQueuePolicyRecord,
    661         queued_at_unix_ms: u64,
    662     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    663         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    664         let status = self
    665             .inner
    666             .phase1_queue_draft(
    667                 decoded_id,
    668                 expected_revision,
    669                 policy.try_into()?,
    670                 queued_at_unix_ms,
    671             )
    672             .await
    673             .map_err(TeraAppError::from)?;
    674         self.subscriptions
    675             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    676         Ok(status.into())
    677     }
    678 
    679     /// Queues with the Rust-owned active relay and settlement policy.
    680     pub async fn phase1_queue_add_intent(
    681         &self,
    682         draft_id: String,
    683         expected_revision: u64,
    684     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    685         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    686         let intent =
    687             Phase1QueueIntent::new(decoded_id, expected_revision).map_err(TeraAppError::from)?;
    688         let status = self
    689             .inner
    690             .phase1_queue_add_intent(intent)
    691             .await
    692             .map_err(TeraAppError::from)?;
    693         self.subscriptions
    694             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    695         Ok(status.into())
    696     }
    697 
    698     pub async fn phase1_recover_draft_queue(
    699         &self,
    700         draft_id: String,
    701         recovered_at_unix_ms: u64,
    702     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    703         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    704         let status = self
    705             .inner
    706             .phase1_recover_draft_queue(decoded_id, recovered_at_unix_ms)
    707             .await
    708             .map_err(TeraAppError::from)?;
    709         self.subscriptions
    710             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    711         Ok(status.into())
    712     }
    713 
    714     pub async fn phase1_recover_add_intent(
    715         &self,
    716         draft_id: String,
    717     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    718         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    719         let status = self
    720             .inner
    721             .phase1_recover_add_intent(decoded_id)
    722             .await
    723             .map_err(TeraAppError::from)?;
    724         self.subscriptions
    725             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    726         Ok(status.into())
    727     }
    728 
    729     pub async fn phase1_sign_queued_draft(
    730         &self,
    731         draft_id: String,
    732         expected_revision: u64,
    733     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    734         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    735         let status = self
    736             .inner
    737             .phase1_sign_queued_draft(decoded_id, expected_revision)
    738             .await
    739             .map_err(TeraAppError::from)?;
    740         self.subscriptions
    741             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    742         Ok(status.into())
    743     }
    744 
    745     pub async fn phase1_advance_draft(
    746         &self,
    747         draft_id: String,
    748         expected_revision: u64,
    749     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    750         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    751         let status = self
    752             .inner
    753             .phase1_advance_draft(decoded_id, expected_revision)
    754             .await
    755             .map_err(TeraAppError::from)?;
    756         self.subscriptions
    757             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    758         Ok(status.into())
    759     }
    760 
    761     pub async fn phase1_upload_draft_media(
    762         &self,
    763         input: FfiBlossomUploadInput,
    764     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    765         if input.schema_version != crate::MOBILE_FFI_SCHEMA_VERSION {
    766             return Err(TeraAppError::invalid_argument("unsupported_schema_version"));
    767         }
    768         let draft_id = decode_id(&input.draft_id, "invalid_draft_id")?;
    769         let operation_id = decode_id(&input.operation_id, "invalid_operation_id")?;
    770         let artifact_id = decode_id(&input.artifact_id, "invalid_artifact_id")?;
    771         let media = PreparedMedia::try_from(input.media)?;
    772         let request = media.upload_request(input.verified_at_unix_ms)?;
    773         let content = radroots_blossom::authorization::AuthorizationContent::parse(
    774             &input.authorization_content,
    775         )
    776         .map_err(|_| TeraAppError::invalid_argument("invalid_blossom_authorization"))?;
    777         let status = self
    778             .inner
    779             .phase1_upload_draft_media(
    780                 draft_id,
    781                 input.expected_revision,
    782                 request,
    783                 content,
    784                 input.authorization_created_at_unix_s,
    785                 input.authorization_lifetime_seconds,
    786                 operation_id,
    787                 artifact_id,
    788                 input.signing_deadline_unix_ms,
    789                 input.signing_cancellation.core(),
    790                 radroots_sdk::transport::BlossomCancellation::default(),
    791                 input.updated_at_unix_ms,
    792             )
    793             .await
    794             .map_err(TeraAppError::from)?;
    795         self.subscriptions
    796             .notify(FfiRuntimeChangeKind::Media, Some(input.draft_id.clone()));
    797         self.subscriptions
    798             .notify(FfiRuntimeChangeKind::Drafts, Some(input.draft_id));
    799         Ok(status.into())
    800     }
    801 
    802     /// Runs a Rust-planned BUD-11/BUD-02/BUD-01 upload attempt. The host
    803     /// supplies only the selected bounded file handle and draft revision.
    804     pub async fn phase1_upload_add_media_intent(
    805         &self,
    806         input: FfiBlossomUploadIntent,
    807     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    808         if input.schema_version != crate::MOBILE_FFI_SCHEMA_VERSION {
    809             return Err(TeraAppError::invalid_argument("unsupported_schema_version"));
    810         }
    811         let draft_id = decode_id(&input.draft_id, "invalid_draft_id")?;
    812         let intent = PreparedMedia::try_from(input.media)?
    813             .into_upload_intent(draft_id, input.expected_revision)?;
    814         let status = self
    815             .inner
    816             .phase1_upload_add_media_intent(intent)
    817             .await
    818             .map_err(TeraAppError::from)?;
    819         self.subscriptions
    820             .notify(FfiRuntimeChangeKind::Media, Some(input.draft_id.clone()));
    821         self.subscriptions
    822             .notify(FfiRuntimeChangeKind::Drafts, Some(input.draft_id));
    823         Ok(status.into())
    824     }
    825 
    826     /// Persists the upload transition before returning an immutable native
    827     /// background-transfer job.
    828     pub async fn phase1_prepare_add_media_background(
    829         &self,
    830         input: crate::FfiBlossomUploadIntent,
    831     ) -> Result<crate::FfiNativeUploadJobRecord, TeraAppError> {
    832         if input.schema_version != crate::MOBILE_FFI_SCHEMA_VERSION {
    833             return Err(TeraAppError::invalid_argument("unsupported_schema_version"));
    834         }
    835         let draft_id = decode_id(&input.draft_id, "invalid_draft_id")?;
    836         let intent = PreparedMedia::try_from(input.media)?
    837             .into_upload_intent(draft_id, input.expected_revision)?;
    838         let (status, job) = self
    839             .inner
    840             .phase1_prepare_native_upload(intent)
    841             .await
    842             .map_err(TeraAppError::from)?;
    843         self.subscriptions
    844             .notify(FfiRuntimeChangeKind::Media, Some(input.draft_id.clone()));
    845         self.subscriptions
    846             .notify(FfiRuntimeChangeKind::Drafts, Some(input.draft_id));
    847         Ok(crate::FfiNativeUploadJobRecord {
    848             schema_version: crate::UPLOAD_OUTPUT_FFI_SCHEMA_VERSION,
    849             operation_id: hex::encode(job.operation_id()),
    850             draft: status.into(),
    851             remote_url: job.remote_url().to_owned(),
    852             upload_url: job.upload_url().to_owned(),
    853             authorization_header: job.authorization_header().to_owned(),
    854             expected_sha256: job.expected_sha256().to_owned(),
    855             media_type: job.media_type().to_owned(),
    856             byte_size: job.byte_size(),
    857         })
    858     }
    859 
    860     /// Accepts only bounded native HTTP evidence; Rust performs descriptor and
    861     /// exact-byte retrieval verification before advancing durable state.
    862     pub async fn phase1_complete_add_media_background(
    863         &self,
    864         input: crate::FfiNativeUploadCompletionInput,
    865     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    866         if input.schema_version != crate::MOBILE_FFI_SCHEMA_VERSION
    867             || input.response_body.len() > 16_384
    868         {
    869             return Err(TeraAppError::invalid_argument(
    870                 "invalid_native_upload_completion",
    871             ));
    872         }
    873         let draft_id = decode_id(&input.draft_id, "invalid_draft_id")?;
    874         let intent = PreparedMedia::try_from(input.media)?
    875             .into_upload_intent(draft_id, input.expected_revision)?;
    876         let status = self
    877             .inner
    878             .phase1_complete_native_upload(
    879                 intent,
    880                 input.status_code,
    881                 input.response_media_type.as_deref(),
    882                 input.response_content_encoding.as_deref(),
    883                 input.response_body.as_slice(),
    884             )
    885             .await
    886             .map_err(TeraAppError::from)?;
    887         self.subscriptions
    888             .notify(FfiRuntimeChangeKind::Media, Some(input.draft_id.clone()));
    889         self.subscriptions
    890             .notify(FfiRuntimeChangeKind::Drafts, Some(input.draft_id));
    891         Ok(status.into())
    892     }
    893 
    894     pub async fn phase1_cancel_draft(
    895         &self,
    896         draft_id: String,
    897         expected_revision: u64,
    898         cancelled_at_unix_ms: u64,
    899     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    900         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    901         let status = self
    902             .inner
    903             .phase1_cancel_draft(decoded_id, expected_revision, cancelled_at_unix_ms)
    904             .await
    905             .map_err(TeraAppError::from)?;
    906         self.subscriptions
    907             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    908         Ok(status.into())
    909     }
    910 
    911     pub async fn phase1_cancel_add_intent(
    912         &self,
    913         draft_id: String,
    914         expected_revision: u64,
    915     ) -> Result<FfiDraftStatusRecord, TeraAppError> {
    916         let decoded_id = decode_id(&draft_id, "invalid_draft_id")?;
    917         let status = self
    918             .inner
    919             .phase1_cancel_add_intent(decoded_id, expected_revision)
    920             .await
    921             .map_err(TeraAppError::from)?;
    922         self.subscriptions
    923             .notify(FfiRuntimeChangeKind::Drafts, Some(draft_id));
    924         Ok(status.into())
    925     }
    926 
    927     pub async fn phase1_settings(&self) -> Result<FfiMobileSettingsRecord, TeraAppError> {
    928         self.inner
    929             .phase1_settings()
    930             .await
    931             .map(|settings| (&settings).into())
    932             .map_err(Into::into)
    933     }
    934 
    935     pub async fn phase1_apply_settings_to_runtime(
    936         &self,
    937     ) -> Result<FfiMobileSettingsRecord, TeraAppError> {
    938         let settings = self.inner.phase1_settings().await?;
    939         self.inner
    940             .configure_relay_preferences(settings.relays())
    941             .await
    942             .map_err(TeraAppError::from)?;
    943         self.inner
    944             .configure_blossom_preferences(settings.blossom())
    945             .await
    946             .map_err(TeraAppError::from)?;
    947         self.subscriptions
    948             .notify(FfiRuntimeChangeKind::Settings, None);
    949         Ok((&settings).into())
    950     }
    951 
    952     pub async fn phase1_replace_settings(
    953         &self,
    954         input: FfiReplaceSettingsRecord,
    955     ) -> Result<FfiSettingsTransitionRecord, TeraAppError> {
    956         let current = self.inner.phase1_settings().await?;
    957         let expected_revision = input.expected_revision;
    958         let next = input.apply(current)?;
    959         let transition = self
    960             .inner
    961             .phase1_replace_settings(ReplaceMobileSettings::new(expected_revision, next)?)
    962             .await?;
    963         self.subscriptions
    964             .notify(FfiRuntimeChangeKind::Settings, None);
    965         Ok(transition.into())
    966     }
    967 
    968     pub async fn phase1_apply_identity_command(
    969         &self,
    970         expected_revision: u64,
    971         command: FfiIdentityCommandRecord,
    972     ) -> Result<FfiSettingsTransitionRecord, TeraAppError> {
    973         let transition = self
    974             .inner
    975             .phase1_apply_identity_command(expected_revision, command.try_into()?)
    976             .await?;
    977         let identity_id = transition
    978             .settings
    979             .identity()
    980             .active_identity_id()
    981             .map(str::to_owned);
    982         self.subscriptions
    983             .notify(FfiRuntimeChangeKind::Identity, identity_id);
    984         Ok(transition.into())
    985     }
    986 
    987     pub async fn phase1_save_profile_metadata(
    988         &self,
    989         input: FfiProfileMetadataInputRecord,
    990     ) -> Result<FfiProfileStatusRecord, TeraAppError> {
    991         let blossom = self.inner.sdk_blossom_slot().map_err(TeraAppError::from)?;
    992         let status = self
    993             .inner
    994             .phase1_save_profile_metadata(input.command(blossom.as_ref())?)
    995             .await?;
    996         let operation_id = hex::encode(status.draft().draft_id().as_bytes());
    997         self.subscriptions
    998             .notify(FfiRuntimeChangeKind::Profile, Some(operation_id));
    999         Ok(status.into())
   1000     }
   1001 
   1002     pub async fn phase1_profile_status(
   1003         &self,
   1004         operation_id: String,
   1005     ) -> Result<FfiProfileStatusRecord, TeraAppError> {
   1006         self.inner
   1007             .phase1_profile_status(decode_id(&operation_id, "invalid_operation_id")?)
   1008             .await
   1009             .map(Into::into)
   1010             .map_err(Into::into)
   1011     }
   1012 
   1013     pub async fn phase1_advance_profile(
   1014         &self,
   1015         operation_id: String,
   1016     ) -> Result<FfiProfileStatusRecord, TeraAppError> {
   1017         let status = self
   1018             .inner
   1019             .phase1_advance_profile(decode_id(&operation_id, "invalid_operation_id")?)
   1020             .await?;
   1021         self.subscriptions
   1022             .notify(FfiRuntimeChangeKind::Profile, Some(operation_id));
   1023         Ok(status.into())
   1024     }
   1025 
   1026     pub async fn phase1_cancel_profile(
   1027         &self,
   1028         operation_id: String,
   1029         expected_revision: u64,
   1030     ) -> Result<FfiProfileStatusRecord, TeraAppError> {
   1031         let status = self
   1032             .inner
   1033             .phase1_cancel_profile(
   1034                 decode_id(&operation_id, "invalid_operation_id")?,
   1035                 expected_revision,
   1036             )
   1037             .await?;
   1038         self.subscriptions
   1039             .notify(FfiRuntimeChangeKind::Profile, Some(operation_id));
   1040         Ok(status.into())
   1041     }
   1042 
   1043     pub async fn phase1_save_revision_intent(
   1044         &self,
   1045         mut input: FfiRevisionInputRecord,
   1046     ) -> Result<FfiRevisionStatusRecord, TeraAppError> {
   1047         let target = input.target()?;
   1048         if input.replacement.identifier.is_none()
   1049             && matches!(
   1050                 input.replacement.command_type,
   1051                 crate::FfiAddCommandType::CreateEvent
   1052                     | crate::FfiAddCommandType::CreateFoodAvailability
   1053             )
   1054         {
   1055             input.replacement.identifier = Some(phase1_new_addressable_identifier());
   1056         }
   1057         let authored_at_unix_s = phase1_operation_now_unix_ms()? / 1_000;
   1058         let blossom = self.inner.sdk_blossom_slot().map_err(TeraAppError::from)?;
   1059         let (command, media, form) = input
   1060             .replacement
   1061             .command_media_and_form(authored_at_unix_s, blossom.as_ref())?;
   1062         let status = self
   1063             .inner
   1064             .prepare_revision_intent(
   1065                 decode_id(&input.request_id, "invalid_revision_request_id")?,
   1066                 Phase1ReviseIntent::new(target, command, media, form)?,
   1067             )
   1068             .await?;
   1069         let operation_id = hex::encode(status.replacement().draft().draft_id().as_bytes());
   1070         self.subscriptions
   1071             .notify(FfiRuntimeChangeKind::Drafts, Some(operation_id));
   1072         Ok(status.into())
   1073     }
   1074 
   1075     pub async fn phase1_revision_status(
   1076         &self,
   1077         operation_id: String,
   1078     ) -> Result<FfiRevisionStatusRecord, TeraAppError> {
   1079         self.inner
   1080             .phase1_revision_status(decode_id(&operation_id, "invalid_operation_id")?)
   1081             .await
   1082             .map(Into::into)
   1083             .map_err(Into::into)
   1084     }
   1085 
   1086     pub async fn phase1_advance_revision(
   1087         &self,
   1088         operation_id: String,
   1089     ) -> Result<FfiRevisionStatusRecord, TeraAppError> {
   1090         let status = self
   1091             .inner
   1092             .phase1_advance_revision(decode_id(&operation_id, "invalid_operation_id")?)
   1093             .await?;
   1094         self.subscriptions
   1095             .notify(FfiRuntimeChangeKind::Drafts, Some(operation_id));
   1096         Ok(status.into())
   1097     }
   1098 
   1099     pub async fn phase1_cancel_revision(
   1100         &self,
   1101         operation_id: String,
   1102     ) -> Result<FfiRevisionStatusRecord, TeraAppError> {
   1103         let status = self
   1104             .inner
   1105             .phase1_cancel_revision(decode_id(&operation_id, "invalid_operation_id")?)
   1106             .await?;
   1107         self.subscriptions
   1108             .notify(FfiRuntimeChangeKind::Drafts, Some(operation_id));
   1109         Ok(status.into())
   1110     }
   1111 
   1112     pub async fn phase1_retrieve_media(
   1113         &self,
   1114         context: FfiLocalNetworkRecord,
   1115         reference_fingerprint: String,
   1116         operation: Arc<FfiMediaOperation>,
   1117     ) -> Result<FfiVerifiedMediaArtifactRecord, TeraAppError> {
   1118         let context = self.local_network(context)?;
   1119         operation.claim()?;
   1120         let operation_id = operation.operation_id();
   1121         let settings = self.inner.phase1_settings().await?;
   1122         let policy = Phase1MediaCachePolicy::new(
   1123             settings.local_storage().media_cache_bytes(),
   1124             settings.local_storage().media_cache_artifacts(),
   1125         )
   1126         .map_err(|_| TeraAppError::invalid_argument("invalid_media_cache_policy"))?;
   1127         let artifact = self
   1128             .inner
   1129             .phase1_retrieve_media(
   1130                 &context,
   1131                 decode_reference_fingerprint(&reference_fingerprint)?,
   1132                 operation.id(),
   1133                 policy,
   1134                 operation.cancellation(),
   1135             )
   1136             .await
   1137             .map_err(|error| TeraAppError::from(error).with_operation_id(operation_id.clone()))?;
   1138         self.subscriptions.notify_context(
   1139             FfiRuntimeChangeKind::Media,
   1140             Some(&context),
   1141             Some(artifact.artifact_id().to_hex()),
   1142         );
   1143         Ok(FfiVerifiedMediaArtifactRecord::from_artifact(
   1144             artifact,
   1145             Some(operation_id),
   1146         ))
   1147     }
   1148 
   1149     pub async fn phase1_verified_media_artifact(
   1150         &self,
   1151         context: FfiLocalNetworkRecord,
   1152         artifact_id: String,
   1153     ) -> Result<Option<FfiVerifiedMediaArtifactRecord>, TeraAppError> {
   1154         let context = self.local_network(context)?;
   1155         self.inner
   1156             .phase1_verified_media_artifact(
   1157                 &context,
   1158                 decode_artifact_id(&artifact_id)?,
   1159                 phase1_operation_now_unix_ms()?,
   1160             )
   1161             .await
   1162             .map(|value| {
   1163                 value.map(|artifact| FfiVerifiedMediaArtifactRecord::from_artifact(artifact, None))
   1164             })
   1165             .map_err(Into::into)
   1166     }
   1167 
   1168     pub async fn phase1_media_cache_status(
   1169         &self,
   1170         context: FfiLocalNetworkRecord,
   1171     ) -> Result<FfiMediaCacheStatusRecord, TeraAppError> {
   1172         let context = self.local_network(context)?;
   1173         self.inner
   1174             .phase1_media_cache_status(&context)
   1175             .await
   1176             .map(Into::into)
   1177             .map_err(Into::into)
   1178     }
   1179 
   1180     pub async fn phase1_invalidate_media_artifact(
   1181         &self,
   1182         context: FfiLocalNetworkRecord,
   1183         artifact_id: String,
   1184     ) -> Result<bool, TeraAppError> {
   1185         let context = self.local_network(context)?;
   1186         let changed = self
   1187             .inner
   1188             .phase1_invalidate_media_artifact(&context, decode_artifact_id(&artifact_id)?)
   1189             .await?;
   1190         if changed {
   1191             self.subscriptions.notify_context(
   1192                 FfiRuntimeChangeKind::Media,
   1193                 Some(&context),
   1194                 Some(artifact_id),
   1195             );
   1196         }
   1197         Ok(changed)
   1198     }
   1199 
   1200     pub async fn phase1_invalidate_media_configuration(
   1201         &self,
   1202         context: FfiLocalNetworkRecord,
   1203         configuration_fingerprint: String,
   1204     ) -> Result<Vec<String>, TeraAppError> {
   1205         let context = self.local_network(context)?;
   1206         let removed = self
   1207             .inner
   1208             .phase1_invalidate_media_configuration(
   1209                 &context,
   1210                 decode_configuration(&configuration_fingerprint)?,
   1211             )
   1212             .await?;
   1213         self.subscriptions
   1214             .notify_context(FfiRuntimeChangeKind::Media, Some(&context), None);
   1215         Ok(removed.into_iter().map(|value| value.to_hex()).collect())
   1216     }
   1217 }
   1218 
   1219 impl TeraRuntime {
   1220     fn local_network(
   1221         &self,
   1222         context: FfiLocalNetworkRecord,
   1223     ) -> Result<tera_core::runtime::product_surface::LocalNetwork, TeraAppError> {
   1224         let profile = self.inner.sdk_relay_status()?.ok_or_else(|| {
   1225             TeraAppError::failure(
   1226                 "relay_profile_unavailable",
   1227                 "relay",
   1228                 true,
   1229                 &["configure_relay"],
   1230                 "The relay profile is unavailable.",
   1231             )
   1232         })?;
   1233         let relay_policy = match profile.profile.as_str() {
   1234             "public" => LocalNetworkRelayPolicy::Public,
   1235             "simulator_local" => LocalNetworkRelayPolicy::Simulator,
   1236             "device_development" => LocalNetworkRelayPolicy::Device,
   1237             _ => {
   1238                 return Err(TeraAppError::failure(
   1239                     "relay_profile_unsupported",
   1240                     "relay",
   1241                     false,
   1242                     &["configure_relay"],
   1243                     "The relay profile is unsupported.",
   1244                 ));
   1245             }
   1246         };
   1247         context.try_into_with_relay_policy(relay_policy)
   1248     }
   1249 }
   1250 
   1251 #[derive(Default)]
   1252 struct RuntimeOpenOptions {
   1253     local_backups: bool,
   1254     restore_guard: Option<tera_core::runtime::restore::ApplicationRestoreGuard>,
   1255 }
   1256 
   1257 async fn build_runtime(
   1258     application_support_directory: String,
   1259     public_key_hex: String,
   1260     source_generation_hex: String,
   1261     source_generation_created_at_unix_ms: u64,
   1262     protected_data: ProtectedDataAvailability,
   1263     host_signer: Option<Box<dyn TeraHostSigner>>,
   1264     options: RuntimeOpenOptions,
   1265 ) -> Result<TeraRuntime, TeraAppError> {
   1266     let store = tera_core::runtime::store::MobileUserStoreConfig::from_encoded(
   1267         application_support_directory,
   1268         public_key_hex.as_str(),
   1269         source_generation_hex.as_str(),
   1270         source_generation_created_at_unix_ms,
   1271         protected_data.into(),
   1272     )?;
   1273     let store = if options.local_backups {
   1274         store.with_local_backups()
   1275     } else {
   1276         store
   1277     };
   1278     let invalidations = tera_core::runtime::invalidation::RuntimeInvalidations::new(
   1279         store.public_key(),
   1280         store.source_generation(),
   1281         tera_core::runtime::invalidation::new_runtime_epoch(),
   1282     );
   1283     let has_host_signer = host_signer.is_some();
   1284     let mut builder = tera_core::runtime::builder::RuntimeBuilder::new(store);
   1285     if let Some(guard) = options.restore_guard {
   1286         builder = builder.restore_guard(guard);
   1287     }
   1288     if let Some(host_signer) = host_signer {
   1289         builder = builder.signer(Arc::new(HostSignerAdapter::new(host_signer)));
   1290     }
   1291     builder
   1292         .build()
   1293         .await
   1294         .map(|inner| TeraRuntime {
   1295             inner,
   1296             has_host_signer,
   1297             subscriptions: SubscriptionHub::new(invalidations),
   1298         })
   1299         .map_err(Into::into)
   1300 }