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_delegation.rs (36874B)


      1 use std::os::fd::AsRawFd;
      2 use std::sync::Arc;
      3 
      4 use tera_ffi::{
      5     FfiAddCommandType, FfiAddDraftInput, FfiBlossomAuthorityPreference,
      6     FfiBlossomEndpointAuthority, FfiBlossomHostKind, FfiBlossomPreferencesRecord,
      7     FfiBlossomUploadIntent, FfiCancellationPolicy, FfiDraftKind, FfiEventTimingKind,
      8     FfiIdentityCommandKind, FfiIdentityCommandRecord, FfiIdentityLockState, FfiLocalNetworkRecord,
      9     FfiLocalStoragePolicyRecord, FfiMediaNetworkPolicyRecord, FfiMediaOperation,
     10     FfiMobileNetworkEnvironment, FfiNativeUploadCompletionInput, FfiOutboxState,
     11     FfiPreparedMediaInput, FfiProfileMetadataInputRecord, FfiQueuePolicyRecord,
     12     FfiRelayAccessPreference, FfiRelayAccessRecord, FfiRelayPreferenceRecord,
     13     FfiRelayPreferencesRecord, FfiRelaySatisfaction, FfiReplaceSettingsRecord,
     14     FfiRetractionDraftInput, FfiRevisionInputRecord, FfiRevisionPhase, FfiTodayCardType,
     15     FfiTodayProjectionUpdate, MOBILE_FFI_SCHEMA_VERSION, TeraAppError,
     16 };
     17 
     18 #[path = "support/retraction.rs"]
     19 mod retraction;
     20 mod support;
     21 
     22 #[tokio::test]
     23 async fn context_aggregate_admission_and_debug_remain_typed_at_native_boundary() {
     24     let (_root, runtime) = support::runtime().await;
     25     let context = FfiLocalNetworkRecord {
     26         schema_version: MOBILE_FFI_SCHEMA_VERSION,
     27         id: "nearby".into(),
     28         label: "private-label-sentinel".into(),
     29         relay_urls: vec!["wss://relay.example".into()],
     30         locality: Some("private-location-sentinel".into()),
     31         followed_authors: (0..4096).map(|index| format!("{index:064x}")).collect(),
     32         generation: 7,
     33     };
     34     assert_eq!(
     35         runtime.phase1_local_network(context.clone()).unwrap(),
     36         context
     37     );
     38     let debug = format!("{context:?}");
     39     for sentinel in [
     40         &context.id,
     41         &context.label,
     42         &context.relay_urls[0],
     43         context.locality.as_ref().unwrap(),
     44         &context.followed_authors[0],
     45     ] {
     46         assert!(!debug.contains(sentinel));
     47     }
     48     assert!(debug.contains("followed_author_count: 4096"));
     49     assert!(debug.contains("generation: 7"));
     50     let mut over = context.clone();
     51     over.followed_authors.push(format!("{:064x}", 4096));
     52     let mut duplicate = context.clone();
     53     duplicate.followed_authors = vec!["a".repeat(64), "a".repeat(64)];
     54     let mut malformed = context.clone();
     55     malformed.followed_authors = vec!["A".repeat(64)];
     56     let mut aggregate = context.clone();
     57     aggregate.followed_authors = vec!["x".repeat(262_145)];
     58     for invalid in [over, duplicate, malformed, aggregate] {
     59         let TeraAppError::Failure { report } = runtime
     60             .phase1_search(invalid, "carrot".into(), 20, 1_800_000_000, "UTC".into())
     61             .await
     62             .unwrap_err();
     63         assert_eq!(report.code, "invalid_local_network");
     64         assert!(!report.retryable);
     65         assert_eq!(report.recovery_actions, ["correct_input"]);
     66     }
     67     runtime.shutdown().await.unwrap();
     68     let TeraAppError::Failure { report } = runtime
     69         .phase1_search(context, "carrot".into(), 20, 1_800_000_000, "UTC".into())
     70         .await
     71         .unwrap_err();
     72     assert_eq!(report.code, "client_closed");
     73 }
     74 
     75 #[tokio::test]
     76 async fn search_byte_admission_preserves_typed_native_failure() {
     77     let (_root, runtime) = support::runtime().await;
     78     let context = FfiLocalNetworkRecord {
     79         schema_version: MOBILE_FFI_SCHEMA_VERSION,
     80         id: "nearby".to_owned(),
     81         label: "Nearby".to_owned(),
     82         relay_urls: vec!["wss://relay.example".to_owned()],
     83         locality: None,
     84         followed_authors: vec![],
     85         generation: 1,
     86     };
     87     runtime
     88         .phase1_refresh_today(
     89             context.clone(),
     90             1_800_000_000,
     91             FfiTodayProjectionUpdate::Rebuild,
     92         )
     93         .await
     94         .unwrap();
     95     for query in [
     96         "x".repeat(257),
     97         format!("{}a", "é".repeat(128)),
     98         format!("{}carrots", " ".repeat(1_048_576)),
     99         "x".repeat(1_048_576),
    100         "   ".to_owned(),
    101         "\ncarrots".to_owned(),
    102         "carrots\0".to_owned(),
    103         "İ".repeat(86),
    104     ] {
    105         let TeraAppError::Failure { report } = runtime
    106             .phase1_search(context.clone(), query, 20, 1_800_000_000, "UTC".to_owned())
    107             .await
    108             .unwrap_err();
    109         assert_eq!(report.code, "today_invalid_request");
    110         assert!(!report.retryable);
    111         assert_eq!(report.recovery_actions, ["correct_input"]);
    112     }
    113     for query in [
    114         "x".repeat(256),
    115         "é".repeat(128),
    116         format!("{}a", "İ".repeat(85)),
    117         "  CARROT  ".to_owned(),
    118     ] {
    119         assert!(
    120             runtime
    121                 .phase1_search(context.clone(), query, 20, 1_800_000_000, "UTC".to_owned())
    122                 .await
    123                 .unwrap()
    124                 .is_empty()
    125         );
    126     }
    127     runtime.shutdown().await.unwrap();
    128     let TeraAppError::Failure { report } = runtime
    129         .phase1_search(
    130             context,
    131             "x".repeat(257),
    132             20,
    133             1_800_000_000,
    134             "UTC".to_owned(),
    135         )
    136         .await
    137         .unwrap_err();
    138     assert_eq!(report.code, "client_closed");
    139 }
    140 
    141 #[tokio::test]
    142 async fn native_boundary_delegates_the_complete_core_surface() {
    143     let (_root, runtime) = support::runtime().await;
    144     assert!(runtime.uptime_millis() >= 0);
    145     assert!(runtime.info_json().contains("sdk"));
    146     runtime.set_app_info_platform(
    147         Some("ios".to_owned()),
    148         Some("org.radroots.app".to_owned()),
    149         Some("0.1.0-alpha".to_owned()),
    150         Some("1".to_owned()),
    151         Some("0123456789abcdef0123456789abcdef01234567".to_owned()),
    152     );
    153     assert_eq!(
    154         runtime.info().app.platform.expect("platform").platform,
    155         Some("ios".to_owned())
    156     );
    157     assert!(!runtime.sdk_capabilities().is_empty());
    158     assert_eq!(
    159         runtime.sdk_storage_status().await.expect("storage").backend,
    160         "sqlite"
    161     );
    162 
    163     let public = runtime
    164         .sdk_relay_status()
    165         .expect("relay status")
    166         .expect("default public profile");
    167     assert_eq!(public.profile, "public");
    168     assert_eq!(public.state, "configured");
    169     assert_eq!(public.read_availability, "unavailable");
    170     assert_eq!(public.write_availability, "unavailable");
    171     assert_eq!(public.relays.len(), 1);
    172     assert_eq!(public.relays[0].access, FfiRelayAccessRecord::ReadWrite);
    173     assert_eq!(public.relays[0].read_state, "unobserved");
    174     assert_eq!(public.relays[0].write_state, "unobserved");
    175 
    176     runtime
    177         .configure_public_relays(vec!["wss://write.example".to_owned()])
    178         .await
    179         .expect("public relays");
    180     let public = runtime
    181         .sdk_relay_status()
    182         .expect("relay status")
    183         .expect("public profile");
    184     assert_eq!(public.relays.len(), 1);
    185     assert_eq!(public.relays[0].relay_url, "wss://write.example");
    186     assert_eq!(public.relays[0].access, FfiRelayAccessRecord::ReadWrite);
    187     assert!(
    188         runtime
    189             .configure_public_relays(vec!["ws://127.0.0.1:7447".to_owned()])
    190             .await
    191             .is_err()
    192     );
    193 
    194     let settings = runtime.phase1_settings().await.expect("settings");
    195     runtime
    196         .phase1_replace_settings(FfiReplaceSettingsRecord {
    197             schema_version: MOBILE_FFI_SCHEMA_VERSION,
    198             expected_revision: settings.revision,
    199             relays: FfiRelayPreferencesRecord {
    200                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    201                 environment: FfiMobileNetworkEnvironment::Public,
    202                 endpoints: vec![
    203                     FfiRelayPreferenceRecord {
    204                         schema_version: MOBILE_FFI_SCHEMA_VERSION,
    205                         url: "wss://read.example".to_owned(),
    206                         access: FfiRelayAccessPreference::ReadOnly,
    207                     },
    208                     FfiRelayPreferenceRecord {
    209                         schema_version: MOBILE_FFI_SCHEMA_VERSION,
    210                         url: "wss://write.example".to_owned(),
    211                         access: FfiRelayAccessPreference::ReadWrite,
    212                     },
    213                 ],
    214             },
    215             blossom: FfiBlossomPreferencesRecord {
    216                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    217                 environment: FfiMobileNetworkEnvironment::Public,
    218                 authority: FfiBlossomAuthorityPreference::PublicWebPki,
    219                 primary_origin: "https://media.example".to_owned(),
    220                 fallback_origins: vec![],
    221             },
    222             media_network: FfiMediaNetworkPolicyRecord {
    223                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    224                 allow_cellular_downloads: true,
    225                 allow_cellular_uploads: true,
    226                 allow_background_transfers: true,
    227             },
    228             local_storage: FfiLocalStoragePolicyRecord {
    229                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    230                 media_cache_bytes: 256 * 1024 * 1024,
    231                 media_cache_artifacts: 1024,
    232             },
    233         })
    234         .await
    235         .expect("replace settings");
    236     runtime
    237         .phase1_apply_settings_to_runtime()
    238         .await
    239         .expect("apply settings");
    240     let applied = runtime
    241         .sdk_relay_status()
    242         .expect("relay status")
    243         .expect("applied settings profile");
    244     assert_eq!(applied.relays.len(), 2);
    245     assert_eq!(applied.relays[0].access, FfiRelayAccessRecord::ReadOnly);
    246     assert_eq!(applied.relays[1].access, FfiRelayAccessRecord::ReadWrite);
    247 
    248     runtime
    249         .configure_simulator_relays(vec!["ws://127.0.0.1:7447".to_owned()])
    250         .await
    251         .expect("simulator relays");
    252     let simulator = runtime
    253         .sdk_relay_status()
    254         .expect("relay status")
    255         .expect("simulator profile");
    256     assert_eq!(simulator.profile, "simulator_local");
    257     assert_eq!(simulator.relays.len(), 1);
    258     assert_eq!(simulator.relays[0].access, FfiRelayAccessRecord::ReadWrite);
    259     assert!(
    260         runtime
    261             .phase1_local_network(FfiLocalNetworkRecord {
    262                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    263                 id: "simulator".to_owned(),
    264                 label: "Simulator".to_owned(),
    265                 relay_urls: vec!["ws://127.0.0.1:7447".to_owned()],
    266                 locality: None,
    267                 followed_authors: vec![],
    268                 generation: 1,
    269             })
    270             .is_ok()
    271     );
    272     assert!(
    273         runtime
    274             .configure_simulator_relays(vec!["wss://relay.example".to_owned()])
    275             .await
    276             .is_err()
    277     );
    278 
    279     runtime
    280         .configure_device_relays(vec!["wss://10.0.0.5:7447".to_owned()])
    281         .await
    282         .expect("device relays");
    283     let device = runtime
    284         .sdk_relay_status()
    285         .expect("relay status")
    286         .expect("device profile");
    287     assert_eq!(device.profile, "device_development");
    288     assert_eq!(device.relays.len(), 1);
    289     assert_eq!(device.relays[0].relay_url, "wss://10.0.0.5:7447");
    290     assert_eq!(device.relays[0].access, FfiRelayAccessRecord::ReadWrite);
    291     assert!(
    292         runtime
    293             .configure_device_relays(vec!["wss://127.0.0.1:7447".to_owned()])
    294             .await
    295             .is_err()
    296     );
    297 
    298     runtime
    299         .configure_blossom(
    300             FfiBlossomHostKind::PhysicalDevice,
    301             FfiBlossomEndpointAuthority::PublicWebPki,
    302             "https://media.example".to_owned(),
    303             vec!["https://fallback.example".to_owned()],
    304         )
    305         .await
    306         .expect("public Blossom");
    307     let blossom = runtime
    308         .sdk_blossom_configuration()
    309         .expect("Blossom configuration")
    310         .expect("configured Blossom");
    311     assert_eq!(blossom.host_kind, "physical_device");
    312     assert_eq!(blossom.endpoint_authority, "public_webpki");
    313     assert_eq!(blossom.primary_origin, "https://media.example");
    314     assert_eq!(blossom.fallback_origins, ["https://fallback.example"]);
    315     assert_eq!(blossom.config_fingerprint.len(), 64);
    316     let evidence = runtime
    317         .sdk_blossom_evidence()
    318         .expect("Blossom evidence")
    319         .expect("configured evidence");
    320     assert_eq!(evidence.schema_version, 2);
    321     assert_eq!(evidence.origin, "https://media.example");
    322     assert_eq!(evidence.config_fingerprint, blossom.config_fingerprint);
    323     assert_eq!(evidence.state, "configured_unobserved");
    324     assert_eq!(evidence.transport_security, "public_webpki");
    325     assert!(evidence.observed_at_unix_ms.is_none());
    326     assert!(evidence.error_code.is_none());
    327     assert!(evidence.server_error_code.is_none());
    328     runtime
    329         .configure_blossom(
    330             FfiBlossomHostKind::Simulator,
    331             FfiBlossomEndpointAuthority::LoopbackDevelopment,
    332             "http://127.0.0.1:3100".to_owned(),
    333             vec![],
    334         )
    335         .await
    336         .expect("simulator Blossom");
    337     runtime
    338         .configure_blossom(
    339             FfiBlossomHostKind::Simulator,
    340             FfiBlossomEndpointAuthority::LoopbackDevelopment,
    341             "http://127.0.0.1:1".to_owned(),
    342             vec![],
    343         )
    344         .await
    345         .expect("unavailable simulator Blossom");
    346     assert!(runtime.probe_blossom().await.is_err());
    347     runtime
    348         .configure_blossom(
    349             FfiBlossomHostKind::PhysicalDevice,
    350             FfiBlossomEndpointAuthority::PrivateNetworkDevelopment,
    351             "https://10.0.0.5:3100".to_owned(),
    352             vec![],
    353         )
    354         .await
    355         .expect("device Blossom");
    356 
    357     assert_eq!(
    358         runtime
    359             .phase1_card_add_parity()
    360             .into_iter()
    361             .map(|item| item.card_type)
    362             .collect::<Vec<_>>(),
    363         vec![
    364             FfiTodayCardType::Update,
    365             FfiTodayCardType::PhotoUpdate,
    366             FfiTodayCardType::Ask,
    367             FfiTodayCardType::Event,
    368             FfiTodayCardType::FoodAvailability,
    369         ]
    370     );
    371     assert_eq!(
    372         runtime
    373             .phase1_add_schemas()
    374             .into_iter()
    375             .map(|schema| schema.command_type)
    376             .collect::<Vec<_>>(),
    377         vec![
    378             FfiAddCommandType::CreateUpdate,
    379             FfiAddCommandType::CreatePhotoUpdate,
    380             FfiAddCommandType::CreateAsk,
    381             FfiAddCommandType::CreateEvent,
    382             FfiAddCommandType::CreateFoodAvailability,
    383         ]
    384     );
    385     let parity = runtime.phase1_card_add_parity();
    386     let schemas = runtime.phase1_add_schemas();
    387     assert_eq!(parity.len(), 5);
    388     for (index, item) in parity.iter().enumerate() {
    389         assert_eq!(item.command_type, schemas[index].command_type);
    390     }
    391     assert_eq!(
    392         schemas[1]
    393             .fields
    394             .iter()
    395             .find(|field| field.id == "media")
    396             .and_then(|field| field.max_items),
    397         Some(20)
    398     );
    399     assert_eq!(
    400         schemas[3]
    401             .fields
    402             .iter()
    403             .find(|field| field.id == "media")
    404             .and_then(|field| field.max_items),
    405         Some(1)
    406     );
    407     let local_network = runtime
    408         .phase1_local_network(FfiLocalNetworkRecord {
    409             schema_version: MOBILE_FFI_SCHEMA_VERSION,
    410             id: "nearby".to_owned(),
    411             label: "Near me".to_owned(),
    412             relay_urls: vec!["ws://192.168.1.7:7447".to_owned()],
    413             locality: Some("u10h".to_owned()),
    414             followed_authors: vec!["a".repeat(64)],
    415             generation: 1,
    416         })
    417         .expect("valid local network");
    418     assert_eq!(local_network.id, "nearby");
    419     assert!(
    420         runtime
    421             .phase1_local_network(FfiLocalNetworkRecord {
    422                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    423                 id: "public-host".to_owned(),
    424                 label: "Public host".to_owned(),
    425                 relay_urls: vec!["wss://relay.example".to_owned()],
    426                 locality: None,
    427                 followed_authors: vec![],
    428                 generation: 1,
    429             })
    430             .is_err()
    431     );
    432     let refresh = runtime
    433         .phase1_refresh_today(
    434             local_network.clone(),
    435             1_800_000_001,
    436             FfiTodayProjectionUpdate::Incremental,
    437         )
    438         .await
    439         .expect("empty Today refresh");
    440     assert_eq!(refresh.update, FfiTodayProjectionUpdate::Incremental);
    441     assert_eq!(refresh.source_events, 0);
    442     assert_eq!(refresh.visible_cards, 0);
    443     assert!(refresh.content_generation > 0);
    444     let today = runtime
    445         .phase1_today_page(
    446             local_network.clone(),
    447             20,
    448             Some(1_800_000_001),
    449             None,
    450             Some("UTC".to_owned()),
    451         )
    452         .await
    453         .expect("empty Today page");
    454     assert!(today.items.is_empty());
    455     assert!(today.next_cursor.is_none());
    456     assert!(
    457         runtime
    458             .phase1_today_page(local_network.clone(), 20, None, None, None)
    459             .await
    460             .is_err()
    461     );
    462     assert!(
    463         runtime
    464             .phase1_today_page(
    465                 local_network.clone(),
    466                 20,
    467                 Some(1_800_000_001),
    468                 Some("opaque".to_owned()),
    469                 Some("UTC".to_owned())
    470             )
    471             .await
    472             .is_err()
    473     );
    474     assert!(
    475         runtime
    476             .phase1_search(
    477                 local_network.clone(),
    478                 "carrots".to_owned(),
    479                 20,
    480                 1_800_000_001,
    481                 "UTC".to_owned()
    482             )
    483             .await
    484             .expect("empty search")
    485             .is_empty()
    486     );
    487     let me = runtime
    488         .phase1_me(local_network.clone(), 1_800_000_001, "UTC".to_owned())
    489         .await
    490         .expect("Me snapshot");
    491     assert_eq!(me.public_key, support::PUBLIC_KEY);
    492 
    493     let add = FfiAddDraftInput {
    494         schema_version: MOBILE_FFI_SCHEMA_VERSION,
    495         command_type: FfiAddCommandType::CreateUpdate,
    496         content: "Farm stand opens at noon".to_owned(),
    497         identifier: None,
    498         title: None,
    499         summary: None,
    500         location: None,
    501         event_timing: None,
    502         event_start_date: None,
    503         event_end_date: None,
    504         event_start_unix_s: None,
    505         event_end_unix_s: None,
    506         event_timezone: None,
    507         price_amount: None,
    508         currency: None,
    509         unit: None,
    510         quantity: None,
    511         food_published_at_unix_s: None,
    512         food_status: None,
    513         media: Vec::new(),
    514     };
    515     runtime
    516         .phase1_validate_add_draft(add.clone(), 1_800_000_001)
    517         .expect("valid draft");
    518     let saved = runtime
    519         .phase1_save_add_intent(add.clone(), None, None)
    520         .await
    521         .expect("saved draft");
    522     let draft_id = saved.draft_id.clone();
    523     assert_eq!(draft_id.len(), 32);
    524     assert_eq!(saved.state, FfiOutboxState::Draft);
    525     assert_eq!(saved.kind, FfiDraftKind::Add);
    526     assert_eq!(
    527         saved.form.as_ref().map(|form| form.content.as_str()),
    528         Some("Farm stand opens at noon")
    529     );
    530     assert_eq!(
    531         runtime
    532             .phase1_draft_status(draft_id.clone())
    533             .await
    534             .expect("draft status")
    535             .revision,
    536         saved.revision
    537     );
    538     assert_eq!(
    539         runtime
    540             .phase1_draft_heads(10)
    541             .await
    542             .expect("draft heads")
    543             .len(),
    544         1
    545     );
    546     let queued = runtime
    547         .phase1_queue_add_intent(draft_id.clone(), saved.revision)
    548         .await
    549         .expect("queued draft");
    550     assert_eq!(queued.state, FfiOutboxState::Queued);
    551     let recovered = runtime
    552         .phase1_recover_add_intent(draft_id.clone())
    553         .await
    554         .expect("recovered queue");
    555     assert_eq!(recovered.revision, queued.revision);
    556     let cancelled = runtime
    557         .phase1_cancel_add_intent(draft_id.clone(), recovered.revision)
    558         .await
    559         .expect("cancelled draft");
    560     assert_eq!(cancelled.state, FfiOutboxState::Cancelled);
    561     assert!(
    562         runtime
    563             .phase1_save_add_intent(
    564                 FfiAddDraftInput {
    565                     schema_version: MOBILE_FFI_SCHEMA_VERSION,
    566                     command_type: FfiAddCommandType::CreateEvent,
    567                     content: "Market opens Saturday".to_owned(),
    568                     identifier: None,
    569                     title: Some("Saturday market".to_owned()),
    570                     summary: Some("Weekly market".to_owned()),
    571                     location: Some("Town square".to_owned()),
    572                     event_timing: Some(FfiEventTimingKind::AllDay),
    573                     event_start_date: Some("2027-01-02".to_owned()),
    574                     event_end_date: None,
    575                     event_start_unix_s: None,
    576                     event_end_unix_s: None,
    577                     event_timezone: None,
    578                     price_amount: None,
    579                     currency: None,
    580                     unit: None,
    581                     quantity: None,
    582                     food_published_at_unix_s: None,
    583                     food_status: None,
    584                     media: Vec::new(),
    585                 },
    586                 None,
    587                 Some(1),
    588             )
    589             .await
    590             .is_err()
    591     );
    592     assert!(
    593         runtime
    594             .phase1_advance_draft(draft_id.clone(), cancelled.revision)
    595             .await
    596             .is_err()
    597     );
    598 
    599     runtime.shutdown().await.unwrap();
    600     let (source_card, source_event) = retraction::seed(_root.path(), add).await;
    601     let runtime = tera_ffi::TeraRuntime::open(
    602         _root.path().to_string_lossy().into_owned(),
    603         support::PUBLIC_KEY.into(),
    604         support::GENERATION.into(),
    605         1_800_000_000_000,
    606         tera_ffi::ProtectedDataAvailability::Available,
    607     )
    608     .await
    609     .unwrap();
    610     runtime
    611         .configure_device_relays(vec!["wss://10.0.0.5:7447".to_owned()])
    612         .await
    613         .unwrap();
    614     runtime
    615         .configure_blossom(
    616             FfiBlossomHostKind::PhysicalDevice,
    617             FfiBlossomEndpointAuthority::PrivateNetworkDevelopment,
    618             "https://10.0.0.5:3100".to_owned(),
    619             vec![],
    620         )
    621         .await
    622         .unwrap();
    623     let retraction_id = "0a".repeat(16);
    624     let retraction_input = FfiRetractionDraftInput {
    625         schema_version: MOBILE_FFI_SCHEMA_VERSION,
    626         command_type: FfiAddCommandType::CreateUpdate,
    627         target_card_id: source_card.clone(),
    628         target_event_id: source_event.clone(),
    629         target_kind: 1,
    630         target_address: None,
    631         reason: "Replaced with a corrected copy".to_owned(),
    632     };
    633     let mut unsupported_retraction = retraction_input.clone();
    634     unsupported_retraction.schema_version += 1;
    635     assert_eq!(
    636         runtime
    637             .phase1_save_retraction_draft(
    638                 retraction_id.clone(),
    639                 unsupported_retraction,
    640                 1_800_000_005,
    641                 1_800_000_005_000,
    642             )
    643             .await
    644             .expect_err("unsupported retraction schema")
    645             .report()
    646             .code,
    647         "unsupported_schema_version"
    648     );
    649     let retraction = runtime
    650         .phase1_save_retraction_draft(
    651             retraction_id.clone(),
    652             retraction_input,
    653             1_800_000_005,
    654             1_800_000_005_000,
    655         )
    656         .await
    657         .expect("saved retraction");
    658     assert_eq!(retraction.kind, FfiDraftKind::Retraction);
    659     assert_eq!(retraction.card_id, source_card);
    660     assert!(retraction.form.is_none());
    661     let queued_retraction = runtime
    662         .phase1_queue_draft(
    663             retraction_id.clone(),
    664             retraction.revision,
    665             FfiQueuePolicyRecord {
    666                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    667                 relay_urls: vec!["wss://write.example".to_owned()],
    668                 satisfaction: FfiRelaySatisfaction::AllAccepted,
    669                 delivery_deadline_unix_ms: 1_800_100_000_000,
    670                 cancellation: FfiCancellationPolicy::LocalCooperative,
    671             },
    672             1_800_000_006_000,
    673         )
    674         .await
    675         .expect("queued retraction");
    676     let cancelled_retraction = runtime
    677         .phase1_cancel_draft(retraction_id, queued_retraction.revision, 1_800_000_007_000)
    678         .await
    679         .expect("cancelled retraction");
    680     assert_eq!(cancelled_retraction.state, FfiOutboxState::Cancelled);
    681 
    682     let upload_file = tempfile::tempfile().expect("media file");
    683     upload_file.set_len(1).expect("bounded media");
    684     let upload = FfiBlossomUploadIntent {
    685         schema_version: MOBILE_FFI_SCHEMA_VERSION + 1,
    686         draft_id,
    687         expected_revision: cancelled.revision,
    688         media: FfiPreparedMediaInput {
    689             schema_version: tera_ffi::PREPARED_MEDIA_FFI_SCHEMA_VERSION,
    690             opaque_reference: "media:unused".to_owned(),
    691             file: Arc::new(
    692                 tera_ffi::FfiMediaFile::new(upload_file.as_raw_fd() as u64, 1)
    693                     .expect("admitted media"),
    694             ),
    695             sha256: "00".repeat(32),
    696             media_type: "image/png".to_owned(),
    697             byte_size: 1,
    698             width: 1,
    699             height: 1,
    700             alt: "unused".to_owned(),
    701             prepared_at_unix_s: 1_800_000_000,
    702         },
    703     };
    704     let upload_error = runtime
    705         .phase1_upload_add_media_intent(upload.clone())
    706         .await
    707         .expect_err("unsupported upload schema");
    708     assert_eq!(upload_error.report().code, "unsupported_schema_version");
    709     assert_eq!(
    710         runtime
    711             .phase1_prepare_add_media_background(upload.clone())
    712             .await
    713             .expect_err("unsupported background upload schema")
    714             .report()
    715             .code,
    716         "unsupported_schema_version"
    717     );
    718     assert_eq!(
    719         runtime
    720             .phase1_complete_add_media_background(FfiNativeUploadCompletionInput {
    721                 schema_version: MOBILE_FFI_SCHEMA_VERSION + 1,
    722                 draft_id: upload.draft_id.clone(),
    723                 expected_revision: upload.expected_revision,
    724                 media: upload.media.clone(),
    725                 status_code: 200,
    726                 response_media_type: Some("application/json".to_owned()),
    727                 response_content_encoding: None,
    728                 response_body: Vec::new(),
    729             })
    730             .await
    731             .expect_err("unsupported completion schema")
    732             .report()
    733             .code,
    734         "invalid_native_upload_completion"
    735     );
    736     assert_eq!(
    737         runtime
    738             .phase1_complete_add_media_background(FfiNativeUploadCompletionInput {
    739                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    740                 draft_id: upload.draft_id.clone(),
    741                 expected_revision: upload.expected_revision,
    742                 media: upload.media.clone(),
    743                 status_code: 200,
    744                 response_media_type: Some("application/json".to_owned()),
    745                 response_content_encoding: None,
    746                 response_body: vec![0; 16_385],
    747             })
    748             .await
    749             .expect_err("oversized completion body")
    750             .report()
    751             .code,
    752         "invalid_native_upload_completion"
    753     );
    754     let mut invalid_id_upload = upload;
    755     invalid_id_upload.schema_version = MOBILE_FFI_SCHEMA_VERSION;
    756     invalid_id_upload.draft_id = "not-a-draft-id".to_owned();
    757     assert_eq!(
    758         runtime
    759             .phase1_upload_add_media_intent(invalid_id_upload.clone())
    760             .await
    761             .expect_err("invalid draft id")
    762             .report()
    763             .code,
    764         "invalid_draft_id"
    765     );
    766     assert_eq!(
    767         runtime
    768             .phase1_prepare_add_media_background(invalid_id_upload.clone())
    769             .await
    770             .expect_err("invalid background draft id")
    771             .report()
    772             .code,
    773         "invalid_draft_id"
    774     );
    775     assert_eq!(
    776         runtime
    777             .phase1_complete_add_media_background(FfiNativeUploadCompletionInput {
    778                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    779                 draft_id: invalid_id_upload.draft_id,
    780                 expected_revision: invalid_id_upload.expected_revision,
    781                 media: invalid_id_upload.media,
    782                 status_code: 200,
    783                 response_media_type: Some("application/json".to_owned()),
    784                 response_content_encoding: None,
    785                 response_body: Vec::new(),
    786             })
    787             .await
    788             .expect_err("invalid completion draft id")
    789             .report()
    790             .code,
    791         "invalid_draft_id"
    792     );
    793     assert!(
    794         runtime
    795             .phase1_local_network(FfiLocalNetworkRecord {
    796                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    797                 id: "nearby".to_owned(),
    798                 label: "Near me".to_owned(),
    799                 relay_urls: Vec::new(),
    800                 locality: None,
    801                 followed_authors: Vec::new(),
    802                 generation: 1,
    803             })
    804             .is_err()
    805     );
    806 
    807     let initial_settings = runtime.phase1_settings().await.expect("settings");
    808     let begun = runtime
    809         .phase1_apply_identity_command(
    810             initial_settings.revision,
    811             FfiIdentityCommandRecord {
    812                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    813                 kind: FfiIdentityCommandKind::BeginImport,
    814                 operation_id: Some("import-ffi-1".to_owned()),
    815                 identity_id: None,
    816                 public_key: None,
    817             },
    818         )
    819         .await
    820         .expect("begin identity import");
    821     let completed = runtime
    822         .phase1_apply_identity_command(
    823             begun.settings.revision,
    824             FfiIdentityCommandRecord {
    825                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    826                 kind: FfiIdentityCommandKind::CompleteImport,
    827                 operation_id: Some("import-ffi-1".to_owned()),
    828                 identity_id: Some("primary".to_owned()),
    829                 public_key: Some(support::PUBLIC_KEY.to_owned()),
    830             },
    831         )
    832         .await
    833         .expect("complete identity import");
    834     let unlocked = runtime
    835         .phase1_apply_identity_command(
    836             completed.settings.revision,
    837             FfiIdentityCommandRecord {
    838                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
    839                 kind: FfiIdentityCommandKind::Unlock,
    840                 operation_id: None,
    841                 identity_id: None,
    842                 public_key: None,
    843             },
    844         )
    845         .await
    846         .expect("record process-local unlock");
    847     assert_eq!(
    848         unlocked.settings.identity.lock_state,
    849         FfiIdentityLockState::Unlocked
    850     );
    851     assert_eq!(unlocked.settings.revision, completed.settings.revision);
    852 
    853     let source_event_id = source_event;
    854     let source = tera_core::runtime::product_surface::CardSourceIdentity::Event(
    855         radroots_event::EventId::parse(&source_event_id).expect("source event id"),
    856     );
    857     let card_id = tera_core::runtime::product_surface::CardId::derive(
    858         tera_core::runtime::product_surface::TodayCardType::Update,
    859         &source,
    860     )
    861     .to_hex();
    862     let revision_input = FfiRevisionInputRecord {
    863         request_id: "ac".repeat(16),
    864         schema_version: MOBILE_FFI_SCHEMA_VERSION,
    865         card_id,
    866         source_event_id,
    867         source_address: None,
    868         author_public_key: support::PUBLIC_KEY.to_owned(),
    869         replacement: FfiAddDraftInput {
    870             schema_version: MOBILE_FFI_SCHEMA_VERSION,
    871             command_type: FfiAddCommandType::CreateUpdate,
    872             content: "Corrected farm stand hours".to_owned(),
    873             identifier: None,
    874             title: None,
    875             summary: None,
    876             location: None,
    877             event_timing: None,
    878             event_start_date: None,
    879             event_end_date: None,
    880             event_start_unix_s: None,
    881             event_end_unix_s: None,
    882             event_timezone: None,
    883             price_amount: None,
    884             currency: None,
    885             unit: None,
    886             quantity: None,
    887             food_published_at_unix_s: None,
    888             food_status: None,
    889             media: Vec::new(),
    890         },
    891     };
    892     let revision = runtime
    893         .phase1_save_revision_intent(revision_input.clone())
    894         .await
    895         .expect("save lossless revision intent");
    896     assert_eq!(
    897         runtime
    898             .phase1_save_revision_intent(revision_input.clone())
    899             .await
    900             .unwrap(),
    901         revision
    902     );
    903     let mut changed = revision_input;
    904     changed.replacement.content = "Conflicting correction".into();
    905     assert!(runtime.phase1_save_revision_intent(changed).await.is_err());
    906     assert_eq!(revision.phase, FfiRevisionPhase::ReplacementPending);
    907     assert_eq!(revision.operation_id, revision.replacement.draft_id);
    908     assert!(revision.replacement.is_revision);
    909     assert_eq!(
    910         runtime
    911             .phase1_revision_status(revision.operation_id.clone())
    912             .await
    913             .expect("revision status")
    914             .phase,
    915         FfiRevisionPhase::ReplacementPending
    916     );
    917     assert!(
    918         runtime
    919             .phase1_advance_revision(revision.operation_id.clone())
    920             .await
    921             .is_err()
    922     );
    923     let cancelled_revision = runtime
    924         .phase1_cancel_revision(revision.operation_id.clone())
    925         .await
    926         .expect("cancel revision intent");
    927     assert_eq!(cancelled_revision.operation_id, revision.operation_id);
    928     assert_eq!(cancelled_revision.phase, FfiRevisionPhase::Cancelled);
    929 
    930     let profile = runtime
    931         .phase1_save_profile_metadata(FfiProfileMetadataInputRecord {
    932             schema_version: MOBILE_FFI_SCHEMA_VERSION,
    933             name: "grower".to_owned(),
    934             display_name: Some("Local Grower".to_owned()),
    935             about: Some("Seasonal produce".to_owned()),
    936             picture: None,
    937             banner: None,
    938             nip05: Some("grower@farm.example".to_owned()),
    939             bot: Some(false),
    940         })
    941         .await
    942         .expect("save profile intent");
    943     assert_eq!(profile.state, FfiOutboxState::Draft);
    944     assert_eq!(profile.operation_id.len(), 32);
    945     assert_eq!(
    946         runtime
    947             .phase1_profile_status(profile.operation_id.clone())
    948             .await
    949             .expect("profile status")
    950             .revision,
    951         profile.revision
    952     );
    953     let cancelled_profile = runtime
    954         .phase1_cancel_profile(profile.operation_id.clone(), profile.revision)
    955         .await
    956         .expect("cancel profile intent");
    957     assert_eq!(cancelled_profile.operation_id, profile.operation_id);
    958     assert_eq!(cancelled_profile.state, FfiOutboxState::Cancelled);
    959     assert_eq!(
    960         runtime
    961             .phase1_advance_profile(profile.operation_id.clone())
    962             .await
    963             .expect("advance cancelled profile")
    964             .state,
    965         FfiOutboxState::Cancelled
    966     );
    967 
    968     // The seeded source changed history after the earlier empty projection.
    969     runtime
    970         .phase1_refresh_today(
    971             local_network.clone(),
    972             1_800_000_010,
    973             FfiTodayProjectionUpdate::Incremental,
    974         )
    975         .await
    976         .unwrap();
    977     let cache = runtime
    978         .phase1_media_cache_status(local_network.clone())
    979         .await
    980         .expect("empty media cache status");
    981     assert_eq!(cache.artifact_count, 0);
    982     assert_eq!(cache.total_bytes, 0);
    983     assert!(cache.configuration_fingerprint.is_none());
    984     assert!(
    985         runtime
    986             .phase1_verified_media_artifact(local_network.clone(), "11".repeat(32))
    987             .await
    988             .expect("empty verified media lookup")
    989             .is_none()
    990     );
    991     assert!(
    992         !runtime
    993             .phase1_invalidate_media_artifact(local_network.clone(), "11".repeat(32))
    994             .await
    995             .expect("missing media invalidation")
    996     );
    997     assert!(
    998         runtime
    999             .phase1_invalidate_media_configuration(local_network.clone(), "22".repeat(32))
   1000             .await
   1001             .expect("empty configuration invalidation")
   1002             .is_empty()
   1003     );
   1004     let media_operation = Arc::new(FfiMediaOperation::new().expect("media operation"));
   1005     let media_error = runtime
   1006         .phase1_retrieve_media(
   1007             local_network.clone(),
   1008             "invalid-reference".to_owned(),
   1009             Arc::clone(&media_operation),
   1010         )
   1011         .await
   1012         .expect_err("invalid media reference");
   1013     assert_eq!(
   1014         media_error.report().code,
   1015         "invalid_media_reference_fingerprint"
   1016     );
   1017     assert_eq!(
   1018         runtime
   1019             .phase1_retrieve_media(local_network, "00".repeat(32), Arc::clone(&media_operation),)
   1020             .await
   1021             .expect_err("single-use media operation")
   1022             .report()
   1023             .code,
   1024         "media_operation_already_used"
   1025     );
   1026 
   1027     runtime.shutdown().await.expect("shutdown");
   1028     assert!(matches!(
   1029         runtime.sdk_storage_status().await,
   1030         Err(TeraAppError::Failure { .. })
   1031     ));
   1032     assert!(matches!(
   1033         runtime.sdk_relay_status(),
   1034         Err(TeraAppError::Failure { .. })
   1035     ));
   1036     assert!(matches!(
   1037         runtime.configure_public_relays(Vec::new()).await,
   1038         Err(TeraAppError::Failure { .. })
   1039     ));
   1040 }