lib

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

package_boundary.rs (14095B)


      1 use std::collections::BTreeSet;
      2 use std::fs;
      3 use std::path::Path;
      4 
      5 const MANIFEST: &str = include_str!("../Cargo.toml");
      6 const README: &str = include_str!("../README.md");
      7 const EXAMPLE: &str = include_str!("../examples/configure_transport.rs");
      8 const PUBLIC_API: &str =
      9     include_str!("../../../contracts/api_baselines/radroots_transport_nostr.txt");
     10 const ROOT: &str = include_str!("../src/lib.rs");
     11 const ERROR: &str = include_str!("../src/error.rs");
     12 const PROFILE: &str = include_str!("../src/profile.rs");
     13 const SINK: &str = include_str!("../src/sink.rs");
     14 const SUBSCRIPTION: &str = include_str!("../src/subscription.rs");
     15 
     16 #[test]
     17 fn original_network_contract_preserves_bounded_untrusted_wire_and_standalone_fixture_provenance() {
     18     let contract: serde_json::Value = serde_json::from_str(include_str!(
     19         "../../../contracts/protocol/source_original.v1.json"
     20     ))
     21     .unwrap();
     22     assert_eq!(
     23         contract["original_event_max_utf8_bytes"],
     24         radroots_protocol::profile::SIGNED_EVENT_MAX_BYTES
     25     );
     26     assert_eq!(contract["pending_events_max"], 256);
     27     assert_eq!(contract["pending_bytes_max"], 4 * 1024 * 1024);
     28     let fixture: serde_json::Value =
     29         serde_json::from_str(include_str!("fixtures/source_original.v1.json")).unwrap();
     30     assert_eq!(
     31         fixture["provenance"]["revision"],
     32         "21ddcd6755fe7de99ea0284c88729fd6adfc5416"
     33     );
     34     assert_eq!(
     35         fixture["provenance"]["sha256"],
     36         "bd59710bedc337b5e4bdcb1c0753de06a74927027b76a0202b251b0e45d02565"
     37     );
     38     assert!(
     39         !SUBSCRIPTION
     40             .split("\n#[cfg(test)]")
     41             .next()
     42             .unwrap()
     43             .contains("raw: event.as_json()")
     44     );
     45     assert!(
     46         !include_str!("../src/source.rs")
     47             .split("\n#[cfg(test)]\nmod tests")
     48             .next()
     49             .unwrap()
     50             .contains("let raw = event.as_ref().as_json()")
     51     );
     52 }
     53 
     54 #[test]
     55 fn manifest_and_root_match_the_governed_transport_boundary() {
     56     for required in [
     57         "name = \"radroots_transport_nostr\"",
     58         "version = \"0.1.0-alpha\"",
     59         "publish = [\"crates-io\"]",
     60         "[lib]\nname = \"radroots_transport_nostr\"",
     61     ] {
     62         assert!(
     63             MANIFEST.contains(required),
     64             "manifest is missing `{required}`"
     65         );
     66     }
     67     assert!(!MANIFEST.contains("[features]"));
     68     assert_eq!(
     69         radroots_dependency_keys(MANIFEST),
     70         BTreeSet::from([
     71             "radroots_event_codec",
     72             "radroots_nostr",
     73             "radroots_protocol",
     74             "radroots_transport",
     75         ])
     76     );
     77     assert_eq!(
     78         private_modules(ROOT),
     79         BTreeSet::from([
     80             "auth",
     81             "client",
     82             "connections",
     83             "cursor",
     84             "error",
     85             "exact_delivery",
     86             "host_time",
     87             "profile",
     88             "relay",
     89             "sink",
     90             "socket_write",
     91             "source",
     92             "source_ingress",
     93             "source_original",
     94             "session_socket",
     95             "test_host",
     96             "status",
     97             "subscription"
     98         ])
     99     );
    100     for export in [
    101         "pub use client::{Config, NostrTransport, ReconnectBackoff};",
    102         "pub use cursor::RelayCursor;",
    103         "pub use error::Error;",
    104         "pub use profile::{",
    105         "pub use relay::{RelayUrl, RelayUrlPolicy};",
    106         "pub use sink::PreparedDelivery;",
    107     ] {
    108         assert!(ROOT.contains(export), "crate root is missing `{export}`");
    109     }
    110 }
    111 
    112 #[test]
    113 fn documentation_example_and_reviewed_api_baseline_are_complete() {
    114     for required in [
    115         "## Configure without connecting",
    116         "## Public surface",
    117         "## Relay and network security",
    118         "## Fetch, live subscription, delivery, and outcome behavior",
    119         "## Prepared delivery boundary",
    120         "## Deadlines, cancellation, and commit points",
    121         "## Serialization and diagnostics",
    122         "## Features and runtime requirements",
    123         "## Intended consumers",
    124         "radroots_crates_release_v1.toml",
    125         "examples/configure_transport.rs",
    126         "contracts/api_baselines/radroots_transport_nostr.txt",
    127         "Live subscriptions use the same explicit readable targets",
    128         "exact indexed single-letter tag",
    129         "Fetch reports `Complete` only after the exact subscription receives EOSE",
    130         "Deadline expiry is `Cancelled`",
    131         "exceeds the bounded inventory is `Partial`",
    132         "inclusive `since` timestamp",
    133         "permits at-least-once",
    134         "same-second events in relay arrival order",
    135         "never regresses the canonical target checkpoint",
    136         "upstream auto-close deadline",
    137         "adapter-owned worker",
    138         "validates the exact request, writable\nrelay bindings, and signed-event conversion without reading a clock, polling\nstatus, or performing relay I/O",
    139         "Executing a capability\nthrough a differently configured transport fails closed",
    140         "let _forged = PreparedDelivery {",
    141         "request: panic!(),",
    142         "skipped: panic!(),",
    143         "literal RFC1918 IPv4 or ULA IPv6 destinations",
    144         "relay URLs and resolved addresses",
    145     ] {
    146         assert!(README.contains(required), "README is missing `{required}`");
    147     }
    148     for required in [
    149         "Config::from_profile(",
    150         "RelayEndpoint::new(",
    151         "RelayProfile::explicit(",
    152         "NostrTransport::new(config, host)",
    153         "let source: &dyn EventSource",
    154         "let subscriber: &dyn EventSubscriber",
    155         "let sink: &dyn EventSink",
    156         "drop(source.status())",
    157         "let _ = subscriber",
    158         "drop(sink.status())",
    159     ] {
    160         assert!(
    161             EXAMPLE.contains(required),
    162             "example is missing `{required}`"
    163         );
    164     }
    165     for required in [
    166         "pub struct radroots_transport_nostr::Config",
    167         "pub struct radroots_transport_nostr::NostrTransport",
    168         "pub struct radroots_transport_nostr::PreparedDelivery",
    169         "pub enum radroots_transport_nostr::RelayAggregateState",
    170         "pub struct radroots_transport_nostr::RelayProfile",
    171         "pub fn radroots_transport_nostr::RelayEndpoint::new(",
    172         "pub fn radroots_transport_nostr::RelayProfile::explicit<I>(",
    173         "pub struct radroots_transport_nostr::RelayStatusReport",
    174         "pub struct radroots_transport_nostr::RelayUrl(_)",
    175         "pub enum radroots_transport_nostr::RelayUrlPolicy",
    176         "pub enum radroots_transport_nostr::Error",
    177         "impl radroots_transport::sink::EventSink for radroots_transport_nostr::NostrTransport",
    178         "impl radroots_transport::source::EventSource for radroots_transport_nostr::NostrTransport",
    179         "impl radroots_transport::source::EventSubscriber for radroots_transport_nostr::NostrTransport",
    180         "NostrTransport::begin_authentication",
    181         "NostrTransport::complete_authentication",
    182         "NostrTransport::reject_authentication",
    183         "NostrTransport::prepare_delivery",
    184         "NostrTransport::execute_prepared_delivery",
    185     ] {
    186         assert!(
    187             PUBLIC_API.contains(required),
    188             "public API baseline is missing `{required}`"
    189         );
    190     }
    191     for forbidden in [
    192         "nostr_sdk",
    193         "nostr_relay_pool",
    194         "tokio::",
    195         "radroots_storage",
    196         "radroots_outbox",
    197         "pub trait radroots_transport_nostr",
    198         "impl core::clone::Clone for radroots_transport_nostr::PreparedDelivery",
    199         "impl serde_core::ser::Serialize for radroots_transport_nostr::PreparedDelivery",
    200     ] {
    201         assert!(
    202             !PUBLIC_API.contains(forbidden),
    203             "reviewed public API baseline exposes `{forbidden}`"
    204         );
    205     }
    206 }
    207 
    208 #[test]
    209 fn public_errors_retain_no_network_or_dependency_owned_material() {
    210     let declaration = ERROR
    211         .split_once("pub enum Error {")
    212         .expect("error declaration")
    213         .1
    214         .split_once("\n}")
    215         .expect("error declaration end")
    216         .0;
    217     for forbidden in [
    218         "url:",
    219         "address:",
    220         "reason:",
    221         "String",
    222         "url::",
    223         "nostr_sdk::",
    224         "nostr_relay_pool::",
    225     ] {
    226         assert!(
    227             !declaration.contains(forbidden),
    228             "public error retains forbidden network material `{forbidden}`"
    229         );
    230     }
    231 }
    232 
    233 #[test]
    234 fn preparation_is_sealed_and_separated_from_execution_io() {
    235     let prepare = SINK
    236         .split_once("pub fn prepare_delivery(")
    237         .expect("prepared delivery function")
    238         .1
    239         .split_once("pub fn execute_prepared_delivery(")
    240         .expect("execution boundary")
    241         .0;
    242     for forbidden in [".await", "unix_time_ms", "self.status", ".publish("] {
    243         assert!(
    244             !prepare.contains(forbidden),
    245             "delivery preparation contains I/O authority `{forbidden}`"
    246         );
    247     }
    248     for required in [
    249         "pub struct PreparedDelivery",
    250         "#[must_use = \"prepared delivery must be durably bound before execution or deliberately discarded\"]",
    251         "request: DeliveryRequest",
    252         "event: ExactEvent",
    253         "config: crate::Config",
    254         "formatter.write_str(\"PreparedDelivery([redacted])\")",
    255         "pub const fn request(&self) -> &DeliveryRequest",
    256     ] {
    257         assert!(
    258             SINK.contains(required),
    259             "prepared boundary is missing `{required}`"
    260         );
    261     }
    262     for forbidden in [
    263         "impl Clone for PreparedDelivery",
    264         "derive(Clone",
    265         "pub fn new(",
    266         "pub request:",
    267         "pub event:",
    268         "pub config:",
    269     ] {
    270         assert!(
    271             !prepare.contains(forbidden),
    272             "prepared boundary exposes `{forbidden}`"
    273         );
    274     }
    275 }
    276 
    277 #[test]
    278 fn relay_profiles_have_no_implicit_destination_or_policy_constructor() {
    279     for forbidden in [
    280         "DEFAULT_PUBLIC_RELAY",
    281         "pub fn public",
    282         "pub fn simulator",
    283         "pub fn device",
    284     ] {
    285         assert!(!ROOT.contains(forbidden));
    286         assert!(!PROFILE.contains(forbidden));
    287         assert!(!PUBLIC_API.contains(forbidden));
    288     }
    289     for required in [
    290         "pub fn new(",
    291         "policy: RelayUrlPolicy",
    292         "access: RelayAccess",
    293         "IntoIterator<Item = RelayEndpoint>",
    294         ".take(crate::client::MAX_RELAYS + 1)",
    295         "Error::RelayProfilePolicyMismatch",
    296     ] {
    297         assert!(
    298             PROFILE.contains(required),
    299             "profile is missing `{required}`"
    300         );
    301     }
    302 }
    303 
    304 fn radroots_dependency_keys(manifest: &str) -> BTreeSet<&str> {
    305     dependency_keys(manifest)
    306         .into_iter()
    307         .filter(|key| key.starts_with("radroots_"))
    308         .collect()
    309 }
    310 
    311 fn dependency_keys(manifest: &str) -> BTreeSet<&str> {
    312     manifest
    313         .split_once("[dependencies]")
    314         .map(|(_, dependencies)| dependencies)
    315         .unwrap_or_default()
    316         .lines()
    317         .skip(1)
    318         .take_while(|line| !line.starts_with('['))
    319         .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim()))
    320         .filter(|key| !key.is_empty())
    321         .collect()
    322 }
    323 
    324 fn private_modules(root: &str) -> BTreeSet<&str> {
    325     root.lines()
    326         .filter_map(|line| line.trim().strip_prefix("mod "))
    327         .filter_map(|module| module.strip_suffix(';'))
    328         .collect()
    329 }
    330 
    331 #[test]
    332 fn adapter_owns_no_storage_outbox_or_orchestration_surface() {
    333     for forbidden in [
    334         "radroots_event_store",
    335         "radroots_outbox",
    336         "radroots_storage",
    337         "publish_claimed",
    338         "fetch_and_ingest",
    339         "projection_refresh",
    340         "retry_schedule",
    341     ] {
    342         assert!(!MANIFEST.contains(forbidden));
    343         assert!(!ROOT.contains(forbidden));
    344     }
    345 
    346     let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    347     let source_files = fs::read_dir(source_root)
    348         .expect("source directory")
    349         .map(|entry| {
    350             entry
    351                 .expect("source entry")
    352                 .file_name()
    353                 .into_string()
    354                 .expect("utf-8 source name")
    355         })
    356         .collect::<BTreeSet<_>>();
    357     assert_eq!(
    358         source_files,
    359         BTreeSet::from([
    360             "auth.rs".to_owned(),
    361             "client.rs".to_owned(),
    362             "connections.rs".to_owned(),
    363             "cursor.rs".to_owned(),
    364             "error.rs".to_owned(),
    365             "exact_delivery.rs".to_owned(),
    366             "host_time.rs".to_owned(),
    367             "host_time_browser.rs".to_owned(),
    368             "lib.rs".to_owned(),
    369             "native_backend_tests.rs".to_owned(),
    370             "profile.rs".to_owned(),
    371             "relay.rs".to_owned(),
    372             "sink.rs".to_owned(),
    373             "socket_write.rs".to_owned(),
    374             "socket_write_tests.rs".to_owned(),
    375             "source.rs".to_owned(),
    376             "source_budget.rs".to_owned(),
    377             "source_ingress.rs".to_owned(),
    378             "source_original.rs".to_owned(),
    379             "source_original_queue_tests.rs".to_owned(),
    380             "source_original_tests.rs".to_owned(),
    381             "source_paging_tests.rs".to_owned(),
    382             "source_window.rs".to_owned(),
    383             "session_socket.rs".to_owned(),
    384             "session_socket_tests.rs".to_owned(),
    385             "test_host.rs".to_owned(),
    386             "status.rs".to_owned(),
    387             "subscription.rs".to_owned(),
    388         ])
    389     );
    390 
    391     for required in [
    392         "impl EventSubscriber for NostrTransport",
    393         "SubscribeAutoCloseOptions::default()",
    394         "ReqExitPolicy::WaitDurationAfterEOSE(query.timeout)",
    395         "self.seen_event_ids.contains(event_id.as_str())",
    396         "resume_cursors",
    397         "let cursor_advances = self",
    398         "self.terminate(SubscriptionEndReason::Cancelled)",
    399     ] {
    400         assert!(
    401             SUBSCRIPTION.contains(required),
    402             "subscription adapter is missing `{required}`"
    403         );
    404     }
    405     for forbidden in [
    406         "tokio::spawn",
    407         "spawn_blocking",
    408         "std::thread",
    409         "process::",
    410         "global_default",
    411     ] {
    412         assert!(
    413             !SUBSCRIPTION.contains(forbidden),
    414             "subscription adapter contains forbidden authority `{forbidden}`"
    415         );
    416     }
    417 }