use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use async_trait::async_trait;
use bytes::Bytes;
use futures::lock::Mutex as AsyncMutex;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::dht::RelayCustody;
use rings_core::ecc::PublicKey;
use rings_core::ecc::VerificationPublicKey;
use rings_core::lifecycle::StopToken;
use rings_core::message::ChordStorageInterface;
use rings_core::message::MessageSigner;
use rings_core::message::ScopedStorage;
use rings_core::swarm::storage_api::StoreReceipt;
use rings_core::utils::get_epoch_ms;
use rings_runtime::MaybeSendSync;
use crate::descriptor::heard_descriptors;
use crate::descriptor::registry_lease;
use crate::descriptor::RegistryElement;
use crate::descriptor::SignedDescriptor;
use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionProcessEpochCell;
use crate::online::OnlineNodeCapabilities;
use crate::online::OnlineNodeDescriptor;
use crate::online::OnlineNodeDescriptorBody;
use crate::online::OnlineNodeType;
use crate::online::ONLINE_NODES_TOPIC;
use crate::processor::stoppable_storage_error;
use crate::processor::Processor;
const DEFAULT_ONLINE_NODE_HEARTBEAT_INTERVAL_SECS: u64 = 30;
const DEFAULT_ONLINE_NODE_TTL_SECS: u64 = 90;
pub(crate) const fn default_online_node_heartbeat_interval_secs() -> u64 {
DEFAULT_ONLINE_NODE_HEARTBEAT_INTERVAL_SECS
}
pub(crate) const fn default_online_node_ttl_secs() -> u64 {
DEFAULT_ONLINE_NODE_TTL_SECS
}
pub(crate) fn default_online_node_type() -> OnlineNodeType {
#[cfg(feature = "ffi")]
{
OnlineNodeType::Ffi
}
#[cfg(all(not(feature = "ffi"), feature = "browser", target_family = "wasm"))]
{
OnlineNodeType::Browser
}
#[cfg(all(
not(feature = "ffi"),
not(all(feature = "browser", target_family = "wasm"))
))]
{
OnlineNodeType::Native
}
}
pub(crate) const fn default_advertise_presence() -> bool {
true
}
pub(crate) fn registry_refresh_bound() -> Duration {
registry_lease() / 2
}
pub(crate) const fn early_publish_armed(heartbeat: bool, edges_at_start: usize) -> bool {
heartbeat && edges_at_start == 0
}
pub(crate) const fn republish_due(armed: bool, admitted_edges: usize) -> bool {
armed && admitted_edges > 0
}
pub(crate) fn validate_registration_timing(
registry: &str,
advertise_setting: &str,
advertised: bool,
heartbeat_interval: Duration,
ttl: Duration,
) -> Result<()> {
if !advertised {
return Ok(());
}
let keys = TimingKeys {
heartbeat_interval: &format!("{registry}_heartbeat_interval"),
ttl: &format!("{registry}_ttl"),
enabled_by: Some(advertise_setting),
};
validate_schedule(&keys, heartbeat_interval, ttl)
}
pub(crate) struct TimingKeys<'a> {
pub(crate) heartbeat_interval: &'a str,
pub(crate) ttl: &'a str,
pub(crate) enabled_by: Option<&'a str>,
}
pub(crate) fn validate_schedule(
keys: &TimingKeys<'_>,
heartbeat_interval: Duration,
ttl: Duration,
) -> Result<()> {
let TimingKeys {
heartbeat_interval: heartbeat_key,
ttl: ttl_key,
enabled_by,
} = keys;
if heartbeat_interval >= ttl {
let condition = enabled_by
.map(|switch| format!(" when {switch} is enabled"))
.unwrap_or_default();
return Err(Error::InvalidConfig(format!(
"{heartbeat_key} ({heartbeat_interval:?}) must be less than {ttl_key} \
({ttl:?}){condition}"
)));
}
let lease = registry_lease();
if ttl > lease {
return Err(Error::InvalidConfig(format!(
"{ttl_key} ({ttl:?}) must be at most {lease:?}, the registry lease"
)));
}
let bound = registry_refresh_bound();
if heartbeat_interval >= bound {
return Err(Error::InvalidConfig(format!(
"{heartbeat_key} ({heartbeat_interval:?}) must be less than {bound:?}, half the \
registry lease"
)));
}
Ok(())
}
pub(crate) struct RegistrationContext<'a> {
processor: &'a Processor,
stop: StopToken,
receipts: Option<Mutex<Vec<StoreReceipt>>>,
}
impl<'a> RegistrationContext<'a> {
pub(crate) fn new(processor: &'a Processor) -> Self {
Self::new_with_stop(processor, StopToken::never())
}
pub(crate) const fn new_with_stop(processor: &'a Processor, stop: StopToken) -> Self {
Self {
processor,
stop,
receipts: None,
}
}
pub(crate) fn reporting(mut self) -> Self {
self.receipts = Some(Mutex::new(Vec::new()));
self
}
pub(crate) fn into_receipts(self) -> Option<Vec<StoreReceipt>> {
self.receipts.map(|receipts| {
receipts
.into_inner()
.unwrap_or_else(PoisonError::into_inner)
})
}
pub(crate) fn should_stop(&self) -> bool {
self.stop.should_stop()
}
pub(crate) fn ensure_running(&self) -> Result<()> {
if self.should_stop() {
return Err(Error::RegistrationStopped);
}
Ok(())
}
pub(crate) fn did(&self) -> Did {
self.processor.did()
}
pub(crate) fn network_id(&self) -> u32 {
self.processor.swarm.network_id()
}
pub(crate) fn storage_redundancy(&self) -> u16 {
self.processor.swarm.storage_redundancy()
}
pub(crate) fn dht_virtual_nodes(&self) -> u16 {
self.processor.swarm.dht_virtual_nodes()
}
pub(crate) fn relay_custody(&self) -> RelayCustody {
self.processor.swarm.dht().relay_custody()
}
pub(crate) fn delegator_verification_pubkey(&self) -> Result<VerificationPublicKey> {
self.processor
.swarm
.delegator_verification_pubkey()
.map_err(Error::CoreError)
}
pub(crate) fn delegatee_key(&self) -> DelegateeKey {
self.processor.delegatee_key()
}
pub(crate) fn message_signer(&self) -> MessageSigner<DelegateeKey> {
MessageSigner::new(self.delegatee_key(), self.network_id())
}
fn storage(&self) -> ScopedStorage<'_> {
self.processor.swarm.scoped_storage(self.stop.clone())
}
pub(crate) async fn append_data(&self, topic: &str, data: Bytes) -> Result<()> {
let Some(receipts) = &self.receipts else {
return self
.storage()
.storage_append_data(topic, data)
.await
.map_err(stoppable_storage_error);
};
let receipt = self
.storage()
.storage_append_data_reported(topic, data)
.await
.map_err(stoppable_storage_error)?;
receipts
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(receipt);
Ok(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct LeaseTerms {
pub(crate) fresh_for_ms: u64,
pub(crate) expires_at_ms: u128,
}
pub(crate) trait LeaseDescriptors: Clone {
type Descriptor: SignedDescriptor + RegistryElement;
fn as_slice(&self) -> &[Self::Descriptor];
fn heard_at(self, heartbeat_at_ms: u128) -> Self;
}
impl<D> LeaseDescriptors for [D; 1]
where D: SignedDescriptor + RegistryElement + Clone
{
type Descriptor = D;
fn as_slice(&self) -> &[D] {
self
}
fn heard_at(self, heartbeat_at_ms: u128) -> Self {
self.map(|descriptor| descriptor.heard_at(heartbeat_at_ms))
}
}
impl<D> LeaseDescriptors for Vec<D>
where D: SignedDescriptor + RegistryElement + Clone
{
type Descriptor = D;
fn as_slice(&self) -> &[D] {
self
}
fn heard_at(self, heartbeat_at_ms: u128) -> Self {
self.into_iter()
.map(|descriptor| descriptor.heard_at(heartbeat_at_ms))
.collect()
}
}
#[derive(Clone, Debug)]
struct HeldLease<S> {
terms: LeaseTerms,
delegatee_public_key: PublicKey<33>,
bodies: Vec<Vec<u8>>,
descriptors: S,
elements: Vec<Bytes>,
}
#[derive(Clone, Debug)]
pub(crate) struct DhtRegistrationPublisher<S> {
topic: String,
renewal_margin_ms: u128,
fresh_for_ms: u64,
held: Arc<AsyncMutex<Option<HeldLease<S>>>>,
}
impl<S: LeaseDescriptors> DhtRegistrationPublisher<S> {
pub(crate) fn new(
topic: impl Into<String>,
heartbeat_interval: Duration,
fresh_for: Duration,
) -> Self {
Self {
topic: topic.into(),
renewal_margin_ms: heartbeat_interval.as_millis().saturating_mul(2),
fresh_for_ms: u64::try_from(fresh_for.as_millis()).unwrap_or(u64::MAX),
held: Arc::new(AsyncMutex::new(None)),
}
}
pub(crate) async fn publish_lease(
&self,
context: &RegistrationContext<'_>,
now_ms: u128,
descriptors_for: impl Fn(LeaseTerms) -> Result<S>,
) -> Result<S> {
let mut held = self.held.lock().await;
context.ensure_running()?;
let delegatee_public_key = context.delegatee_key().delegatee_public_key();
let kept = match held.as_ref() {
Some(lease)
if lease.delegatee_public_key == delegatee_public_key
&& now_ms.saturating_add(self.renewal_margin_ms)
< lease.terms.expires_at_ms =>
{
let bodies = signing_data(descriptors_for(lease.terms)?.as_slice())?;
(bodies == lease.bodies).then(|| lease.clone())
}
_ => None,
};
let lease = match kept {
Some(lease) => lease,
None => {
let nominal_expires_at_ms = now_ms.saturating_add(registry_lease().as_millis());
let max_admissible_expires_at_ms = nominal_expires_at_ms
.saturating_add(rings_core::consts::TS_OFFSET_TOLERANCE_MS);
let terms =
LeaseTerms {
fresh_for_ms: self.fresh_for_ms,
expires_at_ms: nominal_expires_at_ms
.max(held.as_ref().map_or(0, |previous| {
previous.terms.expires_at_ms.saturating_add(1)
}))
.min(max_admissible_expires_at_ms),
};
let descriptors = descriptors_for(terms)?;
let lease = HeldLease {
terms,
delegatee_public_key,
bodies: signing_data(descriptors.as_slice())?,
elements: descriptors
.as_slice()
.iter()
.map(|descriptor| descriptor.to_element().map_err(Error::CoreError))
.collect::<Result<_>>()?,
descriptors,
};
*held = Some(lease.clone());
lease
}
};
for element in &lease.elements {
context.ensure_running()?;
context.append_data(&self.topic, element.clone()).await?;
}
Ok(lease.descriptors.heard_at(now_ms))
}
}
fn signing_data<D: SignedDescriptor>(descriptors: &[D]) -> Result<Vec<Vec<u8>>> {
descriptors
.iter()
.map(|descriptor| {
descriptor
.descriptor_signing_data()
.map_err(Error::CoreError)
})
.collect()
}
#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
pub(crate) trait RegistrationTask: MaybeSendSync {
fn name(&self) -> &'static str;
fn interval(&self) -> Duration;
async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()>;
}
#[derive(Clone, Debug)]
pub struct OnlineNodeRegistration {
heartbeat_interval: Duration,
node_type: OnlineNodeType,
started_at_ms: u128,
endpoint_hint: Option<String>,
onion_relay: Option<OnionProcessEpochCell>,
publisher: DhtRegistrationPublisher<[OnlineNodeDescriptor; 1]>,
}
impl OnlineNodeRegistration {
pub fn new(
heartbeat_interval: Duration,
ttl: Duration,
node_type: OnlineNodeType,
endpoint_hint: Option<String>,
onion_relay: Option<OnionProcessEpochCell>,
) -> Self {
Self {
heartbeat_interval,
node_type,
started_at_ms: get_epoch_ms(),
endpoint_hint,
onion_relay,
publisher: DhtRegistrationPublisher::new(ONLINE_NODES_TOPIC, heartbeat_interval, ttl),
}
}
pub(crate) fn descriptor_at(
&self,
context: &RegistrationContext<'_>,
terms: LeaseTerms,
) -> Result<OnlineNodeDescriptor> {
OnlineNodeDescriptor::new_signed(
OnlineNodeDescriptorBody {
did: context.did(),
public_key: context.delegator_verification_pubkey()?,
delegatee_public_key: context.delegatee_key().delegatee_public_key(),
node_type: self.node_type.clone(),
network_id: context.network_id(),
storage_redundancy: context.storage_redundancy(),
dht_virtual_nodes: context.dht_virtual_nodes(),
capabilities: OnlineNodeCapabilities {
onion_relay: self.onion_relay.as_ref().map(OnionProcessEpochCell::get),
relay_custody: context.relay_custody(),
},
endpoint_hint: self.endpoint_hint.clone(),
started_at_ms: self.started_at_ms,
fresh_for_ms: terms.fresh_for_ms,
expires_at_ms: terms.expires_at_ms,
version: crate::util::build_version(),
},
context.message_signer(),
)
.map_err(Error::CoreError)
}
pub(crate) async fn publish_descriptor(
&self,
context: &RegistrationContext<'_>,
) -> Result<OnlineNodeDescriptor> {
let [descriptor] = self
.publisher
.publish_lease(context, get_epoch_ms(), |terms| {
self.descriptor_at(context, terms)
.map(|descriptor| [descriptor])
})
.await?;
Ok(descriptor)
}
pub fn descriptors_from_entry(
entry: &rings_core::dht::entry::Entry,
) -> Vec<OnlineNodeDescriptor> {
heard_descriptors(entry)
}
}
#[cfg_attr(all(feature = "browser", target_family = "wasm"), async_trait(?Send))]
#[cfg_attr(not(all(feature = "browser", target_family = "wasm")), async_trait)]
impl RegistrationTask for OnlineNodeRegistration {
fn name(&self) -> &'static str {
"online-node"
}
fn interval(&self) -> Duration {
self.heartbeat_interval
}
async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
self.publish_descriptor(context).await.map(|_| ())
}
}
mod readiness;
pub(crate) use readiness::RegistrationReadiness;
#[cfg(test)]
mod test_first_edge;