use std::collections::BTreeMap;
use std::time::Duration;
use async_trait::async_trait;
use rings_core::ecc::VerificationPublicKey;
use rings_dns_relay::AnnouncementError;
use rings_dns_relay::ProxyProtocol;
use super::descriptor::announcement_of;
use super::descriptor::service_topic;
use super::descriptor::ServedPort;
use super::descriptor::ServedTxt;
use super::descriptor::ServiceDescriptor;
use super::descriptor::ServiceDescriptorBody;
use crate::error::Error;
use crate::error::Result;
use crate::prelude::rings_core::dht::Did;
use crate::registration::DhtRegistrationPublisher;
use crate::registration::LeaseTerms;
use crate::registration::RegistrationContext;
use crate::registration::RegistrationTask;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ServiceOffer {
ports: BTreeMap<u16, ProxyProtocol>,
txt: Vec<ServedTxt>,
heartbeat_interval: Duration,
ttl: Duration,
}
impl ServiceOffer {
pub fn new(
ports: BTreeMap<u16, ProxyProtocol>,
txt: Vec<ServedTxt>,
heartbeat_interval: Duration,
ttl: Duration,
) -> std::result::Result<Self, AnnouncementError> {
let offer = Self {
ports,
txt,
heartbeat_interval,
ttl,
};
announcement_of(offer.served_ports(), &offer.txt)?;
Ok(offer)
}
pub fn served_ports(&self) -> impl Iterator<Item = ServedPort> + '_ {
self.ports.iter().map(|(port, proxy_protocol)| ServedPort {
port: *port,
proxy_protocol: *proxy_protocol,
})
}
pub fn heartbeat_interval(&self) -> Duration {
self.heartbeat_interval
}
pub fn ttl(&self) -> Duration {
self.ttl
}
fn body(
&self,
did: Did,
public_key: VerificationPublicKey,
network_id: u32,
terms: LeaseTerms,
) -> ServiceDescriptorBody {
ServiceDescriptorBody {
did,
public_key,
network_id,
ports: self.served_ports().collect(),
txt: self.txt.clone(),
fresh_for_ms: terms.fresh_for_ms,
expires_at_ms: terms.expires_at_ms,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct ServiceRegistration {
offer: ServiceOffer,
publisher: DhtRegistrationPublisher<[ServiceDescriptor; 1]>,
}
impl ServiceRegistration {
pub(crate) fn new(did: Did, offer: ServiceOffer) -> Self {
Self {
publisher: DhtRegistrationPublisher::new(
service_topic(did),
offer.heartbeat_interval,
offer.ttl,
),
offer,
}
}
pub(crate) fn descriptor_at(
&self,
context: &RegistrationContext<'_>,
terms: LeaseTerms,
) -> Result<ServiceDescriptor> {
let body = self.offer.body(
context.did(),
context.delegator_verification_pubkey()?,
context.network_id(),
terms,
);
ServiceDescriptor::new_signed(body, context.message_signer()).map_err(Error::CoreError)
}
}
#[cfg_attr(rings_browser, async_trait(?Send))]
#[cfg_attr(rings_native, async_trait)]
impl RegistrationTask for ServiceRegistration {
fn name(&self) -> &'static str {
"dns-relay-services"
}
fn interval(&self) -> Duration {
self.offer.heartbeat_interval
}
async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
self.publisher
.publish_lease(context, context.now_ms(), |terms| {
self.descriptor_at(context, terms)
.map(|descriptor| [descriptor])
})
.await
.map(drop)
}
}