lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

package_boundary.rs (19823B)


      1 use std::collections::BTreeSet;
      2 
      3 const MANIFEST: &str = include_str!("../Cargo.toml");
      4 const ROOT: &str = include_str!("../src/lib.rs");
      5 const CLIENT: &str = include_str!("../src/client.rs");
      6 const FARM: &str = include_str!("../src/farm.rs");
      7 const LISTING: &str = include_str!("../src/listing.rs");
      8 const TRADE: &str = include_str!("../src/trade.rs");
      9 const STORAGE: &str = include_str!("../src/storage.rs");
     10 const DIAGNOSTICS: &str = include_str!("../src/diagnostics.rs");
     11 const ADAPTERS: &str = include_str!("../src/adapters/mod.rs");
     12 const RADROOTSD: &str = include_str!("../src/adapters/radrootsd.rs");
     13 const SYNC: &str = include_str!("../src/sync.rs");
     14 const TRANSPORT: &str = include_str!("../src/transport.rs");
     15 const PUBLICATION: &str = include_str!("fixtures/publication.toml");
     16 
     17 #[test]
     18 fn manifest_has_final_identity_and_dependency_boundary() {
     19     assert!(MANIFEST.contains("name = \"radroots_sdk\""));
     20     assert!(MANIFEST.contains("publish = [\"crates-io\"]"));
     21     assert!(MANIFEST.contains("version.workspace = true"));
     22     assert!(MANIFEST.contains("name = \"package_boundary\""));
     23 
     24     let dependencies = dependency_names(MANIFEST);
     25     let expected = BTreeSet::from([
     26         "radroots_blossom",
     27         "radroots_core",
     28         "radroots_event",
     29         "radroots_event_codec",
     30         "radroots_geonames",
     31         "radroots_identity",
     32         "radroots_nostr",
     33         "radroots_nostr_connect",
     34         "radroots_protocol",
     35         "radroots_secrets",
     36         "radroots_signing",
     37         "radroots_storage",
     38         "radroots_storage_sqlite",
     39         "radroots_sync",
     40         "radroots_trade",
     41         "radroots_transport",
     42         "radroots_transport_nostr",
     43         "radroots_transport_nostr_native",
     44     ]);
     45     assert_eq!(dependencies, expected);
     46     for forbidden in [
     47         "radroots_event_store",
     48         "radroots_nostr_signer",
     49         "radroots_outbox",
     50         "radroots_protected_store",
     51         "radroots_runtime_paths",
     52         "radroots_secret_vault",
     53         "radroots_transport_reticulum",
     54     ] {
     55         assert!(
     56             !dependencies.contains(forbidden),
     57             "SDK depends on private or superseded package `{forbidden}`"
     58         );
     59     }
     60 }
     61 
     62 #[test]
     63 fn manifest_has_exact_feature_vocabulary_and_explicit_optional_activation() {
     64     let features = MANIFEST
     65         .split_once("[features]")
     66         .expect("feature section")
     67         .1
     68         .split_once("[dependencies]")
     69         .expect("dependency section")
     70         .0
     71         .lines()
     72         .filter_map(|line| line.split_once(" = ").map(|(name, _)| name.trim()))
     73         .collect::<BTreeSet<_>>();
     74     assert_eq!(
     75         features,
     76         BTreeSet::from([
     77             "blossom",
     78             "default",
     79             "full",
     80             "geonames",
     81             "knowledge",
     82             "local-signing",
     83             "memory",
     84             "native",
     85             "nip46",
     86             "nostr",
     87             "radrootsd",
     88             "sqlite",
     89             "sync",
     90         ])
     91     );
     92     for activation in [
     93         "dep:radroots_storage_sqlite",
     94         "dep:radroots_sync",
     95         "dep:radroots_blossom",
     96         "dep:radroots_nostr",
     97         "dep:radroots_transport_nostr",
     98         "dep:radroots_nostr_connect",
     99         "dep:radroots_secrets",
    100         "dep:reqwest",
    101         "dep:serde",
    102         "dep:serde_json",
    103         "dep:tokio",
    104         "dep:radroots_geonames",
    105     ] {
    106         assert!(
    107             MANIFEST.contains(activation),
    108             "missing activation `{activation}`"
    109         );
    110     }
    111     for retired in [
    112         "runtime =",
    113         "local-runtime",
    114         "signer-adapters",
    115         "transport-nostr-runtime",
    116         "transport-nostr-client",
    117         "fixtures =",
    118     ] {
    119         assert!(!MANIFEST.contains(retired), "retired feature `{retired}`");
    120     }
    121 }
    122 
    123 #[test]
    124 fn root_declares_exact_final_module_skeleton() {
    125     let actual = ROOT
    126         .lines()
    127         .filter_map(|line| line.trim().strip_prefix("pub mod "))
    128         .map(|module| module.trim_end_matches(';'))
    129         .collect::<BTreeSet<_>>();
    130     let expected = BTreeSet::from([
    131         "capability",
    132         "client",
    133         "diagnostics",
    134         "error",
    135         "farm",
    136         "listing",
    137         "signing",
    138         "storage",
    139         "sync",
    140         "trade",
    141         "transport",
    142     ]);
    143     assert_eq!(actual, expected);
    144     assert!(!ROOT.contains("no_std"));
    145     assert_eq!(ROOT.matches("pub use crate::").count(), 2);
    146     assert!(ROOT.contains("pub use crate::client::{Client, ClientBuilder};"));
    147     assert!(ROOT.contains("pub use crate::error::{Error, Result};"));
    148     assert!(!ROOT.contains("pub use radroots_"));
    149 }
    150 
    151 #[test]
    152 fn package_contains_only_reachable_sources_and_registered_targets() {
    153     let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    154     assert_eq!(
    155         rust_files(&root.join("src")),
    156         BTreeSet::from([
    157             "adapters/mod.rs".to_owned(),
    158             "adapters/blossom.rs".to_owned(),
    159             "adapters/blossom/native_completion_tests.rs".to_owned(),
    160             "adapters/radrootsd.rs".to_owned(),
    161             "capability.rs".to_owned(),
    162             "client.rs".to_owned(),
    163             "diagnostics.rs".to_owned(),
    164             "error.rs".to_owned(),
    165             "farm.rs".to_owned(),
    166             "lib.rs".to_owned(),
    167             "listing.rs".to_owned(),
    168             "listing/operational_listing/draft.rs".to_owned(),
    169             "listing/operational_listing/mod.rs".to_owned(),
    170             "listing/operational_listing/model.rs".to_owned(),
    171             "listing/operational_listing/mutation.rs".to_owned(),
    172             "listing/operational_listing/price_ext.rs".to_owned(),
    173             "listing/operational_listing/validation.rs".to_owned(),
    174             "signing.rs".to_owned(),
    175             "storage.rs".to_owned(),
    176             "storage/backup_tests.rs".to_owned(),
    177             "storage/restore_tests.rs".to_owned(),
    178             "sync.rs".to_owned(),
    179             "sync/tests/selected.rs".to_owned(),
    180             "trade.rs".to_owned(),
    181             "transport.rs".to_owned(),
    182             "transport/nostr_retirement_tests.rs".to_owned(),
    183         ])
    184     );
    185     assert_eq!(
    186         rust_files(&root.join("tests")),
    187         BTreeSet::from([
    188             "lifecycle.rs".to_owned(),
    189             "package_boundary.rs".to_owned(),
    190             "public_api.rs".to_owned(),
    191             "unit/adapters_radrootsd_tests.rs".to_owned(),
    192         ])
    193     );
    194     assert_eq!(
    195         rust_files(&root.join("examples")),
    196         BTreeSet::from([
    197             "safe_memory_client.rs".to_owned(),
    198             "transport_profile.rs".to_owned(),
    199         ])
    200     );
    201 }
    202 
    203 #[test]
    204 fn compatibility_packages_are_removed() {
    205     assert!(PUBLICATION.contains("retired = []"));
    206     let approved = PUBLICATION
    207         .split_once("approved_packages = [")
    208         .expect("approved package list")
    209         .1
    210         .split_once("\n]")
    211         .expect("approved package list terminator")
    212         .0;
    213     assert!(!approved.contains("radroots_runtime_contract_v1"));
    214     let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    215         .parent()
    216         .and_then(std::path::Path::parent)
    217         .expect("workspace root");
    218     assert!(!workspace.join("crates/runtime_contract_v1").exists());
    219     assert!(!workspace.join("crates/event_index_bindings").exists());
    220 }
    221 
    222 #[test]
    223 fn root_types_have_the_required_std_contracts() {
    224     fn assert_client<T: Clone + Send + Sync>() {}
    225     fn assert_builder<T: Send + Sync>() {}
    226     fn assert_error<T: std::error::Error + Send + Sync + 'static>() {}
    227 
    228     assert_client::<radroots_sdk::Client>();
    229     assert_builder::<radroots_sdk::ClientBuilder>();
    230     assert_error::<radroots_sdk::Error>();
    231     let result: radroots_sdk::Result<()> = Ok(());
    232     assert!(result.is_ok());
    233 }
    234 
    235 #[cfg(feature = "sqlite")]
    236 #[test]
    237 fn sqlite_backend_implements_the_canonical_storage_capability() {
    238     fn assert_storage<T: radroots_storage::Storage>() {}
    239     assert_storage::<radroots_storage_sqlite::SqliteStorage>();
    240 }
    241 
    242 #[cfg(feature = "nostr")]
    243 #[test]
    244 fn nostr_adapter_implements_independent_source_and_sink_capabilities() {
    245     fn assert_source<T: radroots_transport::EventSource>() {}
    246     fn assert_sink<T: radroots_transport::EventSink>() {}
    247     assert_source::<radroots_transport_nostr::NostrTransport>();
    248     assert_sink::<radroots_transport_nostr::NostrTransport>();
    249 }
    250 
    251 #[test]
    252 fn lifecycle_source_owns_no_hidden_worker_runtime_or_blocking_drop() {
    253     for forbidden in [
    254         "tokio::spawn",
    255         "std::thread::spawn",
    256         "Runtime::new",
    257         "block_on(self.close",
    258         "impl Drop for Client",
    259     ] {
    260         assert!(
    261             !CLIENT.contains(forbidden),
    262             "forbidden lifecycle source `{forbidden}`"
    263         );
    264     }
    265     assert!(CLIENT.contains("pub async fn close(&self)"));
    266     assert!(CLIENT.contains("impl Drop for CloseAttempt"));
    267 }
    268 
    269 #[test]
    270 fn sdk_source_contains_no_studio_storage_surface() {
    271     let source_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    272     let mut pending = vec![source_root];
    273     while let Some(path) = pending.pop() {
    274         for entry in std::fs::read_dir(path).expect("read SDK source") {
    275             let entry = entry.expect("source entry");
    276             let path = entry.path();
    277             if path.is_dir() {
    278                 pending.push(path);
    279             } else if path.extension().and_then(|value| value.to_str()) == Some("rs") {
    280                 let source = std::fs::read_to_string(&path).expect("read source file");
    281                 for forbidden in [
    282                     "studio.sqlite",
    283                     "SdkStudioStore",
    284                     "sdk_studio_state",
    285                     "studio_store",
    286                 ] {
    287                     assert!(
    288                         !source.contains(forbidden),
    289                         "{} contains retired Studio storage marker {forbidden}",
    290                         path.display()
    291                     );
    292                 }
    293             }
    294         }
    295     }
    296 }
    297 
    298 #[test]
    299 fn transport_profiles_reuse_canonical_types_and_forbid_fallback() {
    300     assert!(TRANSPORT.contains("use radroots_transport::{"));
    301     assert!(TRANSPORT.contains("satisfaction.validate_for(&targets)?"));
    302     assert!(TRANSPORT.contains("Selection::UnavailablePreview"));
    303     for duplicate in [
    304         "pub struct TargetSet",
    305         "pub enum TargetPolicy",
    306         "pub enum SatisfactionPolicy",
    307         "pub struct SourceStatus",
    308         "pub struct SinkStatus",
    309         "DefaultProfile",
    310     ] {
    311         assert!(
    312             !TRANSPORT.contains(duplicate),
    313             "SDK transport source contains forbidden duplicate or fallback `{duplicate}`"
    314         );
    315     }
    316 }
    317 
    318 #[test]
    319 fn sync_operations_only_delegate_to_the_canonical_engine() {
    320     for delegation in [
    321         "self.engine.pull(request, admission).await",
    322         "self.engine.ingest(observed, admission).await",
    323         "self.engine.ingest_batch(observed, admission).await",
    324         "self.engine.refresh_projection(request, reducer).await",
    325         "self.engine.prepare_push(request).await",
    326         "self.engine.push_status(operation_id).await",
    327         "self.engine.sign_prepared(request).await",
    328         "self.engine.admit_signed(operation_id).await",
    329         "self.engine.deliver_push(operation_id).await",
    330         "self.engine.status(projections).await",
    331         "self.engine.retry_decision(plan, now_unix_ms)",
    332     ] {
    333         assert!(
    334             SYNC.contains(delegation),
    335             "missing sync delegation `{delegation}`"
    336         );
    337     }
    338     for duplicate in [
    339         "pub struct SyncTransport",
    340         "pub struct SyncOutbox",
    341         "pub struct SyncProjection",
    342         "pub struct SyncStatus",
    343         "pub struct PushOutbox",
    344     ] {
    345         assert!(
    346             !SYNC.contains(duplicate),
    347             "SDK sync source contains duplicate lower model `{duplicate}`"
    348         );
    349     }
    350     assert!(
    351         !std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    352             .join("src/sync_runtime.rs")
    353             .exists()
    354     );
    355 }
    356 
    357 #[test]
    358 fn authored_submission_is_one_protocol_neutral_boundary_for_all_typed_contracts() {
    359     use radroots_event_codec::authoring::REGISTRY_V7_TYPED_AUTHORING_CONTRACT_IDS;
    360 
    361     assert_eq!(REGISTRY_V7_TYPED_AUTHORING_CONTRACT_IDS.len(), 16);
    362     assert!(SYNC.contains("pub async fn submit_push"));
    363     assert!(SYNC.contains("request: PushRequest"));
    364     assert!(SYNC.contains("Result<PushStatus, Error>"));
    365     for contract_id in REGISTRY_V7_TYPED_AUTHORING_CONTRACT_IDS {
    366         assert!(
    367             !SYNC.contains(contract_id),
    368             "SDK submission must not branch on typed contract `{contract_id}`"
    369         );
    370     }
    371 }
    372 
    373 #[test]
    374 fn trade_planning_uses_only_the_typed_mutation_authoring_boundary() {
    375     assert!(TRADE.contains("AuthoredEventPlan::from_trade_mutation"));
    376     for forbidden in ["GenericEventDraft", "trade_mutation_event_build("] {
    377         assert!(
    378             !TRADE.contains(forbidden),
    379             "trade planning retains generic authoring path {forbidden}"
    380         );
    381     }
    382 }
    383 
    384 #[test]
    385 fn trade_evidence_surface_is_curated_and_signature_verified() {
    386     let production = TRADE
    387         .split_once("#[cfg(test)]")
    388         .expect("trade tests remain separated")
    389         .0;
    390     for required in [
    391         "pub use radroots_trade::evidence::{",
    392         "pub fn parse_evidence_manifest(",
    393         "pub fn parse_rhi_evidence_report(",
    394         "pub fn prepare_rhi_evidence_attestation(",
    395         "pub fn validate_rhi_evidence_attestation(",
    396         "Nip01SignatureVerifier",
    397         "rhi_evidence_attestation_from_verified_event",
    398     ] {
    399         assert!(
    400             production.contains(required),
    401             "missing trade evidence boundary `{required}`"
    402         );
    403     }
    404     for forbidden in ["SecretKey", "sign_event", "tokio::spawn", "publish_event("] {
    405         assert!(
    406             !production.contains(forbidden),
    407             "trade evidence surface gained forbidden authority `{forbidden}`"
    408         );
    409     }
    410 }
    411 
    412 #[test]
    413 fn farm_operations_preserve_pure_planning_commit_and_privacy_boundaries() {
    414     for required in [
    415         "encode::farm::to_wire_parts",
    416         "AddressableCoordinate",
    417         "GenericEventDraft",
    418         "AuthoredEventPlan",
    419         "radroots_sync::PushRequest::new",
    420         "self.sync",
    421         ".submit_push(",
    422         "PrivateArtifactStore",
    423     ] {
    424         assert!(
    425             FARM.contains(required),
    426             "missing farm boundary `{required}`"
    427         );
    428     }
    429     for forbidden in [
    430         "SdkExactLocation",
    431         "SdkPublicLocality",
    432         "latitude:",
    433         "longitude:",
    434         "enqueue_signed_workflow",
    435         "local_event_seq",
    436         "outbox_event_id",
    437     ] {
    438         assert!(
    439             !FARM.contains(forbidden),
    440             "farm source contains retired SDK or private representation `{forbidden}`"
    441         );
    442     }
    443     let source_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    444     assert!(!source_root.join("farms_runtime.rs").exists());
    445 }
    446 
    447 #[test]
    448 fn listing_operations_reuse_trade_event_sync_and_privacy_boundaries() {
    449     for required in [
    450         "canonicalize_operational_listing_edit",
    451         "RadrootsOperationalListingMutation",
    452         "RadrootsOperationalListingLifecycleState",
    453         "build_operational_listing_mutation_plan",
    454         "radroots_sync::PushRequest::new",
    455         "PrivateArtifactStore",
    456     ] {
    457         assert!(
    458             LISTING.contains(required),
    459             "missing listing boundary `{required}`"
    460         );
    461     }
    462     for forbidden in [
    463         "SdkMutationState",
    464         "ListingEnqueueReceipt",
    465         "enqueue_signed_workflow",
    466         "local_event_seq",
    467         "outbox_event_id",
    468         "latitude:",
    469         "longitude:",
    470     ] {
    471         assert!(
    472             !LISTING.contains(forbidden),
    473             "listing source contains retired duplicate or private representation `{forbidden}`"
    474         );
    475     }
    476     assert!(
    477         !std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    478             .join("src/listings_runtime.rs")
    479             .exists()
    480     );
    481 }
    482 
    483 #[test]
    484 fn trade_operations_use_canonical_workflow_storage_sync_and_projection_types() {
    485     for required in [
    486         "WorkflowPlan",
    487         "TradeMutationEnvelopeV1",
    488         "ReductionInput",
    489         "Projection",
    490         "reduce_trade_records",
    491         "EventQuery",
    492         "EventPage<StoredVisibleEvent>",
    493         "PrivateArtifactMetadata",
    494         "radroots_sync::PushRequest::new",
    495     ] {
    496         assert!(
    497             TRADE.contains(required),
    498             "missing trade boundary `{required}`"
    499         );
    500     }
    501     for forbidden in [
    502         "sqlx::",
    503         "QueryBuilder",
    504         "TradeStatusView",
    505         "SdkPrivateTradeArtifact",
    506         "SdkMutationState",
    507         "TradeCommandReceipt",
    508         "struct Page",
    509         "struct TradeId",
    510     ] {
    511         assert!(
    512             !TRADE.contains(forbidden),
    513             "trade source contains retired duplicate `{forbidden}`"
    514         );
    515     }
    516     assert!(
    517         !std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    518             .join("src/trade_runtime.rs")
    519             .exists()
    520     );
    521 }
    522 
    523 #[test]
    524 fn reliability_and_diagnostics_return_canonical_storage_contracts() {
    525     for required in [
    526         "StorageReliability::begin_backup",
    527         "StorageReliability::transition_backup",
    528         "StorageReliability::begin_restore",
    529         "StorageReliability::transition_restore",
    530         "StorageReliability::integrity",
    531         "StorageReliability::status",
    532     ] {
    533         assert!(
    534             STORAGE.contains(required),
    535             "missing storage delegation `{required}`"
    536         );
    537     }
    538     for forbidden in [
    539         "struct BackupManifest",
    540         "struct IntegrityStatus",
    541         "Studio",
    542         "sqlx::",
    543     ] {
    544         assert!(
    545             !STORAGE.contains(forbidden),
    546             "storage source duplicates `{forbidden}`"
    547         );
    548     }
    549     assert!(DIAGNOSTICS.contains("radroots_storage::StorageStatus"));
    550     for forbidden in ["path:", "SqlitePool", "private_artifact"] {
    551         assert!(
    552             !DIAGNOSTICS.contains(forbidden),
    553             "diagnostics leaks `{forbidden}`"
    554         );
    555     }
    556 }
    557 
    558 #[test]
    559 fn radrootsd_adapter_is_private_explicit_versioned_and_redacted() {
    560     assert!(ROOT.contains("mod adapters;"));
    561     assert!(!ROOT.contains("pub mod adapters"));
    562     assert!(ADAPTERS.contains("cfg(feature = \"radrootsd\")"));
    563     assert!(ADAPTERS.contains("pub(crate) mod radrootsd"));
    564     assert!(RADROOTSD.contains("transport_publish::v5"));
    565     assert!(RADROOTSD.contains("reqwest::Client::builder"));
    566     assert!(RADROOTSD.contains("BearerToken(<redacted>)"));
    567     assert!(!RADROOTSD.contains("tokio::spawn"));
    568 }
    569 
    570 fn dependency_names(manifest: &str) -> BTreeSet<&str> {
    571     let dependencies = manifest
    572         .split_once("[dependencies]")
    573         .expect("dependency section")
    574         .1
    575         .split_once("[[test]]")
    576         .expect("test section")
    577         .0;
    578     dependencies
    579         .lines()
    580         .filter_map(|line| line.split_once(" = ").map(|(name, _)| name.trim()))
    581         .filter(|name| name.starts_with("radroots_"))
    582         .collect()
    583 }
    584 
    585 fn rust_files(root: &std::path::Path) -> BTreeSet<String> {
    586     let mut files = BTreeSet::new();
    587     let mut pending = vec![root.to_path_buf()];
    588     while let Some(directory) = pending.pop() {
    589         for entry in std::fs::read_dir(&directory).expect("read package source directory") {
    590             let path = entry.expect("read package source entry").path();
    591             if path.is_dir() {
    592                 pending.push(path);
    593             } else if path.extension().and_then(|value| value.to_str()) == Some("rs") {
    594                 files.insert(
    595                     path.strip_prefix(root)
    596                         .expect("source remains below root")
    597                         .to_string_lossy()
    598                         .replace(std::path::MAIN_SEPARATOR, "/"),
    599                 );
    600             }
    601         }
    602     }
    603     files
    604 }