Skip to main content

rostra_client/
lib.rs

1//! A runtime client for one Rostra identity.
2//!
3//! [`Client`] is the supported entry point. Construct it with [`Client::builder`]:
4//! omitting [`Database`] creates a temporary in-memory, light client. Supplying
5//! a durable database creates a full client and enables replication and
6//! projection tasks. Clients start read-only unless the builder receives a
7//! [`RostraIdSecretKey`] or [`Client::unlock_active`] is called later.
8//!
9//! Client-created transports default to relay-only mode so that creating a
10//! client does not expose its host's IP address. Call the builder's
11//! `public_mode(true)` only when direct IP connectivity is an intentional
12//! privacy tradeoff. A caller that supplies `iroh_endpoint` owns that
13//! endpoint's transport and privacy policy. The request handler is enabled by
14//! default in both storage modes; durable clients also start background
15//! synchronization by default.
16//!
17//! A client owns its background tasks. Clone the returned [`std::sync::Arc`] to
18//! keep the runtime alive; dropping the final strong reference aborts those
19//! tasks. [`ClientHandle`] is weak and does not extend the runtime's lifetime.
20//! There is no separate shutdown protocol.
21//!
22//! Initialization, activation, peer connection, publication, and explicit
23//! synchronization return typed errors from [`error`] or [`DbError`]. A
24//! database failure in background ingestion is logged and stops the affected
25//! worker; the client does not globally restart failed workers. Database access
26//! remains available through [`Client::db`] for integrations that need Rostra's
27//! materialized views.
28
29pub mod error;
30
31mod connection_cache;
32pub(crate) mod task;
33
34pub mod multiclient;
35
36pub mod id;
37
38mod util;
39
40use std::str::FromStr;
41
42use error::{
43    InvalidDomainSnafu, InvalidEncodingSnafu, InvalidKeySnafu, MissingValueSnafu, RRecordResult,
44    WrongTypeSnafu,
45};
46use futures::future::{self, Either};
47use pkarr::dns::Name;
48use pkarr::dns::rdata::RData;
49use snafu::{OptionExt as _, ResultExt};
50
51const RRECORD_P2P_KEY: &str = "rostra-p2p";
52const RRECORD_HEAD_KEY: &str = "rostra-head";
53const LOG_TARGET: &str = "rostra";
54
55mod client;
56mod net;
57pub use rostra_client_db::{
58    Database, DbError, SOCIAL_POST_MATERIALIZATION_SCAN_MAX, SelfFollowee,
59    SocialPostMaterialization, SocialPostMaterializationCursor, SocialPostMaterializationPage,
60};
61pub use rostra_core::id::{RostraId, RostraIdSecretKey};
62pub use rostra_core::{ExternalEventId, ShortEventId};
63
64pub use crate::client::{
65    Client, ClientHandle, ClientRef, ClientRefError, ClientRefResult, IdP2PState, NodeP2PState,
66    NodeSource, P2PState,
67};
68pub use crate::id::{CompactTicket, IdPublishedData, IdResolvedData};
69pub use crate::multiclient::{MultiClient, MultiClientError, MultiClientResult};
70
71fn get_rrecord_typed<T>(
72    packet: &pkarr::SignedPacket,
73    domain: &str,
74    key: &str,
75) -> RRecordResult<Option<T>>
76where
77    T: FromStr,
78    // <T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
79{
80    get_rrecord(packet, domain, key)?
81        .as_deref()
82        .map(T::from_str)
83        .transpose()
84        .ok()
85        .context(InvalidEncodingSnafu)
86}
87
88fn get_rrecord(
89    packet: &pkarr::SignedPacket,
90    domain: &str,
91    key: &str,
92) -> RRecordResult<Option<String>> {
93    let domain = Name::new(domain).context(InvalidDomainSnafu)?;
94    let key = Name::new(key).context(InvalidKeySnafu)?;
95    let value = match packet
96        .all_resource_records()
97        .find(|a| a.name.without(&domain).is_some_and(|sub| sub == key))
98        .map(|r| r.rdata.to_owned())
99    {
100        Some(RData::TXT(value)) => value,
101        Some(_) => WrongTypeSnafu.fail()?,
102        None => return Ok(None),
103    };
104    let v = value
105        .attributes()
106        .into_keys()
107        .next()
108        .context(MissingValueSnafu)?;
109    Ok(Some(v))
110}
111
112// Generic function that takes two futures and returns the first Ok result
113#[allow(dead_code)]
114async fn take_first_ok<T, E, F1, F2>(fut1: F1, fut2: F2) -> Result<T, E>
115where
116    F1: future::Future<Output = Result<T, E>>,
117    F2: future::Future<Output = Result<T, E>>,
118{
119    let fut1 = Box::pin(fut1);
120    let fut2 = Box::pin(fut2);
121
122    match future::select(fut1, fut2).await {
123        Either::Left((ok @ Ok(_), _)) => ok,
124        Either::Left((Err(_), fut2)) => fut2.await,
125        Either::Right((ok @ Ok(_), _)) => ok,
126        Either::Right((Err(_), fut1)) => fut1.await,
127    }
128}