field_ios

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

error.rs (24109B)


      1 use tera_core::runtime::product_surface::{
      2     Phase1DraftError, Phase1InboundMediaError, ProfileMetadataError, SettingsError, TodayError,
      3 };
      4 use thiserror::Error;
      5 
      6 use crate::MOBILE_FFI_SCHEMA_VERSION;
      7 
      8 #[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)]
      9 pub struct TeraErrorRecord {
     10     pub schema_version: u16,
     11     pub code: String,
     12     pub category: String,
     13     pub retryable: bool,
     14     pub recovery_actions: Vec<String>,
     15     pub operation_id: Option<String>,
     16     pub capability_id: Option<String>,
     17     pub safe_message: String,
     18 }
     19 
     20 /// The only error envelope exported across the native language boundary.
     21 #[derive(Debug, Error, uniffi::Error)]
     22 pub enum TeraAppError {
     23     #[error("radroots operation failed: {report:?}")]
     24     Failure { report: TeraErrorRecord },
     25 }
     26 
     27 impl TeraAppError {
     28     pub(crate) fn initialization(_message: impl Into<String>) -> Self {
     29         Self::failure(
     30             "initialization_failed",
     31             "initialization",
     32             true,
     33             &["retry"],
     34             "The Tera runtime could not be initialized.",
     35         )
     36     }
     37 
     38     pub(crate) fn invalid_argument(code: impl Into<String>) -> Self {
     39         Self::Failure {
     40             report: TeraErrorRecord {
     41                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
     42                 code: code.into(),
     43                 category: "validation".to_owned(),
     44                 retryable: false,
     45                 recovery_actions: vec!["correct_input".to_owned()],
     46                 operation_id: None,
     47                 capability_id: None,
     48                 safe_message: "The request is invalid.".to_owned(),
     49             },
     50         }
     51     }
     52 
     53     pub(crate) fn failure(
     54         code: &str,
     55         category: &str,
     56         retryable: bool,
     57         recovery_actions: &[&str],
     58         safe_message: &str,
     59     ) -> Self {
     60         Self::Failure {
     61             report: TeraErrorRecord {
     62                 schema_version: MOBILE_FFI_SCHEMA_VERSION,
     63                 code: code.to_owned(),
     64                 category: category.to_owned(),
     65                 retryable,
     66                 recovery_actions: recovery_actions
     67                     .iter()
     68                     .map(|action| (*action).to_owned())
     69                     .collect(),
     70                 operation_id: None,
     71                 capability_id: None,
     72                 safe_message: safe_message.to_owned(),
     73             },
     74         }
     75     }
     76 
     77     pub fn report(&self) -> &TeraErrorRecord {
     78         match self {
     79             Self::Failure { report } => report,
     80         }
     81     }
     82 
     83     pub(crate) fn with_operation_id(mut self, operation_id: String) -> Self {
     84         match &mut self {
     85             Self::Failure { report } => report.operation_id = Some(operation_id),
     86         }
     87         self
     88     }
     89 }
     90 
     91 impl From<tera_core::TeraAppError> for TeraAppError {
     92     fn from(error: tera_core::TeraAppError) -> Self {
     93         match error {
     94             tera_core::TeraAppError::Sdk { report } => Self::Failure {
     95                 report: TeraErrorRecord {
     96                     schema_version: report.schema_version,
     97                     code: report.code,
     98                     category: report.class,
     99                     retryable: report.retryable,
    100                     recovery_actions: report.recovery_actions,
    101                     operation_id: report.operation_id,
    102                     capability_id: report.capability_id,
    103                     safe_message: report.message,
    104                 },
    105             },
    106             tera_core::TeraAppError::Store { report } => Self::Failure {
    107                 report: TeraErrorRecord {
    108                     schema_version: report.schema_version,
    109                     code: report.code,
    110                     category: report.class,
    111                     retryable: report.retryable,
    112                     recovery_actions: report.recovery_actions,
    113                     operation_id: None,
    114                     capability_id: None,
    115                     safe_message: report.message,
    116                 },
    117             },
    118             tera_core::TeraAppError::Initialization(_) => Self::initialization("redacted"),
    119             tera_core::TeraAppError::Runtime(_) => Self::failure(
    120                 "runtime_failed",
    121                 "runtime",
    122                 true,
    123                 &["retry"],
    124                 "The runtime operation failed.",
    125             ),
    126             tera_core::TeraAppError::Unsupported(_) => Self::failure(
    127                 "unsupported",
    128                 "capability",
    129                 false,
    130                 &[],
    131                 "The requested capability is unsupported.",
    132             ),
    133             tera_core::TeraAppError::Internal(_) => Self::failure(
    134                 "internal_failure",
    135                 "internal",
    136                 false,
    137                 &["restart"],
    138                 "An internal Tera error occurred.",
    139             ),
    140         }
    141     }
    142 }
    143 
    144 impl From<TodayError> for TeraAppError {
    145     fn from(error: TodayError) -> Self {
    146         let (code, retryable, actions) = match error {
    147             TodayError::Lifecycle(error) => return tera_core::TeraAppError::from(error).into(),
    148             TodayError::InvalidRequest | TodayError::EventNotVisible => {
    149                 ("today_invalid_request", false, &["correct_input"][..])
    150             }
    151             TodayError::ProjectionMissing | TodayError::SnapshotMissing => {
    152                 ("today_refresh_required", true, &["refresh"][..])
    153             }
    154             TodayError::ProjectionRebuilding => {
    155                 ("today_projection_rebuilding", true, &["refresh"][..])
    156             }
    157             TodayError::CursorPositionMissing | TodayError::Cursor(_) => {
    158                 ("today_cursor_invalid", true, &["restart_pagination"][..])
    159             }
    160             TodayError::UnsupportedProjectionVersion => (
    161                 "today_reader_unsupported",
    162                 false,
    163                 &["upgrade_application"][..],
    164             ),
    165             TodayError::RuntimeUnavailable => ("today_runtime_unavailable", true, &["retry"][..]),
    166             TodayError::InboundMedia(Phase1InboundMediaError::SpaceInsufficient) => {
    167                 return Self::needs_space("today");
    168             }
    169             TodayError::InboundMedia(error) => (
    170                 tera_core::error::recovery::inbound_media_code(&error),
    171                 false,
    172                 &["review_media"][..],
    173             ),
    174             TodayError::InboundRetrieval(error) => {
    175                 if error.retryable() {
    176                     (error.code(), true, &["retry_media"][..])
    177                 } else {
    178                     (error.code(), false, &["review_media"][..])
    179                 }
    180             }
    181             TodayError::Storage(radroots_storage::Error::SpaceInsufficient) => {
    182                 return Self::needs_space("today");
    183             }
    184             TodayError::Storage(
    185                 radroots_storage::Error::SourceGenerationChanged
    186                 | radroots_storage::Error::SourceEpochChanged
    187                 | radroots_storage::Error::ProjectionRevisionConflict,
    188             ) => ("today_cursor_invalid", true, &["restart_pagination"][..]),
    189             TodayError::Storage(_) => ("today_storage_failed", true, &["inspect_local_stores"][..]),
    190             TodayError::CorruptProjection | TodayError::Serialization => {
    191                 ("today_state_failed", true, &["rebuild", "retry"][..])
    192             }
    193         };
    194         Self::failure(
    195             code,
    196             "today",
    197             retryable,
    198             actions,
    199             "The Today operation could not be completed.",
    200         )
    201     }
    202 }
    203 
    204 impl From<Phase1DraftError> for TeraAppError {
    205     fn from(error: Phase1DraftError) -> Self {
    206         let (code, retryable, actions) = match error {
    207             Phase1DraftError::Lifecycle(error) => {
    208                 return tera_core::TeraAppError::from(error).into();
    209             }
    210             Phase1DraftError::IdentityUnavailable => (
    211                 "identity_unavailable",
    212                 true,
    213                 &["unlock_identity", "retry"][..],
    214             ),
    215             Phase1DraftError::InvalidDraft => ("draft_invalid", false, &["correct_input"][..]),
    216             Phase1DraftError::InvalidInventoryRequest => {
    217                 ("draft_inventory_invalid", false, &["correct_input"][..])
    218             }
    219             Phase1DraftError::InvalidInventoryCursor => (
    220                 "draft_inventory_cursor_invalid",
    221                 false,
    222                 &["reload_drafts"][..],
    223             ),
    224             Phase1DraftError::InvalidMedia => {
    225                 ("draft_media_invalid", false, &["replace_media"][..])
    226             }
    227             Phase1DraftError::InvalidQueuePolicy => {
    228                 ("draft_queue_policy_invalid", false, &["correct_input"][..])
    229             }
    230             Phase1DraftError::RevisionConflict => {
    231                 ("draft_revision_conflict", true, &["refresh"][..])
    232             }
    233             Phase1DraftError::NotFound => ("draft_not_found", false, &[][..]),
    234             Phase1DraftError::Terminal => ("draft_terminal", false, &[][..]),
    235             Phase1DraftError::MediaNotReady => {
    236                 ("draft_media_not_ready", true, &["retry_media"][..])
    237             }
    238             Phase1DraftError::OperationUnavailable => {
    239                 ("authoring_unavailable", true, &["retry"][..])
    240             }
    241             Phase1DraftError::OperationInProgress => {
    242                 return Self::failure(
    243                     "operation_in_progress",
    244                     "operation",
    245                     true,
    246                     &["retry_operation_with_same_idempotency_key"],
    247                     "An authored transition is already in progress for this operation.",
    248                 );
    249             }
    250             Phase1DraftError::SpaceInsufficient => return Self::needs_space("authoring"),
    251             Phase1DraftError::Storage => (
    252                 "authoring_storage_failed",
    253                 true,
    254                 &["inspect_local_stores"][..],
    255             ),
    256             Phase1DraftError::Overlay => ("authoring_overlay_failed", true, &["refresh"][..]),
    257             Phase1DraftError::Operation => {
    258                 ("authoring_failed", true, &["retry", "inspect_outbox"][..])
    259             }
    260             Phase1DraftError::Corrupt => ("draft_corrupt", false, &["recover_draft"][..]),
    261             Phase1DraftError::ClockUnavailable => {
    262                 ("operation_clock_unavailable", true, &["retry"][..])
    263             }
    264             Phase1DraftError::DeadlineOverflow => ("operation_deadline_overflow", false, &[][..]),
    265             Phase1DraftError::NoWritableRelay => (
    266                 "writable_relay_unavailable",
    267                 true,
    268                 &["configure_relay", "retry"][..],
    269             ),
    270             Phase1DraftError::InvalidRevision => {
    271                 ("revision_invalid", false, &["review_revision"][..])
    272             }
    273             Phase1DraftError::Restore(error) => (error.code(), false, &["review_restore"][..]),
    274         };
    275         Self::failure(
    276             code,
    277             "authoring",
    278             retryable,
    279             actions,
    280             "The authored operation could not be completed.",
    281         )
    282     }
    283 }
    284 
    285 impl From<SettingsError> for TeraAppError {
    286     fn from(error: SettingsError) -> Self {
    287         if let SettingsError::Lifecycle(error) = error {
    288             return tera_core::TeraAppError::from(error).into();
    289         }
    290         if matches!(error, SettingsError::SpaceInsufficient) {
    291             return Self::needs_space("settings");
    292         }
    293         let retryable = matches!(
    294             error,
    295             SettingsError::RevisionConflict | SettingsError::Storage
    296         );
    297         let actions = if matches!(error, SettingsError::RevisionConflict) {
    298             &["refresh"] as &[&str]
    299         } else if retryable {
    300             &["retry"] as &[&str]
    301         } else {
    302             &["correct_input"] as &[&str]
    303         };
    304         Self::failure(
    305             error.code(),
    306             "settings",
    307             retryable,
    308             actions,
    309             "The settings operation could not be completed.",
    310         )
    311     }
    312 }
    313 
    314 impl From<ProfileMetadataError> for TeraAppError {
    315     fn from(error: ProfileMetadataError) -> Self {
    316         Self::failure(
    317             error.code(),
    318             "profile",
    319             false,
    320             &["correct_input"],
    321             "The profile metadata is invalid.",
    322         )
    323     }
    324 }
    325 
    326 impl TeraAppError {
    327     pub(crate) fn needs_space(domain: &str) -> Self {
    328         Self::failure(
    329             "storage_space_insufficient",
    330             domain,
    331             false,
    332             &[
    333                 "free_reconstructable_cache",
    334                 "preserve_local_work",
    335                 "reconcile_original_operation",
    336             ],
    337             "Local storage space is insufficient. Preserve the original work and reconcile its state before retrying.",
    338         )
    339     }
    340 }
    341 
    342 #[cfg(test)]
    343 mod tests {
    344     use super::*;
    345 
    346     #[test]
    347     fn current_storage_conflicts_refuse_scope_without_collapsing_offline_or_capacity_reports() {
    348         for conflict in [
    349             radroots_storage::Error::SourceGenerationChanged,
    350             radroots_storage::Error::SourceEpochChanged,
    351             radroots_storage::Error::ProjectionRevisionConflict,
    352         ] {
    353             let ffi = TeraAppError::from(TodayError::Storage(conflict));
    354             assert_eq!(ffi.report().code, "today_cursor_invalid");
    355             assert!(ffi.report().retryable);
    356             assert_eq!(ffi.report().recovery_actions, ["restart_pagination"]);
    357             let recovery = crate::recovery::classify_error_recovery(
    358                 ffi.report().schema_version,
    359                 ffi.report().code.clone(),
    360             );
    361             assert_eq!(
    362                 recovery.disposition,
    363                 crate::recovery::FfiRecoveryDisposition::StaleCursor
    364             );
    365         }
    366         let offline = TeraAppError::from(TodayError::Storage(
    367             radroots_storage::Error::BackendUnavailable,
    368         ));
    369         assert_eq!(offline.report().code, "today_storage_failed");
    370         assert_eq!(offline.report().recovery_actions, ["inspect_local_stores"]);
    371         let space = TeraAppError::from(TodayError::Storage(
    372             radroots_storage::Error::SpaceInsufficient,
    373         ));
    374         assert_eq!(space.report().code, "storage_space_insufficient");
    375         assert_eq!(
    376             space.report().recovery_actions,
    377             [
    378                 "free_reconstructable_cache",
    379                 "preserve_local_work",
    380                 "reconcile_original_operation",
    381             ]
    382         );
    383     }
    384 
    385     #[test]
    386     fn mutation_admission_reports_the_existing_typed_recovery_contract() {
    387         let error = TeraAppError::from(Phase1DraftError::OperationInProgress);
    388         let report = error.report();
    389         assert_eq!(report.schema_version, MOBILE_FFI_SCHEMA_VERSION);
    390         assert_eq!(report.code, "operation_in_progress");
    391         assert_eq!(report.category, "operation");
    392         assert!(report.retryable);
    393         assert_eq!(
    394             report.recovery_actions,
    395             ["retry_operation_with_same_idempotency_key"]
    396         );
    397         let recovery = tera_core::error::recovery::classify(report.schema_version, &report.code);
    398         assert_eq!(
    399             recovery.disposition,
    400             tera_core::error::recovery::RecoveryDisposition::OutcomeUnknown
    401         );
    402     }
    403 
    404     #[test]
    405     fn internal_core_messages_are_not_copied_to_the_ffi_record() {
    406         let error = TeraAppError::from(tera_core::TeraAppError::internal(
    407             "private/path/secret-value",
    408         ));
    409         assert_eq!(error.report().code, "internal_failure");
    410         assert!(!format!("{error:?}").contains("secret-value"));
    411         assert!(!error.report().safe_message.contains("secret-value"));
    412     }
    413 
    414     #[test]
    415     fn every_core_error_class_maps_to_a_versioned_redacted_record() {
    416         let sdk = tera_core::TeraAppError::Sdk {
    417             report: tera_core::SdkErrorRecord {
    418                 schema_version: 1,
    419                 code: "relay_unavailable".to_owned(),
    420                 class: "transport".to_owned(),
    421                 retryable: true,
    422                 recovery_actions: vec!["retry".to_owned()],
    423                 operation_id: Some("operation".to_owned()),
    424                 capability_id: Some("relay".to_owned()),
    425                 message: "Safe relay failure".to_owned(),
    426             },
    427         };
    428         let sdk = TeraAppError::from(sdk);
    429         assert_eq!(sdk.report().code, "relay_unavailable");
    430         assert_eq!(sdk.report().operation_id.as_deref(), Some("operation"));
    431 
    432         let store = tera_core::TeraAppError::Store {
    433             report: tera_core::StoreErrorRecord {
    434                 schema_version: 1,
    435                 code: "store_locked".to_owned(),
    436                 class: "storage".to_owned(),
    437                 retryable: true,
    438                 recovery_actions: vec!["unlock".to_owned()],
    439                 message: "Safe store failure".to_owned(),
    440             },
    441         };
    442         let store = TeraAppError::from(store);
    443         assert_eq!(store.report().code, "store_locked");
    444         assert!(store.report().operation_id.is_none());
    445 
    446         for (core, code, category) in [
    447             (
    448                 tera_core::TeraAppError::initialization("secret"),
    449                 "initialization_failed",
    450                 "initialization",
    451             ),
    452             (
    453                 tera_core::TeraAppError::runtime("secret"),
    454                 "runtime_failed",
    455                 "runtime",
    456             ),
    457             (
    458                 tera_core::TeraAppError::unsupported("secret"),
    459                 "unsupported",
    460                 "capability",
    461             ),
    462             (
    463                 tera_core::TeraAppError::internal("secret"),
    464                 "internal_failure",
    465                 "internal",
    466             ),
    467         ] {
    468             let ffi = TeraAppError::from(core);
    469             assert_eq!(ffi.report().code, code);
    470             assert_eq!(ffi.report().category, category);
    471             assert!(!ffi.report().safe_message.contains("secret"));
    472         }
    473     }
    474 
    475     #[test]
    476     fn today_and_draft_failures_have_stable_recovery_classes() {
    477         for error in [
    478             TodayError::InvalidRequest,
    479             TodayError::EventNotVisible,
    480             TodayError::ProjectionMissing,
    481             TodayError::SnapshotMissing,
    482             TodayError::CursorPositionMissing,
    483             TodayError::RuntimeUnavailable,
    484             TodayError::CorruptProjection,
    485             TodayError::Serialization,
    486         ] {
    487             let ffi = TeraAppError::from(error);
    488             assert_eq!(ffi.report().category, "today");
    489             assert!(!ffi.report().safe_message.is_empty());
    490         }
    491 
    492         for error in [
    493             Phase1DraftError::IdentityUnavailable,
    494             Phase1DraftError::InvalidDraft,
    495             Phase1DraftError::InvalidInventoryRequest,
    496             Phase1DraftError::InvalidInventoryCursor,
    497             Phase1DraftError::InvalidMedia,
    498             Phase1DraftError::InvalidQueuePolicy,
    499             Phase1DraftError::RevisionConflict,
    500             Phase1DraftError::NotFound,
    501             Phase1DraftError::Terminal,
    502             Phase1DraftError::MediaNotReady,
    503             Phase1DraftError::OperationUnavailable,
    504             Phase1DraftError::Operation,
    505             Phase1DraftError::Storage,
    506             Phase1DraftError::Overlay,
    507             Phase1DraftError::Corrupt,
    508             Phase1DraftError::ClockUnavailable,
    509             Phase1DraftError::DeadlineOverflow,
    510             Phase1DraftError::NoWritableRelay,
    511             Phase1DraftError::InvalidRevision,
    512         ] {
    513             let ffi = TeraAppError::from(error);
    514             assert_eq!(ffi.report().category, "authoring");
    515             assert!(!ffi.report().safe_message.is_empty());
    516         }
    517     }
    518 
    519     #[test]
    520     fn cursor_media_settings_and_profile_failures_cover_every_stable_class() {
    521         use tera_core::runtime::product_surface::{
    522             CursorError, IdentitySettingsError, Phase1InboundMediaError,
    523         };
    524 
    525         for cursor in [
    526             CursorError::InvalidContext,
    527             CursorError::Malformed,
    528             CursorError::Integrity,
    529             CursorError::Version,
    530             CursorError::ContextMismatch,
    531             CursorError::SnapshotMismatch,
    532             CursorError::Stale,
    533             CursorError::InvalidPosition,
    534         ] {
    535             let error = TeraAppError::from(TodayError::Cursor(cursor));
    536             assert_eq!(error.report().code, "today_cursor_invalid");
    537             let recovery = crate::recovery::classify_error_recovery(
    538                 error.report().schema_version,
    539                 error.report().code.clone(),
    540             );
    541             assert_eq!(
    542                 recovery.disposition,
    543                 crate::recovery::FfiRecoveryDisposition::StaleCursor
    544             );
    545         }
    546         for media in [
    547             Phase1InboundMediaError::InvalidReference,
    548             Phase1InboundMediaError::InvalidDigest,
    549             Phase1InboundMediaError::MissingDigest,
    550             Phase1InboundMediaError::InvalidMediaType,
    551             Phase1InboundMediaError::InvalidDimensions,
    552             Phase1InboundMediaError::InvalidByteSize,
    553             Phase1InboundMediaError::InvalidAlt,
    554             Phase1InboundMediaError::MetadataMismatch,
    555             Phase1InboundMediaError::InvalidOperation,
    556             Phase1InboundMediaError::OperationMismatch,
    557             Phase1InboundMediaError::InvalidFailure,
    558             Phase1InboundMediaError::InvalidConfiguration,
    559             Phase1InboundMediaError::ConfigurationMismatch,
    560             Phase1InboundMediaError::InvalidVerificationTime,
    561             Phase1InboundMediaError::InvalidCachePolicy,
    562             Phase1InboundMediaError::InvalidCacheObservation,
    563             Phase1InboundMediaError::CacheQuotaExceeded,
    564             Phase1InboundMediaError::ArtifactCollision,
    565             Phase1InboundMediaError::CorruptReceipt,
    566             Phase1InboundMediaError::CorruptState,
    567             Phase1InboundMediaError::UnsupportedSchema,
    568             Phase1InboundMediaError::CacheUnavailable,
    569             Phase1InboundMediaError::CacheIo,
    570             Phase1InboundMediaError::CorruptArtifact,
    571         ] {
    572             let expected = tera_core::error::recovery::inbound_media_code(&media);
    573             let error = TeraAppError::from(TodayError::InboundMedia(media));
    574             assert_eq!(error.report().code, expected);
    575         }
    576         for settings in [
    577             SettingsError::UnknownRelayAccess,
    578             SettingsError::InvalidRelayEndpoint,
    579             SettingsError::InvalidRelayEndpointCount,
    580             SettingsError::DuplicateRelayEndpoint,
    581             SettingsError::InvalidBlossomEndpoint,
    582             SettingsError::InvalidBlossomEndpointCount,
    583             SettingsError::NetworkEnvironmentMismatch,
    584             SettingsError::InvalidMediaCacheBytes,
    585             SettingsError::InvalidMediaCacheArtifacts,
    586             SettingsError::RevisionConflict,
    587             SettingsError::RevisionExhausted,
    588             SettingsError::UnsupportedSchema,
    589             SettingsError::CorruptDocument,
    590             SettingsError::Storage,
    591             SettingsError::Identity(IdentitySettingsError::InvalidIdentityId),
    592         ] {
    593             let expected_retryable = matches!(
    594                 settings,
    595                 SettingsError::RevisionConflict | SettingsError::Storage
    596             );
    597             let error = TeraAppError::from(settings);
    598             assert_eq!(error.report().retryable, expected_retryable);
    599         }
    600         for profile in [
    601             ProfileMetadataError::InvalidName,
    602             ProfileMetadataError::InvalidDisplayName,
    603             ProfileMetadataError::InvalidAbout,
    604             ProfileMetadataError::InvalidNip05,
    605         ] {
    606             assert_eq!(TeraAppError::from(profile).report().category, "profile");
    607         }
    608         assert_eq!(
    609             TeraAppError::initialization("private").report().code,
    610             "initialization_failed"
    611         );
    612         assert_eq!(
    613             TeraAppError::invalid_argument("bad")
    614                 .with_operation_id("operation".to_owned())
    615                 .report()
    616                 .operation_id
    617                 .as_deref(),
    618             Some("operation")
    619         );
    620     }
    621 }
    622 
    623 #[cfg(test)]
    624 #[path = "capacity_tests.rs"]
    625 mod capacity_tests;