pub fn endpoint_id_from_txt_name(name: &str) -> Result<EndpointId, ParseError>Expand description
Parses a EndpointId from iroh DNS name.
endpoint_id_from_txt_name
pub fn endpoint_id_from_txt_name(name: &str) -> Result<EndpointId, ParseError>Expand description
Parses a [EndpointId] from iroh DNS name.
Takes a DNS name and expects the first label to be IROH_TXT_NAME and the second
-label to be a z32 encoded EndpointId. Ignores subsequent labels.
EndpointId]. Ignores subsequent labels.
Module attrs
Expand description
Support for handling DNS resource records for dialing by EndpointId.
Module attrs
Expand description
Support for handling DNS resource records for dialing by [EndpointId].
DNS records are published under the following names:
_iroh.<z32-endpoint-id>.<origin-domain> TXT
The returned TXT records must contain a string value of the form key=value as defined
in RFC1464.
Structs§
- TxtAttrs
- Attributes parsed from
IROH_TXT_NAMETXT records.
Enums§
- Encoding
Error - Iroh
Attr - The attributes supported by iroh for
IROH_TXT_NAMEDNS resource records. - Parse
Error
Constants§
- IROH_
TXT_ NAME - The DNS name for the iroh TXT record.
Functions§
- endpoint_
id_ from_ txt_ name - Parses a
EndpointIdfrom iroh DNS name.
Structs§
- TxtAttrs
- Attributes parsed from
IROH_TXT_NAMETXT records.
Enums§
- Encoding
Error - Iroh
Attr - The attributes supported by iroh for
IROH_TXT_NAMEDNS resource records. - Parse
Error
Constants§
- IROH_
TXT_ NAME - The DNS name for the iroh TXT record.
Functions§
- endpoint_
id_ from_ txt_ name - Parses a [
EndpointId] from iroh DNS name.
FromStr and
Display.
Implementations§
Source§impl<T: FromStr + Display + Hash + Ord> TxtAttrs<T>
impl<T: FromStr + Display + Hash + Ord> TxtAttrs<T>
Sourcepub fn from_parts(
- endpoint_id: EndpointId,
+ endpoint_id: EndpointId,
pairs: impl Iterator<Item = (T, String)>,
) -> Self
pub fn from_parts( - endpoint_id: EndpointId, + endpoint_id: EndpointId, pairs: impl Iterator<Item = (T, String)>, ) -> Self
Creates TxtAttrs from an endpoint id and an iterator of key-value pairs.
Sourcepub fn from_strings(
- endpoint_id: EndpointId,
+ endpoint_id: EndpointId,
strings: impl Iterator<Item = String>,
) -> Result<Self, ParseError>
pub fn from_strings( - endpoint_id: EndpointId, + endpoint_id: EndpointId, strings: impl Iterator<Item = String>, ) -> Result<Self, ParseError>
Creates TxtAttrs from an endpoint id and an iterator of “{key}={value}” strings.
Sourcepub fn endpoint_id(&self) -> EndpointId
pub fn endpoint_id(&self) -> EndpointId
Returns the endpoint id.
+Sourcepub fn endpoint_id(&self) -> EndpointId
pub fn endpoint_id(&self) -> EndpointId
Returns the endpoint id.
Sourcepub fn from_txt_lookup(
name: String,
lookup: impl Iterator<Item = impl Display>,
@@ -24,10 +24,10 @@ values that implement Sourcepub fn to_txt_strings(&self) -> impl Iterator<Item = String> + '_
Converts to {key}={value} strings.
pub fn from_txt_lookup(
name: String,
lookup: impl Iterator<Item = impl Display>,
@@ -24,10 +24,10 @@ values that implement Sourcepub fn to_txt_strings(&self) -> impl Iterator<Item = String> + '_
Converts to {key}={value} strings.
pub fn to_txt_strings(&self) -> impl Iterator<Item = String> + '_
Converts to {key}={value} strings.
Sourcepub fn to_pkarr_signed_packet(
&self,
- secret_key: &SecretKey,
+ secret_key: &SecretKey,
ttl: u32,
) -> Result<SignedPacket, EncodingError>
pub fn to_pkarr_signed_packet( &self, - secret_key: &SecretKey, + secret_key: &SecretKey, ttl: u32, ) -> Result<SignedPacket, EncodingError>
Creates a pkarr::SignedPacket
This constructs a DNS packet and signs it with a SecretKey.
This constructs a DNS packet and signs it with a [SecretKey].
Trait Implementations§
Auto Trait Implementations§
impl<T> Freeze for TxtAttrs<T>
impl<T> RefUnwindSafe for TxtAttrs<T>where
T: RefUnwindSafe,
impl<T> Send for TxtAttrs<T>where
T: Send,
impl<T> Sync for TxtAttrs<T>where
diff --git a/pr/4026/docs/iroh_dns/enum.DecodingError.html b/pr/4026/docs/iroh_dns/enum.DecodingError.html
index 43b41092d1..ba55e0c71f 100644
--- a/pr/4026/docs/iroh_dns/enum.DecodingError.html
+++ b/pr/4026/docs/iroh_dns/enum.DecodingError.html
@@ -8,12 +8,12 @@
meta: Meta,
},
InvalidKey {
- source: KeyParsingError,
+ source: KeyParsingError,
meta: Meta,
},
}Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.Trait Implementations§
Source§impl Debug for DecodingError
Source§impl Display for DecodingError
Source§impl Error for DecodingError
Source§fn source(&self) -> Option<&(dyn Error + 'static)>
Returns the lower-level source of this error, if any. Read more1.0.0 · Source§fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()Source§impl From<DecodingError> for AnyError
Source§fn from(value: DecodingError) -> AnyError
Converts to this type from the input type.Source§impl From<DecodingError> for ParseError
Source§fn from(source: DecodingError) -> Self
Converts to this type from the input type.Source§impl StackError for DecodingError
Source§fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)
Returns this error as a std error reference.Source§fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>
Returns this error as a std error.Source§fn fmt_message(&self, f: &mut Formatter<'_>) -> Result
Returns the next source in the chain, if any.Source§fn is_transparent(&self) -> bool
Returns whether this error is transparent and should be skipped in reports.Auto Trait Implementations§
§impl Freeze for DecodingError
§impl RefUnwindSafe for DecodingError
§impl Send for DecodingError
§impl Sync for DecodingError
§impl Unpin for DecodingError
§impl UnwindSafe for DecodingError
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
diff --git a/pr/4026/docs/iroh_dns/index.html b/pr/4026/docs/iroh_dns/index.html
index f8d2fcb8a6..e276c05581 100644
--- a/pr/4026/docs/iroh_dns/index.html
+++ b/pr/4026/docs/iroh_dns/index.html
@@ -1,5 +1,5 @@
iroh_dns - Rust Crate iroh_dns
Expand description
DNS-based endpoint discovery for iroh.
This crate contains the core types for publishing and resolving iroh endpoint
information via DNS, using the pkarr signed packet format.
-Modules§
- attrs
- Support for handling DNS resource records for dialing by
EndpointId. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for
EndpointId to encode to and decode from z-base-32,
+
Modules§
- attrs
- Support for handling DNS resource records for dialing by [
EndpointId]. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for [
EndpointId] to encode to and decode from z-base-32,
which is the encoding used by pkarr domain names.
\ No newline at end of file
diff --git a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
index 23b64647b5..fcb8d03fff 100644
--- a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
+++ b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
@@ -3,7 +3,7 @@
The DNS packet must be at most 1000 bytes. Total max size is 1104 bytes.
Implementations§
Source§impl SignedPacket
Sourcepub fn from_txt_strings(
- secret_key: &SecretKey,
+ secret_key: &SecretKey,
name: &str,
values: impl IntoIterator<Item = impl AsRef<str>>,
ttl: u32,
@@ -11,7 +11,7 @@
This is the common case: multiple TXT values under the same DNS name (e.g. "_iroh").
Sourcepub fn from_bytes(bytes: &[u8]) -> Result<SignedPacket, SignedPacketVerifyError>
Parse and verify a signed packet from its wire representation.
Sourcepub fn from_relay_payload(
- public_key: &PublicKey,
+ public_key: &PublicKey,
payload: &[u8],
) -> Result<SignedPacket, SignedPacketVerifyError>
Create from a public key and relay payload (signature + timestamp + dns).
Sourcepub fn from_bytes_unchecked(
@@ -20,8 +20,8 @@
Still validates minimum length and DNS parsing.
Sourcepub fn to_relay_payload(&self) -> Vec<u8> ⓘ
Return the relay payload (everything after the public key).
-Sourcepub fn public_key(&self) -> PublicKey
Return the public key.
-Sourcepub fn public_key(&self) -> PublicKey
Return the public key.
+Sourcepub fn encoded_packet(&self) -> &[u8] ⓘ
Return the encoded DNS packet bytes.
Sourcepub fn txt_records(&self, name: &str) -> Vec<String>
Iterate over TXT records under a specific DNS name.
diff --git a/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html b/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html
index 4ee78decb2..bdd3ab70e4 100644
--- a/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html
+++ b/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html
@@ -1,9 +1,9 @@
EndpointIdExt in iroh_dns - Rust EndpointIdExt
pub trait EndpointIdExt {
// Required methods
fn to_z32(&self) -> String;
- fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
-}
Expand description
Extension methods for EndpointId to encode to and decode from z-base-32,
+ fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
+}Expand description
Extension methods for [EndpointId] to encode to and decode from z-base-32,
which is the encoding used by pkarr domain names.
-
Required Methods§
Sourcefn to_z32(&self) -> String
Encodes a EndpointId in z-base-32 encoding.
-Sourcefn from_z32(s: &str) -> Result<EndpointId, DecodingError>
Parses a EndpointId from z-base-32 encoding.
-Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl EndpointIdExt for EndpointId
Implementors§
\ No newline at end of file
+Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl EndpointIdExt for EndpointId
Implementors§
\ No newline at end of file
diff --git a/pr/4026/docs/src/iroh_dns_server/store/signed_packets.rs.html b/pr/4026/docs/src/iroh_dns_server/store/signed_packets.rs.html
index 4c2ea9cbb9..b1b3ebe2ba 100644
--- a/pr/4026/docs/src/iroh_dns_server/store/signed_packets.rs.html
+++ b/pr/4026/docs/src/iroh_dns_server/store/signed_packets.rs.html
@@ -6,7 +6,7 @@
6 time::{Duration, SystemTime},
7};
8
-9use iroh_dns::pkarr::SignedPacket;
+9use iroh_dns::pkarr::{SignedPacket, Timestamp};
10use n0_error::{Result, StackResultExt, StdResultExt, anyerr};
11use redb::{
12 Database, MultimapTableDefinition, ReadableDatabase, ReadableTable, TableDefinition,
@@ -59,7 +59,7 @@
59 res: oneshot::Sender<Snapshot>,
60 },
61 CheckExpired {
-62 time: u64,
+62 time: Timestamp,
63 key: PublicKeyBytes,
64 },
65}
@@ -216,7 +216,7 @@
216 Some(packet) => {
217 let expiry_us = self.options.eviction.as_micros() as u64;
218 let expired =
-219 iroh_dns::pkarr::Timestamp::from_micros(timestamp_now() - expiry_us);
+219 Timestamp::from_micros(Timestamp::now().as_micros() - expiry_us);
220 if packet.timestamp() < expired {
221 tables
222 .update_time
@@ -249,313 +249,306 @@
249 }
250}
251
-252fn fmt_time(t: u64) -> String {
-253 let duration = std::time::Duration::from_micros(t);
+252fn fmt_time(t: Timestamp) -> String {
+253 let duration = std::time::Duration::from_micros(t.as_micros());
254 humantime::format_rfc3339_micros(SystemTime::UNIX_EPOCH + duration).to_string()
255}
256
-257fn timestamp_now() -> u64 {
-258 SystemTime::now()
-259 .duration_since(SystemTime::UNIX_EPOCH)
-260 .expect("system time before UNIX epoch")
-261 .as_micros() as u64
+257/// A struct similar to [`redb::Table`] but for all tables that make up the
+258/// signed packet store.
+259pub(super) struct Tables<'a> {
+260 pub signed_packets: redb::Table<'a, &'static SignedPacketsKey, &'static [u8]>,
+261 pub update_time: redb::MultimapTable<'a, [u8; 8], SignedPacketsKey>,
262}
263
-264/// A struct similar to [`redb::Table`] but for all tables that make up the
-265/// signed packet store.
-266pub(super) struct Tables<'a> {
-267 pub signed_packets: redb::Table<'a, &'static SignedPacketsKey, &'static [u8]>,
-268 pub update_time: redb::MultimapTable<'a, [u8; 8], SignedPacketsKey>,
-269}
-270
-271impl<'txn> Tables<'txn> {
-272 pub fn new(tx: &'txn redb::WriteTransaction) -> result::Result<Self, redb::TableError> {
-273 Ok(Self {
-274 signed_packets: tx.open_table(SIGNED_PACKETS_TABLE)?,
-275 update_time: tx.open_multimap_table(UPDATE_TIME_TABLE)?,
-276 })
-277 }
-278}
-279
-280pub(super) struct Snapshot {
-281 #[allow(dead_code)]
-282 pub signed_packets: redb::ReadOnlyTable<&'static SignedPacketsKey, &'static [u8]>,
-283 pub update_time: redb::ReadOnlyMultimapTable<[u8; 8], SignedPacketsKey>,
-284}
-285
-286impl Snapshot {
-287 pub fn new(db: &Database) -> Result<Self> {
-288 let tx = db.begin_read().anyerr()?;
-289 Ok(Self {
-290 signed_packets: tx.open_table(SIGNED_PACKETS_TABLE).anyerr()?,
-291 update_time: tx.open_multimap_table(UPDATE_TIME_TABLE).anyerr()?,
-292 })
-293 }
-294}
-295
-296impl SignedPacketStore {
-297 pub fn persistent(
-298 path: impl AsRef<Path>,
-299 options: Options,
-300 metrics: Arc<Metrics>,
-301 ) -> Result<Self> {
-302 let path = path.as_ref();
-303 info!("loading packet database from {}", path.to_string_lossy());
-304 if let Some(parent) = path.parent() {
-305 std::fs::create_dir_all(parent).with_std_context(|_| {
-306 format!(
-307 "failed to create database directory at {}",
-308 path.to_string_lossy()
-309 )
-310 })?;
-311 }
-312 let db = Database::builder()
-313 .create(path)
-314 .std_context("failed to open packet database")?;
-315 Self::open(db, options, metrics)
-316 }
-317
-318 pub fn in_memory(options: Options, metrics: Arc<Metrics>) -> Result<Self> {
-319 info!("using in-memory packet database");
-320 let db = Database::builder()
-321 .create_with_backend(InMemoryBackend::new())
-322 .anyerr()?;
-323 Self::open(db, options, metrics)
-324 }
-325
-326 pub fn open(db: Database, options: Options, metrics: Arc<Metrics>) -> Result<Self> {
-327 // create tables
-328 let write_tx = db.begin_write().anyerr()?;
-329 let _ = Tables::new(&write_tx).anyerr()?;
-330 write_tx.commit().anyerr()?;
-331 let (send, recv) = mpsc::channel(1024);
-332 let send2 = send.clone();
-333 let cancel = CancellationToken::new();
-334 let cancel2 = cancel.clone();
-335 let cancel3 = cancel.clone();
-336 let actor = Actor {
-337 db,
-338 recv: PeekableReceiver::new(recv),
-339 cancel: cancel2,
-340 options,
-341 metrics,
-342 };
-343 // start an io thread and donate it to the tokio runtime so we can do blocking IO
-344 // inside the thread despite being in a tokio runtime
-345 let _write_thread = IoThread::new("packet-store-actor", move || actor.run())?;
-346 let _evict_thread = IoThread::new("packet-store-evict", move || {
-347 evict_task(send2, options, cancel3)
-348 })?;
-349 Ok(Self {
-350 send,
-351 cancel,
-352 _write_thread,
-353 _evict_thread,
-354 })
-355 }
-356
-357 pub async fn upsert(&self, packet: SignedPacket) -> Result<bool> {
-358 let (tx, rx) = oneshot::channel();
-359 self.send
-360 .send(Message::Upsert { packet, res: tx })
-361 .await
-362 .anyerr()?;
-363 rx.await.anyerr()
-364 }
-365
-366 pub async fn get(&self, key: &PublicKeyBytes) -> Result<Option<SignedPacket>> {
-367 let (tx, rx) = oneshot::channel();
-368 self.send
-369 .send(Message::Get { key: *key, res: tx })
-370 .await
-371 .anyerr()?;
-372 rx.await.anyerr()
-373 }
-374
-375 pub async fn remove(&self, key: &PublicKeyBytes) -> Result<bool> {
-376 let (tx, rx) = oneshot::channel();
-377 self.send
-378 .send(Message::Remove { key: *key, res: tx })
-379 .await
-380 .anyerr()?;
-381 rx.await.anyerr()
-382 }
-383}
-384
-385/// Serialize a signed packet for storage: `<8 bytes last_seen><packet bytes>`.
-386fn serialize(packet: &SignedPacket) -> Vec<u8> {
-387 let mut out = Vec::with_capacity(8 + packet.as_bytes().len());
-388 out.extend_from_slice(×tamp_now().to_be_bytes());
-389 out.extend_from_slice(packet.as_bytes());
-390 out
-391}
-392
-393/// Deserialize a signed packet from storage format.
-394///
-395/// Handles backwards compatibility with older storage formats that didn't include
-396/// the `last_seen` prefix.
-397fn deserialize(data: &[u8]) -> Result<SignedPacket> {
-398 // Try parsing as <8 bytes last_seen><packet> (pkarr v3 format)
-399 if data.len() >= 8
-400 && let Ok(packet) = SignedPacket::from_bytes_unchecked(&data[8..])
-401 {
-402 return Ok(packet);
-403 }
-404 // Fall back to raw packet bytes (pre-v0.35 format without last_seen prefix)
-405 SignedPacket::from_bytes_unchecked(data)
-406 .map_err(|err| anyerr!("Failed to decode stored packet: {err:#}"))
-407}
-408
-409fn get_packet(
-410 table: &impl ReadableTable<&'static SignedPacketsKey, &'static [u8]>,
-411 key: &PublicKeyBytes,
-412) -> Result<Option<SignedPacket>> {
-413 let Some(row) = table
-414 .get(key.as_ref())
-415 .std_context("database fetch failed")?
-416 else {
-417 return Ok(None);
-418 };
-419 Ok(Some(deserialize(row.value())?))
-420}
-421
-422async fn evict_task(send: mpsc::Sender<Message>, options: Options, cancel: CancellationToken) {
-423 let cancel2 = cancel.clone();
-424 let _ = cancel2
-425 .run_until_cancelled(async move {
-426 info!("starting evict task");
-427 if let Err(cause) = evict_task_inner(send, options).await {
-428 error!("evict task failed: {:?}", cause);
-429 }
-430 // when we are done for whatever reason we want to shut down the actor
-431 cancel.cancel();
-432 })
-433 .await;
-434}
-435
-436/// Periodically check for expired packets and remove them.
-437async fn evict_task_inner(send: mpsc::Sender<Message>, options: Options) -> Result<()> {
-438 let expiry_us = options.eviction.as_micros() as u64;
-439 loop {
-440 let (tx, rx) = oneshot::channel();
-441 let _ = send.send(Message::Snapshot { res: tx }).await.ok();
-442 // if we can't get the snapshot we exit the loop, main actor dead
-443 let snapshot = rx.await.std_context("failed to get snapshot")?;
-444
-445 let expired = timestamp_now() - expiry_us;
-446 trace!("evicting packets older than {}", fmt_time(expired));
-447 // if getting the range fails we exit the loop and shut down
-448 // if individual reads fail we log the error and limp on
-449 for item in snapshot
-450 .update_time
-451 .range(..expired.to_be_bytes())
-452 .anyerr()?
-453 {
-454 let (time, keys) = match item {
-455 Ok(v) => v,
-456 Err(e) => {
-457 error!("failed to read update_time row {:?}", e);
-458 continue;
-459 }
-460 };
-461 let time = u64::from_be_bytes(time.value());
-462 trace!("evicting expired packets at {}", fmt_time(time));
-463 for item in keys {
-464 let key = match item {
-465 Ok(v) => v,
-466 Err(e) => {
-467 error!(
-468 "failed to read update_time item at {}: {:?}",
-469 fmt_time(time),
-470 e
-471 );
-472 continue;
-473 }
-474 };
-475 let key = PublicKeyBytes::new(key.value());
-476
-477 debug!("evicting expired packet {} {}", fmt_time(time), key);
-478 send.send(Message::CheckExpired { time, key })
-479 .await
-480 .anyerr()?;
-481 }
-482 }
-483 // sleep for the eviction interval so we don't constantly check
-484 tokio::time::sleep(options.eviction_interval).await;
-485 }
-486}
-487
-488/// An io thread that drives a future to completion on the current tokio runtime
-489///
-490/// Inside the future, blocking IO can be done without blocking one of the tokio
-491/// pool threads.
-492#[derive(Debug)]
-493struct IoThread {
-494 handle: Option<std::thread::JoinHandle<()>>,
-495}
-496
-497impl IoThread {
-498 /// Spawn a new io thread.
-499 ///
-500 /// Calling this function requires that the current thread is running in a
-501 /// tokio runtime. It is up to the caller to make sure the future exits,
-502 /// e.g. by using a cancellation token. Otherwise, drop will block.
-503 fn new<F, Fut>(name: &str, f: F) -> Result<Self>
-504 where
-505 F: FnOnce() -> Fut + Send + 'static,
-506 Fut: Future<Output = ()>,
-507 {
-508 let rt = tokio::runtime::Handle::try_current().std_context("get tokio handle")?;
-509 let handle = std::thread::Builder::new()
-510 .name(name.into())
-511 .spawn(move || rt.block_on(f()))
-512 .std_context("failed to spawn thread")?;
-513 Ok(Self {
-514 handle: Some(handle),
-515 })
-516 }
-517}
-518
-519impl Drop for IoThread {
-520 fn drop(&mut self) {
-521 if let Some(handle) = self.handle.take() {
-522 let _ = handle.join();
-523 }
-524 }
+264impl<'txn> Tables<'txn> {
+265 pub fn new(tx: &'txn redb::WriteTransaction) -> result::Result<Self, redb::TableError> {
+266 Ok(Self {
+267 signed_packets: tx.open_table(SIGNED_PACKETS_TABLE)?,
+268 update_time: tx.open_multimap_table(UPDATE_TIME_TABLE)?,
+269 })
+270 }
+271}
+272
+273pub(super) struct Snapshot {
+274 #[allow(dead_code)]
+275 pub signed_packets: redb::ReadOnlyTable<&'static SignedPacketsKey, &'static [u8]>,
+276 pub update_time: redb::ReadOnlyMultimapTable<[u8; 8], SignedPacketsKey>,
+277}
+278
+279impl Snapshot {
+280 pub fn new(db: &Database) -> Result<Self> {
+281 let tx = db.begin_read().anyerr()?;
+282 Ok(Self {
+283 signed_packets: tx.open_table(SIGNED_PACKETS_TABLE).anyerr()?,
+284 update_time: tx.open_multimap_table(UPDATE_TIME_TABLE).anyerr()?,
+285 })
+286 }
+287}
+288
+289impl SignedPacketStore {
+290 pub fn persistent(
+291 path: impl AsRef<Path>,
+292 options: Options,
+293 metrics: Arc<Metrics>,
+294 ) -> Result<Self> {
+295 let path = path.as_ref();
+296 info!("loading packet database from {}", path.to_string_lossy());
+297 if let Some(parent) = path.parent() {
+298 std::fs::create_dir_all(parent).with_std_context(|_| {
+299 format!(
+300 "failed to create database directory at {}",
+301 path.to_string_lossy()
+302 )
+303 })?;
+304 }
+305 let db = Database::builder()
+306 .create(path)
+307 .std_context("failed to open packet database")?;
+308 Self::open(db, options, metrics)
+309 }
+310
+311 pub fn in_memory(options: Options, metrics: Arc<Metrics>) -> Result<Self> {
+312 info!("using in-memory packet database");
+313 let db = Database::builder()
+314 .create_with_backend(InMemoryBackend::new())
+315 .anyerr()?;
+316 Self::open(db, options, metrics)
+317 }
+318
+319 pub fn open(db: Database, options: Options, metrics: Arc<Metrics>) -> Result<Self> {
+320 // create tables
+321 let write_tx = db.begin_write().anyerr()?;
+322 let _ = Tables::new(&write_tx).anyerr()?;
+323 write_tx.commit().anyerr()?;
+324 let (send, recv) = mpsc::channel(1024);
+325 let send2 = send.clone();
+326 let cancel = CancellationToken::new();
+327 let cancel2 = cancel.clone();
+328 let cancel3 = cancel.clone();
+329 let actor = Actor {
+330 db,
+331 recv: PeekableReceiver::new(recv),
+332 cancel: cancel2,
+333 options,
+334 metrics,
+335 };
+336 // start an io thread and donate it to the tokio runtime so we can do blocking IO
+337 // inside the thread despite being in a tokio runtime
+338 let _write_thread = IoThread::new("packet-store-actor", move || actor.run())?;
+339 let _evict_thread = IoThread::new("packet-store-evict", move || {
+340 evict_task(send2, options, cancel3)
+341 })?;
+342 Ok(Self {
+343 send,
+344 cancel,
+345 _write_thread,
+346 _evict_thread,
+347 })
+348 }
+349
+350 pub async fn upsert(&self, packet: SignedPacket) -> Result<bool> {
+351 let (tx, rx) = oneshot::channel();
+352 self.send
+353 .send(Message::Upsert { packet, res: tx })
+354 .await
+355 .anyerr()?;
+356 rx.await.anyerr()
+357 }
+358
+359 pub async fn get(&self, key: &PublicKeyBytes) -> Result<Option<SignedPacket>> {
+360 let (tx, rx) = oneshot::channel();
+361 self.send
+362 .send(Message::Get { key: *key, res: tx })
+363 .await
+364 .anyerr()?;
+365 rx.await.anyerr()
+366 }
+367
+368 pub async fn remove(&self, key: &PublicKeyBytes) -> Result<bool> {
+369 let (tx, rx) = oneshot::channel();
+370 self.send
+371 .send(Message::Remove { key: *key, res: tx })
+372 .await
+373 .anyerr()?;
+374 rx.await.anyerr()
+375 }
+376}
+377
+378/// Serialize a signed packet for storage: `<8 bytes last_seen><packet bytes>`.
+379fn serialize(packet: &SignedPacket) -> Vec<u8> {
+380 let mut out = Vec::with_capacity(8 + packet.as_bytes().len());
+381 out.extend_from_slice(&Timestamp::now().to_be_bytes());
+382 out.extend_from_slice(packet.as_bytes());
+383 out
+384}
+385
+386/// Deserialize a signed packet from storage format.
+387///
+388/// Handles backwards compatibility with older storage formats that didn't include
+389/// the `last_seen` prefix.
+390fn deserialize(data: &[u8]) -> Result<SignedPacket> {
+391 // Try parsing as <8 bytes last_seen><packet> (pkarr v3 format)
+392 if data.len() >= 8
+393 && let Ok(packet) = SignedPacket::from_bytes_unchecked(&data[8..])
+394 {
+395 return Ok(packet);
+396 }
+397 // Fall back to raw packet bytes (pre-v0.35 format without last_seen prefix)
+398 SignedPacket::from_bytes_unchecked(data)
+399 .map_err(|err| anyerr!("Failed to decode stored packet: {err:#}"))
+400}
+401
+402fn get_packet(
+403 table: &impl ReadableTable<&'static SignedPacketsKey, &'static [u8]>,
+404 key: &PublicKeyBytes,
+405) -> Result<Option<SignedPacket>> {
+406 let Some(row) = table
+407 .get(key.as_ref())
+408 .std_context("database fetch failed")?
+409 else {
+410 return Ok(None);
+411 };
+412 Ok(Some(deserialize(row.value())?))
+413}
+414
+415async fn evict_task(send: mpsc::Sender<Message>, options: Options, cancel: CancellationToken) {
+416 let cancel2 = cancel.clone();
+417 let _ = cancel2
+418 .run_until_cancelled(async move {
+419 info!("starting evict task");
+420 if let Err(cause) = evict_task_inner(send, options).await {
+421 error!("evict task failed: {:?}", cause);
+422 }
+423 // when we are done for whatever reason we want to shut down the actor
+424 cancel.cancel();
+425 })
+426 .await;
+427}
+428
+429/// Periodically check for expired packets and remove them.
+430async fn evict_task_inner(send: mpsc::Sender<Message>, options: Options) -> Result<()> {
+431 let expiry_us = options.eviction.as_micros() as u64;
+432 loop {
+433 let (tx, rx) = oneshot::channel();
+434 let _ = send.send(Message::Snapshot { res: tx }).await.ok();
+435 // if we can't get the snapshot we exit the loop, main actor dead
+436 let snapshot = rx.await.std_context("failed to get snapshot")?;
+437
+438 let expired = Timestamp::from_micros(Timestamp::now().as_micros() - expiry_us);
+439 trace!("evicting packets older than {}", fmt_time(expired));
+440 // if getting the range fails we exit the loop and shut down
+441 // if individual reads fail we log the error and limp on
+442 for item in snapshot
+443 .update_time
+444 .range(..expired.to_be_bytes())
+445 .anyerr()?
+446 {
+447 let (time, keys) = match item {
+448 Ok(v) => v,
+449 Err(e) => {
+450 error!("failed to read update_time row {:?}", e);
+451 continue;
+452 }
+453 };
+454 let time = Timestamp::from_be_bytes(time.value());
+455 trace!("evicting expired packets at {}", fmt_time(time));
+456 for item in keys {
+457 let key = match item {
+458 Ok(v) => v,
+459 Err(e) => {
+460 error!(
+461 "failed to read update_time item at {}: {:?}",
+462 fmt_time(time),
+463 e
+464 );
+465 continue;
+466 }
+467 };
+468 let key = PublicKeyBytes::new(key.value());
+469
+470 debug!("evicting expired packet {} {}", fmt_time(time), key);
+471 send.send(Message::CheckExpired { time, key })
+472 .await
+473 .anyerr()?;
+474 }
+475 }
+476 // sleep for the eviction interval so we don't constantly check
+477 tokio::time::sleep(options.eviction_interval).await;
+478 }
+479}
+480
+481/// An io thread that drives a future to completion on the current tokio runtime
+482///
+483/// Inside the future, blocking IO can be done without blocking one of the tokio
+484/// pool threads.
+485#[derive(Debug)]
+486struct IoThread {
+487 handle: Option<std::thread::JoinHandle<()>>,
+488}
+489
+490impl IoThread {
+491 /// Spawn a new io thread.
+492 ///
+493 /// Calling this function requires that the current thread is running in a
+494 /// tokio runtime. It is up to the caller to make sure the future exits,
+495 /// e.g. by using a cancellation token. Otherwise, drop will block.
+496 fn new<F, Fut>(name: &str, f: F) -> Result<Self>
+497 where
+498 F: FnOnce() -> Fut + Send + 'static,
+499 Fut: Future<Output = ()>,
+500 {
+501 let rt = tokio::runtime::Handle::try_current().std_context("get tokio handle")?;
+502 let handle = std::thread::Builder::new()
+503 .name(name.into())
+504 .spawn(move || rt.block_on(f()))
+505 .std_context("failed to spawn thread")?;
+506 Ok(Self {
+507 handle: Some(handle),
+508 })
+509 }
+510}
+511
+512impl Drop for IoThread {
+513 fn drop(&mut self) {
+514 if let Some(handle) = self.handle.take() {
+515 let _ = handle.join();
+516 }
+517 }
+518}
+519
+520/// A wrapper for a tokio mpsc receiver that allows peeking at the next message.
+521#[derive(Debug)]
+522pub(super) struct PeekableReceiver<T> {
+523 msg: Option<T>,
+524 recv: tokio::sync::mpsc::Receiver<T>,
525}
526
-527/// A wrapper for a tokio mpsc receiver that allows peeking at the next message.
-528#[derive(Debug)]
-529pub(super) struct PeekableReceiver<T> {
-530 msg: Option<T>,
-531 recv: tokio::sync::mpsc::Receiver<T>,
-532}
-533
-534#[allow(dead_code)]
-535impl<T> PeekableReceiver<T> {
-536 pub fn new(recv: tokio::sync::mpsc::Receiver<T>) -> Self {
-537 Self { msg: None, recv }
-538 }
-539
-540 /// Receive the next message.
-541 ///
-542 /// Will block if there are no messages.
-543 /// Returns None only if there are no more messages (sender is dropped).
-544 pub async fn recv(&mut self) -> Option<T> {
-545 if let Some(msg) = self.msg.take() {
-546 return Some(msg);
-547 }
-548 self.recv.recv().await
-549 }
-550
-551 /// Push back a message. This will only work if there is room for it.
-552 /// Otherwise, it will fail and return the message.
-553 pub fn push_back(&mut self, msg: T) -> std::result::Result<(), T> {
-554 if self.msg.is_none() {
-555 self.msg = Some(msg);
-556 Ok(())
-557 } else {
-558 Err(msg)
-559 }
-560 }
-561}
Variants (Non-exhaustive)§
This enum is marked as non-exhaustive
Trait Implementations§
Source§impl Debug for DecodingError
impl Debug for DecodingError
Source§impl Display for DecodingError
impl Display for DecodingError
Source§impl Error for DecodingError
impl Error for DecodingError
Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
Source§impl From<DecodingError> for AnyError
impl From<DecodingError> for AnyError
Source§fn from(value: DecodingError) -> AnyError
fn from(value: DecodingError) -> AnyError
Source§impl From<DecodingError> for ParseError
impl From<DecodingError> for ParseError
Source§fn from(source: DecodingError) -> Self
fn from(source: DecodingError) -> Self
Source§impl StackError for DecodingError
impl StackError for DecodingError
Source§fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)
fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)
Source§fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>
fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>
Source§fn fmt_message(&self, f: &mut Formatter<'_>) -> Result
fn fmt_message(&self, f: &mut Formatter<'_>) -> Result
Source§fn is_transparent(&self) -> bool
fn is_transparent(&self) -> bool
Auto Trait Implementations§
impl Freeze for DecodingError
impl RefUnwindSafe for DecodingError
impl Send for DecodingError
impl Sync for DecodingError
impl Unpin for DecodingError
impl UnwindSafe for DecodingError
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
diff --git a/pr/4026/docs/iroh_dns/index.html b/pr/4026/docs/iroh_dns/index.html
index f8d2fcb8a6..e276c05581 100644
--- a/pr/4026/docs/iroh_dns/index.html
+++ b/pr/4026/docs/iroh_dns/index.html
@@ -1,5 +1,5 @@
iroh_dns - Rust Crate iroh_dns
Expand description
DNS-based endpoint discovery for iroh.
This crate contains the core types for publishing and resolving iroh endpoint
information via DNS, using the pkarr signed packet format.
-Modules§
- attrs
- Support for handling DNS resource records for dialing by
EndpointId. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for
EndpointId to encode to and decode from z-base-32,
+
Modules§
- attrs
- Support for handling DNS resource records for dialing by [
EndpointId]. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for [
EndpointId] to encode to and decode from z-base-32,
which is the encoding used by pkarr domain names.
\ No newline at end of file
diff --git a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
index 23b64647b5..fcb8d03fff 100644
--- a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
+++ b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
@@ -3,7 +3,7 @@
The DNS packet must be at most 1000 bytes. Total max size is 1104 bytes.
impl<T> BorrowMut<T> for Twhere
diff --git a/pr/4026/docs/iroh_dns/index.html b/pr/4026/docs/iroh_dns/index.html
index f8d2fcb8a6..e276c05581 100644
--- a/pr/4026/docs/iroh_dns/index.html
+++ b/pr/4026/docs/iroh_dns/index.html
@@ -1,5 +1,5 @@
iroh_dns - Rust Crate iroh_dns
Expand description
DNS-based endpoint discovery for iroh.
This crate contains the core types for publishing and resolving iroh endpoint
information via DNS, using the pkarr signed packet format.
-Modules§
- attrs
- Support for handling DNS resource records for dialing by
EndpointId. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for
EndpointId to encode to and decode from z-base-32,
+
Modules§
- attrs
- Support for handling DNS resource records for dialing by [
EndpointId]. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for [
EndpointId] to encode to and decode from z-base-32,
which is the encoding used by pkarr domain names.
\ No newline at end of file
diff --git a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
index 23b64647b5..fcb8d03fff 100644
--- a/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
+++ b/pr/4026/docs/iroh_dns/pkarr/struct.SignedPacket.html
@@ -3,7 +3,7 @@
Crate iroh_dns
Expand description
DNS-based endpoint discovery for iroh.
This crate contains the core types for publishing and resolving iroh endpoint information via DNS, using the pkarr signed packet format.
-Modules§
- attrs
- Support for handling DNS resource records for dialing by
EndpointId. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for
EndpointIdto encode to and decode from z-base-32, +
Modules§
- attrs
- Support for handling DNS resource records for dialing by [
EndpointId]. - pkarr
- Pkarr signed packet encoding.
Enums§
Traits§
- Endpoint
IdExt - Extension methods for [
EndpointId] to encode to and decode from z-base-32, which is the encoding used by pkarr domain names.
The DNS packet must be at most 1000 bytes. Total max size is 1104 bytes.
Implementations§
Source§impl SignedPacket
impl SignedPacket
Sourcepub fn from_txt_strings(
- secret_key: &SecretKey,
+ secret_key: &SecretKey,
name: &str,
values: impl IntoIterator<Item = impl AsRef<str>>,
ttl: u32,
@@ -11,7 +11,7 @@
This is the common case: multiple TXT values under the same DNS name (e.g. "_iroh").
pub fn from_txt_strings( - secret_key: &SecretKey, + secret_key: &SecretKey, name: &str, values: impl IntoIterator<Item = impl AsRef<str>>, ttl: u32, @@ -11,7 +11,7 @@
This is the common case: multiple TXT values under the same DNS name (e.g. "_iroh").
Sourcepub fn from_bytes(bytes: &[u8]) -> Result<SignedPacket, SignedPacketVerifyError>
pub fn from_bytes(bytes: &[u8]) -> Result<SignedPacket, SignedPacketVerifyError>
Parse and verify a signed packet from its wire representation.
Sourcepub fn from_relay_payload(
- public_key: &PublicKey,
+ public_key: &PublicKey,
payload: &[u8],
) -> Result<SignedPacket, SignedPacketVerifyError>
pub fn from_relay_payload( - public_key: &PublicKey, + public_key: &PublicKey, payload: &[u8], ) -> Result<SignedPacket, SignedPacketVerifyError>
Create from a public key and relay payload (signature + timestamp + dns).
Sourcepub fn from_bytes_unchecked(
@@ -20,8 +20,8 @@
Still validates minimum length and DNS parsing.
pub fn from_bytes_unchecked( @@ -20,8 +20,8 @@
Still validates minimum length and DNS parsing.
Sourcepub fn to_relay_payload(&self) -> Vec<u8> ⓘ
pub fn to_relay_payload(&self) -> Vec<u8> ⓘ
Return the relay payload (everything after the public key).
-Sourcepub fn public_key(&self) -> PublicKey
pub fn public_key(&self) -> PublicKey
Return the public key.
-Sourcepub fn public_key(&self) -> PublicKey
pub fn public_key(&self) -> PublicKey
Return the public key.
+Sourcepub fn encoded_packet(&self) -> &[u8] ⓘ
pub fn encoded_packet(&self) -> &[u8] ⓘ
Return the encoded DNS packet bytes.
Sourcepub fn txt_records(&self, name: &str) -> Vec<String>
pub fn txt_records(&self, name: &str) -> Vec<String>
Iterate over TXT records under a specific DNS name.
diff --git a/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html b/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html index 4ee78decb2..bdd3ab70e4 100644 --- a/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html +++ b/pr/4026/docs/iroh_dns/trait.EndpointIdExt.html @@ -1,9 +1,9 @@EndpointIdExt
pub trait EndpointIdExt {
// Required methods
fn to_z32(&self) -> String;
- fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
-}Expand description
Extension methods for Extension methods for [EndpointId to encode to and decode from z-base-32,
+ fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
+}Expand description
EndpointId] to encode to and decode from z-base-32,
which is the encoding used by pkarr domain names.
Required Methods§
Sourcefn to_z32(&self) -> String
fn to_z32(&self) -> String
Encodes a EndpointId in z-base-32 encoding.
Sourcefn from_z32(s: &str) -> Result<EndpointId, DecodingError>
fn from_z32(s: &str) -> Result<EndpointId, DecodingError>
Parses a EndpointId from z-base-32 encoding.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Source§impl EndpointIdExt for EndpointId
impl EndpointIdExt for EndpointId
Implementors§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.