mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6d0d698dd | ||
|
|
54c85253e3 | ||
|
|
5061c0f2bc | ||
|
|
d7151fde2f | ||
|
|
83be931e74 | ||
|
|
a839ec05c6 | ||
|
|
7631c75afd | ||
|
|
5dadbd44bd | ||
|
|
dfb229bb4e | ||
|
|
82502fb72c |
No files matched your search
Generated
+11
-59
@@ -182,22 +182,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -272,9 +263,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1445,22 +1436,6 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1470,17 +1445,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1488,8 +1452,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1498,18 +1462,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1517,8 +1469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1930,9 +1882,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
|
||||
Generated
+11
-59
@@ -79,22 +79,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -169,9 +160,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.20",
|
||||
@@ -994,22 +985,6 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1019,17 +994,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1037,8 +1001,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1047,18 +1011,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1066,8 +1018,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1305,9 +1257,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
|
||||
@@ -803,7 +803,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.5",
|
||||
"requirement": "^0.6",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -814,12 +814,14 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"CBAdvertisementData",
|
||||
"CBCentralManagerConstants"
|
||||
"CBCentralManagerConstants",
|
||||
"CBPeripheralManagerConstants",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
@@ -828,11 +830,12 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"NSString"
|
||||
"NSString",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
|
||||
@@ -345,7 +345,9 @@ pub fn rns_protocol::resource::LinkResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::LinkResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub struct rns_protocol::resource::MultiSegmentInbound
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_segments: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_through: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::original_hash: [u8; 32]
|
||||
@@ -362,6 +364,7 @@ pub fn rns_protocol::resource::MultiSegmentInbound::reassemble(&self) -> core::r
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_metadata(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment(&mut self, usize, rns_protocol::resource::InboundResource)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment_data(&mut self, usize, alloc::vec::Vec<u8>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::take_reassembled(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::with_size_bound(self, usize) -> Self
|
||||
pub struct rns_protocol::resource::MultiSegmentOutbound
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::data_size: usize
|
||||
|
||||
@@ -17,6 +17,7 @@ pub async fn rns_transport::actor::PersistenceTrigger::request(&self) -> bool
|
||||
pub struct rns_transport::actor::RecentAnnounce
|
||||
pub rns_transport::actor::RecentAnnounce::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_transport::actor::RecentAnnounce::dest_hash: [u8; 16]
|
||||
pub rns_transport::actor::RecentAnnounce::emitted: core::option::Option<u64>
|
||||
pub rns_transport::actor::RecentAnnounce::facts_known: bool
|
||||
pub rns_transport::actor::RecentAnnounce::hops: u8
|
||||
pub rns_transport::actor::RecentAnnounce::is_path_response: bool
|
||||
@@ -83,6 +84,7 @@ pub rns_transport::background_egress::BackgroundRegistrationError::Duplicate
|
||||
pub struct rns_transport::background_egress::BackgroundAnnounceReceiver
|
||||
impl rns_transport::background_egress::BackgroundAnnounceReceiver
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::has_offer(&self) -> bool
|
||||
pub async fn rns_transport::background_egress::BackgroundAnnounceReceiver::offered(&self)
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::ordinary_is_empty(&self) -> bool
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::register(&tokio::sync::mpsc::bounded::Sender<bytes::bytes::Bytes>) -> core::result::Result<Self, rns_transport::background_egress::BackgroundRegistrationError>
|
||||
pub fn rns_transport::background_egress::BackgroundAnnounceReceiver::retire_generation(&self)
|
||||
@@ -1362,6 +1364,7 @@ pub struct rns_transport::messages::AnnounceHandlerId(_)
|
||||
#[non_exhaustive] pub struct rns_transport::messages::AnnounceRpcEntry
|
||||
pub rns_transport::messages::AnnounceRpcEntry::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_transport::messages::AnnounceRpcEntry::dest_hash: [u8; 16]
|
||||
pub rns_transport::messages::AnnounceRpcEntry::emitted: core::option::Option<u64>
|
||||
pub rns_transport::messages::AnnounceRpcEntry::facts_known: bool
|
||||
pub rns_transport::messages::AnnounceRpcEntry::hops: u8
|
||||
pub rns_transport::messages::AnnounceRpcEntry::is_path_response: bool
|
||||
|
||||
+4
-4
@@ -51,8 +51,8 @@
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-transport.txt",
|
||||
"itemCount": 2270,
|
||||
"sha256": "bb1fb9639200f46f4af711d011e107fce2a3b13d544baeaf0f41aa9a1ef1b652"
|
||||
"itemCount": 2273,
|
||||
"sha256": "7894fdab76428a6fd8cd7097e60058409a6a593d8c4970c01c5d440e98613fa1"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
@@ -69,8 +69,8 @@
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-protocol.txt",
|
||||
"itemCount": 670,
|
||||
"sha256": "c597cd463ba4cc68357fee72f7a3926086473383cf52014a38235a8f462e7ddf"
|
||||
"itemCount": 673,
|
||||
"sha256": "cac91c8ac80f6706f0d2a4257da740f8188846ffc7da61a8ff2a8a293ad6dee3"
|
||||
},
|
||||
{
|
||||
"name": "rns-interface",
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
let ciphertext =
|
||||
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
|
||||
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len());
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len() + 32);
|
||||
signed_parts.extend_from_slice(&iv);
|
||||
signed_parts.extend_from_slice(&ciphertext);
|
||||
|
||||
|
||||
@@ -265,16 +265,9 @@ fn barrier_unsupported(error: &io::Error) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// On Apple targets `sync_all` is already `F_FULLFSYNC`.
|
||||
fn file_barrier(file: &File) -> io::Result<()> {
|
||||
supported_barrier(file.sync_all())?;
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
{
|
||||
use std::os::fd::AsRawFd;
|
||||
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_FULLFSYNC) } == -1 {
|
||||
supported_barrier(Err(io::Error::last_os_error()))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
supported_barrier(file.sync_all())
|
||||
}
|
||||
|
||||
fn parent_barrier(_path: &Path) -> io::Result<()> {
|
||||
|
||||
@@ -45,9 +45,9 @@ md-5 = { workspace = true }
|
||||
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
|
||||
# values, which Apple is free to change.
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
objc2 = "0.5"
|
||||
objc2-foundation = { version = "0.2", features = ["NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] }
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.3", default-features = false, features = ["std", "CBAdvertisementData", "CBCentralManagerConstants", "CBPeripheralManagerConstants"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Owned Objective-C values for the Apple BLE modules. Their calls run on Tokio
|
||||
//! workers and other threads with no autorelease pool, where an autoreleased
|
||||
//! object lives until the thread exits.
|
||||
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::{Allocated, Retained};
|
||||
use objc2::runtime::{AnyClass, AnyObject};
|
||||
use objc2_foundation::NSString;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// `UUIDWithString:` autoreleases, so call this inside `autoreleasepool`.
|
||||
pub(crate) fn cbuuid(uuid: &Uuid) -> Retained<AnyObject> {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
let cls = AnyClass::get(c"CBUUID").expect("CBUUID must exist at runtime");
|
||||
unsafe { msg_send![cls, UUIDWithString: &*s] }
|
||||
}
|
||||
|
||||
/// A copy of `bytes`, never autoreleased.
|
||||
pub(crate) fn nsdata(bytes: &[u8]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSData").expect("NSData must exist at runtime");
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj,
|
||||
initWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Never autoreleased; the array retains each element.
|
||||
pub(crate) fn nsarray(objects: &[&AnyObject]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSArray").expect("NSArray must exist at runtime");
|
||||
let ptrs: Vec<*const AnyObject> = objects.iter().map(|o| *o as *const AnyObject).collect();
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj, initWithObjects: ptrs.as_ptr(), count: ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use objc2::rc::{Weak, autoreleasepool};
|
||||
|
||||
/// Runs `make` on a thread with no autorelease pool, drops what it returns,
|
||||
/// and reports whether every returned object was freed. A stray retain or
|
||||
/// an autorelease outside `make`'s own pool keeps the object alive.
|
||||
pub(crate) fn freed_on_drop<F>(make: F) -> bool
|
||||
where
|
||||
F: FnOnce() -> Vec<Retained<AnyObject>> + Send + 'static,
|
||||
{
|
||||
std::thread::spawn(move || {
|
||||
let weak: Vec<Weak<AnyObject>> = {
|
||||
let objs = make();
|
||||
let weak: Vec<_> = objs.iter().map(Weak::from_retained).collect();
|
||||
// A class without weak-reference support would pass vacuously.
|
||||
assert!(weak.iter().all(|w| w.load().is_some()));
|
||||
weak
|
||||
};
|
||||
weak.iter().all(|w| w.load().is_none())
|
||||
})
|
||||
.join()
|
||||
.expect("probe thread")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_sees_an_autoreleased_object() {
|
||||
assert!(!freed_on_drop(|| {
|
||||
let cls = AnyClass::get(c"NSData").unwrap();
|
||||
let bytes = [0xCDu8; 300];
|
||||
unsafe {
|
||||
let raw: *mut AnyObject = msg_send![cls,
|
||||
dataWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()];
|
||||
vec![Retained::retain(raw).unwrap()]
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsdata_and_nsarray_are_never_autoreleased() {
|
||||
assert!(freed_on_drop(|| {
|
||||
let data = nsdata(&[0xAB; 300]);
|
||||
let arr = nsarray(&[&data]);
|
||||
vec![data, arr]
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbuuid_holds_no_extra_retain() {
|
||||
assert!(freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![cbuuid(&crate::ble_peer::RATSPEAK_SERVICE_UUID)])
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use crate::ble_central_lifecycle::{
|
||||
CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol,
|
||||
};
|
||||
use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID};
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
@@ -144,7 +145,7 @@ pub async fn start_scan(
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
|
||||
|
||||
let Some(mgr_cls) = AnyClass::get("CBCentralManager") else {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBCentralManager") else {
|
||||
tracing::error!("Apple BLE Central: CBCentralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -216,12 +217,12 @@ pub async fn stop_scan() -> Result<(), String> {
|
||||
}
|
||||
};
|
||||
|
||||
unsafe {
|
||||
// We do NOT release the manager — the next start_scan reuses it.
|
||||
// Per-cycle release on macOS triggers CBManagerStateUnsupported.
|
||||
// `teardown_central` does the full release on interface shutdown.
|
||||
// We do NOT release the manager — the next start_scan reuses it.
|
||||
// Per-cycle release on macOS triggers CBManagerStateUnsupported.
|
||||
// `teardown_central` does the full release on interface shutdown.
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*mgr_ptr, stopScan];
|
||||
}
|
||||
});
|
||||
|
||||
finalize_stop();
|
||||
Ok(())
|
||||
@@ -286,8 +287,8 @@ pub fn central_manager_ptr() -> Option<*mut AnyObject> {
|
||||
|
||||
fn get_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new("RatspeakBleCentralDelegate", superclass)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleCentralDelegate", superclass)
|
||||
.expect("ClassBuilder for central delegate must succeed");
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
@@ -720,23 +721,14 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
.map_err(|e| format!("scan_services lock poisoned: {e}"))?
|
||||
.clone();
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let uuids: Vec<_> = services.iter().map(crate::apple_objc::cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = uuids.iter().map(|u| &**u).collect();
|
||||
// nil filter = scan all.
|
||||
let svc_arr: *mut AnyObject = if services.is_empty() {
|
||||
std::ptr::null_mut()
|
||||
} else {
|
||||
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
|
||||
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(services.len());
|
||||
for u in &services {
|
||||
raw_ptrs.push(cbuuid(u) as *const AnyObject);
|
||||
}
|
||||
msg_send![arr_cls,
|
||||
arrayWithObjects: raw_ptrs.as_ptr(),
|
||||
count: raw_ptrs.len()]
|
||||
};
|
||||
let svc_arr = (!refs.is_empty()).then(|| crate::apple_objc::nsarray(&refs));
|
||||
|
||||
let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let number_cls = AnyClass::get(c"NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true];
|
||||
let opts: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: yes,
|
||||
@@ -750,16 +742,16 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
"Apple BLE Central: scanForPeripheralsWithServices"
|
||||
);
|
||||
let _: () = msg_send![&*mgr_raw,
|
||||
scanForPeripheralsWithServices: svc_arr,
|
||||
scanForPeripheralsWithServices: svc_arr.as_deref(),
|
||||
options: opts];
|
||||
}
|
||||
Ok(())
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS.
|
||||
unsafe fn build_init_options() -> Result<*mut AnyObject, String> {
|
||||
unsafe {
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let restore_id = NSString::from_str(CENTRAL_RESTORE_ID);
|
||||
let opts: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: &*restore_id,
|
||||
@@ -852,18 +844,6 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
unsafe {
|
||||
let cls = AnyClass::get("CBUUID").expect("CBUUID must exist at runtime");
|
||||
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
|
||||
// UUIDWithString: returns autoreleased; retain so the pointer
|
||||
// survives the autorelease pool drain.
|
||||
let _: *mut AnyObject = msg_send![obj, retain];
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using
|
||||
/// the Bluetooth base UUID.
|
||||
fn parse_short_uuid(s: &str) -> Result<Uuid, ()> {
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
|
||||
#![cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use crate::ble_tx_queue::PacketQueue;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_foundation::NSString;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
@@ -135,7 +136,7 @@ pub struct ConnectedPeer {
|
||||
|
||||
impl Drop for ConnectedPeer {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
// Clear the (weakly-retained) delegate first so a late callback
|
||||
// can't fire into freed memory after the release below.
|
||||
if !self.peripheral.0.is_null() {
|
||||
@@ -157,7 +158,7 @@ impl Drop for ConnectedPeer {
|
||||
let _: () = msg_send![p.0, release];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,12 +213,12 @@ pub async fn connect_peer(
|
||||
reason = %reason,
|
||||
"Apple BLE central connect: tearing down partial connection"
|
||||
);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral];
|
||||
let _: () = msg_send![peripheral, setDelegate: std::ptr::null::<AnyObject>()];
|
||||
let _: () = msg_send![delegate, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
});
|
||||
if let Ok(mut g) = pending().lock() {
|
||||
for kind in [
|
||||
CallbackKind::Connect,
|
||||
@@ -239,11 +240,11 @@ pub async fn connect_peer(
|
||||
"Apple BLE central: connectPeripheral"
|
||||
);
|
||||
let rx = install_pending(&address, CallbackKind::Connect);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager.0,
|
||||
connectPeripheral: peripheral.0,
|
||||
options: std::ptr::null::<AnyObject>()];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
@@ -263,17 +264,19 @@ pub async fn connect_peer(
|
||||
// install_pending must run BEFORE the CB call so a fast-path callback
|
||||
// (cached service data) can't race ahead of its own entry.
|
||||
let rx = install_pending(&address, CallbackKind::Services);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0, setDelegate: delegate.0];
|
||||
let svc_filter = build_cbuuid_array(&[target_service_uuid]);
|
||||
let _: () = msg_send![peripheral.0, discoverServices: svc_filter];
|
||||
}
|
||||
let _: () = msg_send![peripheral.0, discoverServices: &*svc_filter];
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let service = match unsafe { find_service(peripheral.0, target_service_uuid) } {
|
||||
let service = match autoreleasepool(|_| unsafe {
|
||||
find_service(peripheral.0, target_service_uuid)
|
||||
}) {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
let msg = format!("target service {target_service_uuid} not present after discovery");
|
||||
@@ -295,39 +298,41 @@ pub async fn connect_peer(
|
||||
PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID),
|
||||
};
|
||||
let rx = install_pending(&address, CallbackKind::Chars);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]);
|
||||
let _: () = msg_send![peripheral.0,
|
||||
discoverCharacteristics: chars_filter,
|
||||
discoverCharacteristics: &*chars_filter,
|
||||
forService: service.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let rx_char = match unsafe { find_char(service.0, rx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
let found = autoreleasepool(|_| unsafe {
|
||||
let rx_char = find_char(service.0, rx_uuid);
|
||||
let tx_char = find_char(service.0, tx_uuid);
|
||||
if let (Some(rx), Some(tx)) = (rx_char, tx_char) {
|
||||
let _: *mut AnyObject = msg_send![rx, retain];
|
||||
let _: *mut AnyObject = msg_send![tx, retain];
|
||||
}
|
||||
(rx_char, tx_char)
|
||||
});
|
||||
let (rx_char, tx_char) = match found {
|
||||
(Some(rx), Some(tx)) => (SendPtr(rx), SendPtr(tx)),
|
||||
(None, _) => {
|
||||
let msg = format!("rx characteristic {rx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
let tx_char = match unsafe { find_char(service.0, tx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
(_, None) => {
|
||||
let msg = format!("tx characteristic {tx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
unsafe {
|
||||
let _: *mut AnyObject = msg_send![rx_char.0, retain];
|
||||
let _: *mut AnyObject = msg_send![tx_char.0, retain];
|
||||
}
|
||||
tracing::info!(
|
||||
target: "ble_trace",
|
||||
step = "apple_connect.chars_discovered",
|
||||
@@ -339,11 +344,11 @@ pub async fn connect_peer(
|
||||
|
||||
// Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally).
|
||||
let rx = install_pending(&address, CallbackKind::Notify);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0,
|
||||
setNotifyValue: true,
|
||||
forCharacteristic: tx_char.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await {
|
||||
// Balance the rx/tx retains on failure.
|
||||
unsafe {
|
||||
@@ -437,17 +442,19 @@ fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, St
|
||||
}
|
||||
|
||||
fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
return false;
|
||||
}
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
autoreleasepool(|_| {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
return false;
|
||||
}
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be
|
||||
@@ -457,11 +464,11 @@ fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
|
||||
/// pointers.
|
||||
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
|
||||
let value = nsdata(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
unsafe {
|
||||
let nsdata = nsdata_from_slice(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
let _: () = msg_send![peer.peripheral.0,
|
||||
writeValue: nsdata,
|
||||
writeValue: &*value,
|
||||
forCharacteristic: peer.rx_char.0,
|
||||
type: WRITE_WITHOUT_RESPONSE];
|
||||
}
|
||||
@@ -481,10 +488,10 @@ pub fn disconnect_peer(address: &str) {
|
||||
*q = PacketQueue::default();
|
||||
}
|
||||
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager_ptr,
|
||||
cancelPeripheralConnection: peer.peripheral.0];
|
||||
}
|
||||
});
|
||||
}
|
||||
// online_flags entry stays — the disconnect callback flips it.
|
||||
tracing::info!(
|
||||
@@ -575,8 +582,6 @@ pub unsafe fn adopt_restored_peer(
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
unsafe {
|
||||
let _: () = msg_send![rx_char.0, retain];
|
||||
let _: () = msg_send![rx_char.0, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
return Err(format!(
|
||||
@@ -824,8 +829,8 @@ async fn await_step(
|
||||
|
||||
fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new("RatspeakBlePeripheralDelegate", superclass)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBlePeripheralDelegate", superclass)
|
||||
.expect("ClassBuilder for peripheral delegate must succeed");
|
||||
|
||||
extern "C" fn did_discover_services(
|
||||
@@ -1015,41 +1020,11 @@ fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
})
|
||||
}
|
||||
|
||||
/// Autoreleased `NSArray<CBUUID>`; CB retains internally.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> *mut AnyObject {
|
||||
if uuids.is_empty() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let cbuuid_cls = match AnyClass::get("CBUUID") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let nsarr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(uuids.len());
|
||||
for u in uuids {
|
||||
let s = NSString::from_str(&u.to_string());
|
||||
unsafe {
|
||||
let cb: *mut AnyObject = msg_send![cbuuid_cls, UUIDWithString: &*s];
|
||||
raw_ptrs.push(cb as *const AnyObject);
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
msg_send![nsarr_cls,
|
||||
arrayWithObjects: raw_ptrs.as_ptr(),
|
||||
count: raw_ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Autoreleased `NSData` over a copy of `bytes`; valid for the synchronous
|
||||
/// CB call only.
|
||||
unsafe fn nsdata_from_slice(bytes: &[u8]) -> *mut AnyObject {
|
||||
let cls = AnyClass::get("NSData").expect("NSData class must exist");
|
||||
let ptr = bytes.as_ptr() as *const std::ffi::c_void;
|
||||
let len = bytes.len();
|
||||
unsafe { msg_send![cls, dataWithBytes: ptr, length: len] }
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> Retained<AnyObject> {
|
||||
let owned: Vec<_> = uuids.iter().map(cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = owned.iter().map(|u| &**u).collect();
|
||||
nsarray(&refs)
|
||||
}
|
||||
|
||||
unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> {
|
||||
@@ -1204,6 +1179,13 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cbuuid_filter_holds_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![build_cbuuid_array(&[RATSPEAK_RX_UUID, RATSPEAK_TX_UUID])])
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_short_uuid_round_trip_16bit() {
|
||||
let u = expand_short_uuid("180D").expect("must parse");
|
||||
|
||||
@@ -398,39 +398,45 @@ fn has_wanted_reconnects(map: &RecentlyDisconnected) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan saw a peer the connect loop would try: a free slot, and a
|
||||
/// peer linked neither way and not in reconnect backoff. Pass only addresses
|
||||
/// that clear the connect loop's RSSI gate, so the active scan rate is held
|
||||
/// only for peers it can act on.
|
||||
fn has_connect_candidate<'a>(
|
||||
mut scanned: impl Iterator<Item = &'a str>,
|
||||
connected: &HashMap<String, Arc<AtomicBool>>,
|
||||
linked_to_us: &[String],
|
||||
recently_disc: &RecentlyDisconnected,
|
||||
) -> bool {
|
||||
connected.len() < MAX_PEERS
|
||||
&& scanned.any(|address| {
|
||||
!connected.contains_key(address)
|
||||
&& !linked_to_us.iter().any(|peer| peer == address)
|
||||
&& !reconnect_in_backoff(recently_disc, address)
|
||||
})
|
||||
}
|
||||
|
||||
/// Interval used for background scans with `mobile-throttle`.
|
||||
pub const SCAN_BACKGROUND_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
const SCAN_SLEEP_SLICE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Exits early on foreground-resume or `wake` notify.
|
||||
/// Exits early on a `wake` notify, which the owner sends after each change
|
||||
/// of `foreground`. The wait registers before the foreground check, so a
|
||||
/// resume between the scan and this sleep is not lost.
|
||||
async fn scan_sleep(
|
||||
total: Duration,
|
||||
foreground: &Arc<AtomicBool>,
|
||||
was_foreground: bool,
|
||||
wake: &Arc<tokio::sync::Notify>,
|
||||
) {
|
||||
if was_foreground {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(total) => {}
|
||||
_ = wake.notified() => {}
|
||||
}
|
||||
let notified = wake.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if !was_foreground && foreground.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let deadline = std::time::Instant::now() + total;
|
||||
loop {
|
||||
let now = std::time::Instant::now();
|
||||
if now >= deadline {
|
||||
return;
|
||||
}
|
||||
let remaining = (deadline - now).min(SCAN_SLEEP_SLICE);
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(remaining) => {}
|
||||
_ = wake.notified() => return,
|
||||
}
|
||||
if foreground.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(total) => {}
|
||||
_ = notified => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1510,8 +1516,15 @@ pub(crate) fn try_push_apple_inbound(peer: String, data: Vec<u8>) -> bool {
|
||||
#[cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
mod apple_peripheral {
|
||||
use super::*;
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use objc2::rc::{Allocated, Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
CBPeripheralManagerOptionRestoreIdentifierKey,
|
||||
CBPeripheralManagerRestoredStateAdvertisementDataKey,
|
||||
CBPeripheralManagerRestoredStateServicesKey,
|
||||
};
|
||||
use objc2_foundation::NSString;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -1631,15 +1644,6 @@ mod apple_peripheral {
|
||||
/// previously-backgrounded GATT subscriptions.
|
||||
const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral";
|
||||
|
||||
// objc2-core-bluetooth 0.2.2 only exports the central-role keys; link
|
||||
// the peripheral-role NSString constants directly.
|
||||
#[link(name = "CoreBluetooth", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static CBPeripheralManagerOptionRestoreIdentifierKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateServicesKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateAdvertisementDataKey: &'static NSString;
|
||||
}
|
||||
|
||||
/// Ratspeak primary + Columba compat.
|
||||
const EXPECTED_SERVICE_COUNT: usize = 2;
|
||||
|
||||
@@ -1856,8 +1860,8 @@ mod apple_peripheral {
|
||||
|
||||
fn get_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new("RatspeakBleDelegate", superclass).unwrap();
|
||||
let superclass = AnyClass::get(c"NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleDelegate", superclass).unwrap();
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
_this: *mut AnyObject,
|
||||
@@ -2488,40 +2492,27 @@ mod apple_peripheral {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
unsafe {
|
||||
let arr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let data_cls = match AnyClass::get("NSData") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let payload: *mut AnyObject = msg_send![data_cls,
|
||||
dataWithBytes: data.as_ptr() as *const std::ffi::c_void,
|
||||
length: data.len()];
|
||||
let centrals: *mut AnyObject = if let Some(peer_id) = to_peer {
|
||||
let map = subscribed_centrals_map().lock().unwrap();
|
||||
let ptr = match map.get(peer_id) {
|
||||
Some(p) => p.0,
|
||||
None => {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let payload = nsdata(data);
|
||||
let centrals = match to_peer {
|
||||
Some(peer_id) => {
|
||||
let map = subscribed_centrals_map().lock().unwrap();
|
||||
let Some(central) = map.get(peer_id) else {
|
||||
tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let one = [ptr as *const AnyObject];
|
||||
msg_send![arr_cls, arrayWithObjects: one.as_ptr(), count: 1usize]
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
};
|
||||
Some(nsarray(&[&*central.0]))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let ok: bool = msg_send![
|
||||
mgr,
|
||||
updateValue: payload,
|
||||
updateValue: &*payload,
|
||||
forCharacteristic: char_ptr,
|
||||
onSubscribedCentrals: centrals,
|
||||
onSubscribedCentrals: centrals.as_deref(),
|
||||
];
|
||||
ok
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// We only need the TX chars from notify_tx, but the registry is keyed
|
||||
@@ -2556,17 +2547,6 @@ mod apple_peripheral {
|
||||
.map(|(uuid, _)| *uuid)
|
||||
}
|
||||
|
||||
/// Returns a raw retained pointer.
|
||||
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
unsafe {
|
||||
let cls = AnyClass::get("CBUUID").unwrap();
|
||||
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
|
||||
let _: *mut AnyObject = msg_send![obj, retain];
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> {
|
||||
// Drive the lifecycle BEFORE any side effects.
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested);
|
||||
@@ -2608,7 +2588,7 @@ mod apple_peripheral {
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
|
||||
|
||||
let Some(mgr_cls) = AnyClass::get("CBPeripheralManager") else {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBPeripheralManager") else {
|
||||
tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -2617,7 +2597,7 @@ mod apple_peripheral {
|
||||
// background BLE event after the process is killed.
|
||||
let opts: *mut AnyObject = {
|
||||
let dict_cls =
|
||||
AnyClass::get("NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
AnyClass::get(c"NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
let id = NSString::from_str(PERIPHERAL_RESTORE_ID);
|
||||
msg_send![dict_cls,
|
||||
dictionaryWithObject: &*id,
|
||||
@@ -2682,68 +2662,21 @@ mod apple_peripheral {
|
||||
mgr_raw: *mut AnyObject,
|
||||
id_hash: &[u8],
|
||||
) -> Result<(), String> {
|
||||
unsafe {
|
||||
let char_cls = AnyClass::get("CBMutableCharacteristic")
|
||||
.ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get("CBMutableService").ok_or("CBMutableService not found")?;
|
||||
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
|
||||
// RX (write + writeNoResponse)
|
||||
let rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let rx_raw: *mut AnyObject = msg_send![rx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
// TX (read + notify)
|
||||
let tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let tx_raw: *mut AnyObject = msg_send![tx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
// Keep the registry pointer valid for notify_tx.
|
||||
let _: *mut AnyObject = msg_send![tx_raw, retain];
|
||||
register_characteristic(RATSPEAK_TX_UUID, tx_raw);
|
||||
// No static ID characteristic: it exposed a MAC-rotation-stable
|
||||
// identity read to any connecting scanner (a tracking vector) and
|
||||
// was never read by this stack — identity is learned from signed
|
||||
// announces instead.
|
||||
|
||||
// Ratspeak service (primary)
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_SERVICE_UUID), primary: true];
|
||||
let char_ptrs = [rx_raw as *const AnyObject, tx_raw as *const AnyObject];
|
||||
let chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![svc_raw, setCharacteristics: chars];
|
||||
let _: () = msg_send![mgr_raw, addService: svc_raw];
|
||||
|
||||
// Columba compat (secondary, omitted from advertising payload).
|
||||
let c_rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_rx_raw: *mut AnyObject = msg_send![c_rx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![c_tx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
let _: *mut AnyObject = msg_send![c_tx_raw, retain];
|
||||
register_characteristic(COLUMBA_TX_UUID, c_tx_raw);
|
||||
let c_svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let c_svc_raw: *mut AnyObject = msg_send![c_svc_raw,
|
||||
initWithType: cbuuid(&COLUMBA_SERVICE_UUID), primary: false];
|
||||
let c_char_ptrs = [c_rx_raw as *const AnyObject, c_tx_raw as *const AnyObject];
|
||||
let c_chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: c_char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![c_svc_raw, setCharacteristics: c_chars];
|
||||
let _: () = msg_send![mgr_raw, addService: c_svc_raw];
|
||||
autoreleasepool(|_| unsafe {
|
||||
let gatt = build_gatt_services()?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
// The registry owns these +1s until it is drained.
|
||||
register_characteristic(RATSPEAK_TX_UUID, Retained::into_raw(gatt.ratspeak_tx));
|
||||
register_characteristic(COLUMBA_TX_UUID, Retained::into_raw(gatt.columba_tx));
|
||||
// The manager retains each service.
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.ratspeak];
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.columba];
|
||||
|
||||
// One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not.
|
||||
let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs");
|
||||
let uuid_ptrs = [cbuuid(&RATSPEAK_SERVICE_UUID) as *const AnyObject];
|
||||
let uuid_arr: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: uuid_ptrs.as_ptr(), count: 1usize];
|
||||
let uuid_arr = nsarray(&[&*cbuuid(&RATSPEAK_SERVICE_UUID)]);
|
||||
let ad_dict: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: uuid_arr, forKey: &*ad_key];
|
||||
dictionaryWithObject: &*uuid_arr, forKey: &*ad_key];
|
||||
let _: () = msg_send![mgr_raw, startAdvertising: ad_dict];
|
||||
|
||||
tracing::info!(
|
||||
@@ -2755,7 +2688,53 @@ mod apple_peripheral {
|
||||
"Apple BLE Peripheral: advertising started"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct GattServices {
|
||||
ratspeak: Retained<AnyObject>,
|
||||
columba: Retained<AnyObject>,
|
||||
ratspeak_tx: Retained<AnyObject>,
|
||||
columba_tx: Retained<AnyObject>,
|
||||
}
|
||||
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease. No static ID
|
||||
/// characteristic: it exposed a MAC-rotation-stable identity read to any
|
||||
/// connecting scanner (a tracking vector) and was never read by this
|
||||
/// stack — identity is learned from signed announces instead.
|
||||
unsafe fn build_gatt_services() -> Result<GattServices, String> {
|
||||
let char_cls =
|
||||
AnyClass::get(c"CBMutableCharacteristic").ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get(c"CBMutableService").ok_or("CBMutableService not found")?;
|
||||
// RX: write + writeNoResponse, writeable. TX: read + notify, readable.
|
||||
let characteristic = |uuid: &Uuid, properties: u64, permissions: u64| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![char_cls, alloc];
|
||||
let obj: Retained<AnyObject> = msg_send![obj,
|
||||
initWithType: &*cbuuid(uuid), properties: properties,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: permissions];
|
||||
obj
|
||||
};
|
||||
let service = |uuid: &Uuid, primary: bool, rx: &AnyObject, tx: &AnyObject| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![svc_cls, alloc];
|
||||
let obj: Retained<AnyObject> =
|
||||
msg_send![obj, initWithType: &*cbuuid(uuid), primary: primary];
|
||||
let chars = nsarray(&[rx, tx]);
|
||||
let _: () = msg_send![&*obj, setCharacteristics: &*chars];
|
||||
obj
|
||||
};
|
||||
let rx = characteristic(&RATSPEAK_RX_UUID, 0x0C, 0x02);
|
||||
let ratspeak_tx = characteristic(&RATSPEAK_TX_UUID, 0x12, 0x01);
|
||||
let ratspeak = service(&RATSPEAK_SERVICE_UUID, true, &rx, &ratspeak_tx);
|
||||
// Columba compat: secondary, omitted from the advertising payload.
|
||||
let c_rx = characteristic(&COLUMBA_RX_UUID, 0x0C, 0x02);
|
||||
let columba_tx = characteristic(&COLUMBA_TX_UUID, 0x12, 0x01);
|
||||
let columba = service(&COLUMBA_SERVICE_UUID, false, &c_rx, &columba_tx);
|
||||
Ok(GattServices {
|
||||
ratspeak,
|
||||
columba,
|
||||
ratspeak_tx,
|
||||
columba_tx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Walks the lifecycle state machine in lockstep with the platform
|
||||
@@ -2829,9 +2808,9 @@ mod apple_peripheral {
|
||||
let mgr_send = SendPtr(mgr_ptr);
|
||||
|
||||
if needs_stop_ad {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, stopAdvertising];
|
||||
}
|
||||
});
|
||||
// CB has no peripheralManagerDidStopAdvertising delegate — poll
|
||||
// `isAdvertising`. Radio flips within ~20ms; 1s budget covers
|
||||
// contended radios and bounce loops.
|
||||
@@ -2855,13 +2834,13 @@ mod apple_peripheral {
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped);
|
||||
}
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, removeAllServices];
|
||||
}
|
||||
});
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved);
|
||||
|
||||
// Without this, every toggle cycle leaks two CBMutableCharacteristic
|
||||
// pointers and notify_tx can race onto dead characteristics post-teardown.
|
||||
// Releases the registry's TX characteristics, so notify_tx can't race
|
||||
// onto dead characteristics post-teardown.
|
||||
{
|
||||
let mut map = characteristic_registry().lock().unwrap();
|
||||
for (_, ptr) in map.drain() {
|
||||
@@ -2930,6 +2909,15 @@ mod apple_peripheral {
|
||||
mod notify_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn gatt_services_hold_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| {
|
||||
let g = unsafe { build_gatt_services() }.unwrap();
|
||||
vec![g.ratspeak, g.columba, g.ratspeak_tx, g.columba_tx]
|
||||
})
|
||||
}));
|
||||
}
|
||||
#[test]
|
||||
fn readiness_keeps_partial_packet_first_across_characteristics() {
|
||||
let mut state = NotifyState {
|
||||
accepting: true,
|
||||
@@ -3026,10 +3014,10 @@ mod android_peripheral {
|
||||
}
|
||||
|
||||
fn signal_peer_offline(address: &str) {
|
||||
if let Ok(g) = peer_online_map().lock() {
|
||||
if let Some(flag) = g.get(address) {
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
if let Ok(g) = peer_online_map().lock()
|
||||
&& let Some(flag) = g.get(address)
|
||||
{
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3274,10 +3262,9 @@ mod android_peripheral {
|
||||
return Err("RatspeakBleAvailability returned null".into());
|
||||
}
|
||||
let jstr: jni::objects::JString = result.into();
|
||||
Ok(env
|
||||
.get_string(jstr)
|
||||
env.get_string(jstr)
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.map_err(|e| format!("availability string: {e}"))?)
|
||||
.map_err(|e| format!("availability string: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3406,7 +3393,7 @@ mod android_peripheral {
|
||||
// Close GATT server
|
||||
with_env(|env| {
|
||||
let server_cls = find_app_class(env, "org.ratspeak.android.RatspeakBleServer")
|
||||
.map_err(|e| format!("{e}"))?;
|
||||
.map_err(|e| e.to_string())?;
|
||||
env.call_static_method(server_cls, "closeGattServer", "()V", &[])
|
||||
.map_err(|e| format!("closeGattServer: {e}"))?;
|
||||
Ok(())
|
||||
@@ -5998,11 +5985,12 @@ pub async fn spawn_ble_peer_interface(
|
||||
// already-connected peers every scan, so gating on "new
|
||||
// peers seen" alone pinned the radio at the active duty
|
||||
// cycle forever.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& peers.iter().any(|p| {
|
||||
!connected_addrs.contains_key(&p.ble_address)
|
||||
&& !reconnect_in_backoff(&recently_disc, &p.ble_address)
|
||||
});
|
||||
let have_candidate = has_connect_candidate(
|
||||
peers.iter().map(|p| p.ble_address.as_str()),
|
||||
&connected_addrs,
|
||||
&[],
|
||||
&recently_disc,
|
||||
);
|
||||
let next_interval =
|
||||
if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
@@ -6282,13 +6270,16 @@ pub async fn spawn_ble_peer_interface(
|
||||
// Connect strongest-RSSI first so a crowded room fills
|
||||
// the MAX_PEERS slots with the nearest peers.
|
||||
peers.sort_by_key(|p| std::cmp::Reverse(p.rssi));
|
||||
let peripheral_peer_addresses =
|
||||
apple_peripheral::subscribed_central_addresses();
|
||||
// Idle down when there is no actionable peer — a stable
|
||||
// mesh keeps seeing its connected peers every scan.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& peers.iter().any(|p| {
|
||||
!connected_addrs.contains_key(&p.ble_address)
|
||||
&& !reconnect_in_backoff(&recently_disc, &p.ble_address)
|
||||
});
|
||||
let have_candidate = has_connect_candidate(
|
||||
peers.iter().map(|p| p.ble_address.as_str()),
|
||||
&connected_addrs,
|
||||
&peripheral_peer_addresses,
|
||||
&recently_disc,
|
||||
);
|
||||
let next_interval =
|
||||
if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
@@ -6309,9 +6300,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
}
|
||||
scan_interval = next_interval;
|
||||
|
||||
let peripheral_peer_addresses =
|
||||
apple_peripheral::subscribed_central_addresses();
|
||||
|
||||
for peer in &peers {
|
||||
dispatch_event(BlePeerEvent::Discovered {
|
||||
address: peer.ble_address.clone(),
|
||||
@@ -6616,19 +6604,6 @@ pub async fn spawn_ble_peer_interface(
|
||||
// MAX_PEERS slots with the nearest peers.
|
||||
scan_results.sort_by_key(|r| std::cmp::Reverse(r.1));
|
||||
|
||||
// Idle down when there is no actionable peer — a stable mesh
|
||||
// keeps seeing its connected peers every scan.
|
||||
let have_candidate = connected_addrs.len() < MAX_PEERS
|
||||
&& scan_results.iter().any(|(addr, _, _)| {
|
||||
!connected_addrs.contains_key(addr)
|
||||
&& !reconnect_in_backoff(&recently_disc, addr)
|
||||
});
|
||||
let scan_interval = if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
} else {
|
||||
SCAN_IDLE_INTERVAL
|
||||
};
|
||||
|
||||
let peripheral_peer_addresses = if scan_results.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
@@ -6638,6 +6613,22 @@ pub async fn spawn_ble_peer_interface(
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// Idle down when there is no actionable peer — a stable mesh
|
||||
// keeps seeing its connected peers every scan.
|
||||
let have_candidate = has_connect_candidate(
|
||||
scan_results
|
||||
.iter()
|
||||
.filter(|(_, rssi, _)| *rssi >= MIN_RSSI)
|
||||
.map(|(addr, _, _)| addr.as_str()),
|
||||
&connected_addrs,
|
||||
&peripheral_peer_addresses,
|
||||
&recently_disc,
|
||||
);
|
||||
let scan_interval = if have_candidate || has_wanted_reconnects(&recently_disc) {
|
||||
SCAN_ACTIVE_INTERVAL
|
||||
} else {
|
||||
SCAN_IDLE_INTERVAL
|
||||
};
|
||||
|
||||
for (addr, rssi, protocol) in &scan_results {
|
||||
dispatch_event(BlePeerEvent::Discovered {
|
||||
@@ -7579,6 +7570,59 @@ mod tests {
|
||||
assert!(!reconnect_in_backoff(&map, "peer-address"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_candidates_match_what_the_connect_loop_would_try() {
|
||||
let recent = new_recently_disconnected();
|
||||
let online = || Arc::new(AtomicBool::new(true));
|
||||
let mut connected = HashMap::from([("central".to_owned(), online())]);
|
||||
let linked_to_us = vec!["subscribed".to_owned()];
|
||||
for _ in 0..RECONNECT_BACKOFF_FAILURES {
|
||||
record_reconnect_failure(&recent, "backoff");
|
||||
}
|
||||
let candidate = |scanned: &[&'static str], connected: &HashMap<_, _>| {
|
||||
has_connect_candidate(scanned.iter().copied(), connected, &linked_to_us, &recent)
|
||||
};
|
||||
|
||||
assert!(!candidate(
|
||||
&["central", "subscribed", "backoff"],
|
||||
&connected
|
||||
));
|
||||
assert!(candidate(&["central", "new"], &connected));
|
||||
for index in connected.len()..MAX_PEERS {
|
||||
connected.insert(format!("peer-{index}"), online());
|
||||
}
|
||||
assert!(!candidate(&["new"], &connected));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn scan_sleep_wakes_on_a_resume_before_or_during_it() {
|
||||
let foreground = Arc::new(AtomicBool::new(true));
|
||||
let wake = Arc::new(tokio::sync::Notify::new());
|
||||
let started = tokio::time::Instant::now();
|
||||
scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await;
|
||||
assert_eq!(
|
||||
started.elapsed(),
|
||||
Duration::ZERO,
|
||||
"a resume before the sleep"
|
||||
);
|
||||
|
||||
foreground.store(false, Ordering::Relaxed);
|
||||
let sleep = tokio::spawn({
|
||||
let (foreground, wake) = (foreground.clone(), wake.clone());
|
||||
async move { scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await }
|
||||
});
|
||||
for _ in 0..8 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
wake.notify_waiters();
|
||||
sleep.await.unwrap();
|
||||
assert_eq!(started.elapsed(), Duration::ZERO, "a wake during the sleep");
|
||||
|
||||
foreground.store(false, Ordering::Relaxed);
|
||||
scan_sleep(SCAN_BACKGROUND_INTERVAL, &foreground, false, &wake).await;
|
||||
assert_eq!(started.elapsed(), SCAN_BACKGROUND_INTERVAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_status_state_reflects_peer_count() {
|
||||
assert_eq!(peer_state_for_count(0), PeerState::Starting);
|
||||
|
||||
@@ -9,6 +9,8 @@ pub mod android_usb;
|
||||
mod android_usb_lifecycle;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod android_usb_setup;
|
||||
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
|
||||
mod apple_objc;
|
||||
pub mod auto;
|
||||
pub mod ax25kiss;
|
||||
pub mod backbone;
|
||||
|
||||
@@ -1471,6 +1471,8 @@ struct RNodeWriterContext {
|
||||
beacon_poll_interval: Duration,
|
||||
idle_probe_interval: Option<Duration>,
|
||||
idle_probes_enabled: Arc<AtomicBool>,
|
||||
/// Wakes an idle writer for cancellation or a newly installed lane.
|
||||
wake: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
@@ -1572,6 +1574,7 @@ struct RNodeGenerationWriter {
|
||||
ready: Arc<AtomicBool>,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
idle_probes_enabled: Arc<AtomicBool>,
|
||||
wake: Arc<tokio::sync::Notify>,
|
||||
task: RNodeTaskGuard<Result<RNodeWriterExit, RNodeWriteFailure>>,
|
||||
}
|
||||
|
||||
@@ -1579,6 +1582,12 @@ struct RNodeGenerationWriter {
|
||||
impl RNodeGenerationWriter {
|
||||
fn cancel(&self) {
|
||||
self.cancelled.store(true, Ordering::SeqCst);
|
||||
self.wake.notify_one();
|
||||
}
|
||||
|
||||
fn install_background(&self, lane: crate::background_announce::BackgroundAnnounceReceiver) {
|
||||
*self.background.lock().unwrap() = Some(lane);
|
||||
self.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1696,6 +1705,7 @@ enum RNodeWriterEvent {
|
||||
ProbePoll,
|
||||
FlowPoll,
|
||||
BeaconPoll,
|
||||
Wake,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
@@ -1706,6 +1716,16 @@ async fn wait_for_rnode_probe_deadline(deadline: Option<tokio::time::Instant>) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
async fn wait_for_rnode_background_offer(
|
||||
lane: Option<&crate::background_announce::BackgroundAnnounceReceiver>,
|
||||
) {
|
||||
match lane {
|
||||
Some(lane) => lane.offered().await,
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
async fn run_rnode_writer<W>(
|
||||
mut writer: W,
|
||||
@@ -1781,8 +1801,8 @@ where
|
||||
&& packet_rx.is_empty()
|
||||
&& context.carrier_online.load(Ordering::SeqCst)
|
||||
&& context.interface_online.load(Ordering::SeqCst)
|
||||
&& let Some(background) = background.filter(|lane| lane.ordinary_is_empty())
|
||||
&& let Some(packet) = background.try_start_when(rns_transport::now_f64(), || {
|
||||
&& let Some(lane) = background.as_ref().filter(|lane| lane.ordinary_is_empty())
|
||||
&& let Some(packet) = lane.try_start_when(rns_transport::now_f64(), || {
|
||||
!context.flow_control
|
||||
|| context
|
||||
.ready
|
||||
@@ -1855,12 +1875,17 @@ where
|
||||
}
|
||||
|
||||
let probe_deadline = idle_probe.as_ref().map(|probe| probe.deadline);
|
||||
// READY and carrier state have no signal, so only waiting work polls.
|
||||
let offer_waiting = background
|
||||
.as_ref()
|
||||
.is_some_and(crate::background_announce::BackgroundAnnounceReceiver::has_offer);
|
||||
let event = if pending_packet.is_some() {
|
||||
tokio::select! {
|
||||
biased;
|
||||
request = control_rx.recv(), if control_lane_open => {
|
||||
RNodeWriterEvent::Control(request)
|
||||
}
|
||||
_ = context.wake.notified() => RNodeWriterEvent::Wake,
|
||||
_ = wait_for_rnode_probe_deadline(probe_deadline) => {
|
||||
RNodeWriterEvent::ProbePoll
|
||||
}
|
||||
@@ -1874,12 +1899,16 @@ where
|
||||
request = control_rx.recv(), if control_lane_open => {
|
||||
RNodeWriterEvent::Control(request)
|
||||
}
|
||||
_ = context.wake.notified() => RNodeWriterEvent::Wake,
|
||||
_ = wait_for_rnode_probe_deadline(probe_deadline) => {
|
||||
RNodeWriterEvent::ProbePoll
|
||||
}
|
||||
_ = tokio::time::sleep(RNODE_FLOW_POLL_INTERVAL) => {
|
||||
_ = tokio::time::sleep(RNODE_FLOW_POLL_INTERVAL), if offer_waiting => {
|
||||
RNodeWriterEvent::FlowPoll
|
||||
}
|
||||
_ = wait_for_rnode_background_offer(background.as_ref()), if !offer_waiting => {
|
||||
RNodeWriterEvent::Wake
|
||||
}
|
||||
packet = packet_rx.recv(), if packet_lane_open => {
|
||||
RNodeWriterEvent::Packet(packet)
|
||||
}
|
||||
@@ -1931,6 +1960,7 @@ where
|
||||
}
|
||||
RNodeWriterEvent::ProbePoll => {}
|
||||
RNodeWriterEvent::FlowPoll => {}
|
||||
RNodeWriterEvent::Wake => {}
|
||||
// Wake the top-of-loop due check even when both input lanes are
|
||||
// idle. Checking there also prevents a continuously ready packet
|
||||
// lane from starving an elapsed station-ID beacon.
|
||||
@@ -1950,6 +1980,7 @@ where
|
||||
let ready = context.ready.clone();
|
||||
let cancelled = context.cancelled.clone();
|
||||
let idle_probes_enabled = context.idle_probes_enabled.clone();
|
||||
let wake = context.wake.clone();
|
||||
let carrier_online = context.carrier_online.clone();
|
||||
let interface_online = context.interface_online.clone();
|
||||
let id = context.id;
|
||||
@@ -1975,6 +2006,7 @@ where
|
||||
ready,
|
||||
cancelled,
|
||||
idle_probes_enabled,
|
||||
wake,
|
||||
task: RNodeTaskGuard::new(task),
|
||||
}
|
||||
}
|
||||
@@ -2015,6 +2047,7 @@ fn spawn_rnode_generation_writer(
|
||||
beacon_poll_interval: RNODE_BEACON_POLL_INTERVAL,
|
||||
idle_probe_interval: port.is_tcp().then_some(RNODE_TCP_IDLE_PROBE_INTERVAL),
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(options.idle_probes_enabled)),
|
||||
wake: Arc::new(tokio::sync::Notify::new()),
|
||||
},
|
||||
);
|
||||
writer.interrupt = interrupt;
|
||||
@@ -2031,6 +2064,7 @@ async fn finish_rnode_writer(writer: RNodeGenerationWriter) -> RNodeWriterFinish
|
||||
ready: _,
|
||||
cancelled: _,
|
||||
idle_probes_enabled: _,
|
||||
wake: _,
|
||||
mut task,
|
||||
background: _,
|
||||
} = writer;
|
||||
@@ -4225,7 +4259,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
let mut port_r = port_r;
|
||||
|
||||
background.retire_generation();
|
||||
*generation_writer.background.lock().unwrap() = Some(background.clone());
|
||||
generation_writer.install_background(background.clone());
|
||||
let ready = generation_writer.ready.clone();
|
||||
let packet_tx = generation_writer.packet_tx.clone();
|
||||
let control_tx = generation_writer.control_tx.clone();
|
||||
@@ -4759,6 +4793,7 @@ mod tests {
|
||||
beacon_poll_interval,
|
||||
idle_probe_interval: None,
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(true)),
|
||||
wake: Arc::new(tokio::sync::Notify::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9323,4 +9358,55 @@ mod tests {
|
||||
tokio::time::advance(RNODE_FLOW_POLL_INTERVAL).await;
|
||||
finish_rnode_writer(writer).await;
|
||||
}
|
||||
|
||||
// The clock never moves here: an idle writer has no poll to fall back on,
|
||||
// so each step proves its wake signal.
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn idle_writer_wakes_for_lane_install_offer_and_cancel_without_polling() {
|
||||
let (outer, _outer_rx) = mpsc::channel(2);
|
||||
let background = crate::background_announce::register(&outer).unwrap();
|
||||
let (actor, actor_control, raw) =
|
||||
crate::background_announce::scheduled_actor(outer.clone());
|
||||
let scripted = ScriptedWriter::default();
|
||||
let context = scripted_writer_context(
|
||||
false,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicU64::new(0)),
|
||||
None,
|
||||
Duration::from_millis(5),
|
||||
);
|
||||
let mut writer = spawn_rnode_writer(scripted.clone(), context);
|
||||
yield_to_rnode_tasks().await;
|
||||
|
||||
writer.install_background(background.clone());
|
||||
yield_to_rnode_tasks().await;
|
||||
actor_control
|
||||
.send(TransportMessage::Tick(rns_transport::messages::TimerTick))
|
||||
.await
|
||||
.unwrap();
|
||||
yield_until_rnode_test(
|
||||
|| scripted.flush_calls() == 1,
|
||||
"an offer must wake an idle writer",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(scripted.writes(), vec![kiss::frame(&raw)]);
|
||||
|
||||
writer.cancel();
|
||||
yield_until_rnode_test(
|
||||
|| writer.task.is_finished(),
|
||||
"cancel must wake an idle writer",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
writer.task.take().await.unwrap().unwrap(),
|
||||
RNodeWriterExit::Cancelled
|
||||
);
|
||||
actor_control
|
||||
.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.unwrap();
|
||||
actor.await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1149,13 +1149,18 @@ impl LazyMultiSegmentOutbound {
|
||||
|
||||
/// Collect independently verified Resource segments in order. Use
|
||||
/// `set_segment` with `assemble_segment`, or pass already verified payloads to
|
||||
/// `set_segment_data`. `reassemble` concatenates those payloads; it does not
|
||||
/// recompute or verify `original_hash` or impose a total byte limit.
|
||||
/// `set_segment_data`. Payloads that arrive in order are appended to one
|
||||
/// buffer at once; `take_reassembled` returns it. Neither recomputes or
|
||||
/// verifies `original_hash`.
|
||||
pub struct MultiSegmentInbound {
|
||||
pub original_hash: [u8; 32],
|
||||
pub total_segments: usize,
|
||||
pub segments: Vec<Option<InboundResource>>,
|
||||
/// Payloads that arrived ahead of a missing segment, by 0-based index.
|
||||
pub assembled_segments: Vec<Option<Vec<u8>>>,
|
||||
/// Segments `1..=assembled_through`, concatenated.
|
||||
pub assembled: Vec<u8>,
|
||||
pub assembled_through: usize,
|
||||
pub data_size: usize,
|
||||
/// First metadata supplied through `set_metadata`. Outbound constructors
|
||||
/// can attach metadata to the first segment; the owner must carry it here
|
||||
@@ -1174,6 +1179,8 @@ impl MultiSegmentInbound {
|
||||
total_segments,
|
||||
segments: Vec::new(),
|
||||
assembled_segments: Vec::new(),
|
||||
assembled: Vec::new(),
|
||||
assembled_through: 0,
|
||||
data_size: 0,
|
||||
metadata: None,
|
||||
size_bound: None,
|
||||
@@ -1215,13 +1222,43 @@ impl MultiSegmentInbound {
|
||||
let idx = segment_index - 1;
|
||||
if let Some(Some(resource)) = self.segments.get_mut(idx) {
|
||||
let data = resource.assemble(decrypt_fn)?;
|
||||
*Self::slot(&mut self.assembled_segments, idx) = Some(data);
|
||||
self.store(idx, data);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ResourceError::Incomplete)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_segment(&self, idx: usize) -> bool {
|
||||
idx < self.assembled_through || matches!(self.assembled_segments.get(idx), Some(Some(_)))
|
||||
}
|
||||
|
||||
/// Append the payload when it is next in order, then any parked payloads
|
||||
/// it unblocks; otherwise park it.
|
||||
fn store(&mut self, idx: usize, data: Vec<u8>) {
|
||||
if idx < self.assembled_through {
|
||||
return;
|
||||
}
|
||||
if idx > self.assembled_through {
|
||||
*Self::slot(&mut self.assembled_segments, idx) = Some(data);
|
||||
return;
|
||||
}
|
||||
let mut next = Some(data);
|
||||
while let Some(data) = next.take() {
|
||||
// Grown as data arrives, never from the peer's segment count.
|
||||
if self.assembled_through == 0 {
|
||||
self.assembled = data;
|
||||
} else {
|
||||
self.assembled.extend_from_slice(&data);
|
||||
}
|
||||
self.assembled_through += 1;
|
||||
next = self
|
||||
.assembled_segments
|
||||
.get_mut(self.assembled_through)
|
||||
.and_then(Option::take);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime ingest of an assembled segment at 1-based `segment_index`.
|
||||
/// Errors: `InvalidAdvertisement` for out-of-range index;
|
||||
/// `DuplicateSegment` on overwrite (slot already accepted); `TooLarge`
|
||||
@@ -1238,12 +1275,11 @@ impl MultiSegmentInbound {
|
||||
if self.size_bound.is_some_and(|bound| data_size > bound) {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
let slot = Self::slot(&mut self.assembled_segments, segment_index - 1);
|
||||
if slot.is_some() {
|
||||
if self.has_segment(segment_index - 1) {
|
||||
return Err(ResourceError::DuplicateSegment);
|
||||
}
|
||||
self.data_size = data_size;
|
||||
*slot = Some(data);
|
||||
self.store(segment_index - 1, data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1258,23 +1294,31 @@ impl MultiSegmentInbound {
|
||||
self.assembled_count() == self.total_segments
|
||||
}
|
||||
|
||||
/// Concatenate every assembled segment into the original payload.
|
||||
/// A copy of the original payload. [`Self::take_reassembled`] moves it.
|
||||
pub fn reassemble(&self) -> Result<Vec<u8>, ResourceError> {
|
||||
if !self.is_complete() {
|
||||
return Err(ResourceError::Incomplete);
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
for seg in &self.assembled_segments {
|
||||
result.extend_from_slice(seg.as_ref().ok_or(ResourceError::Incomplete)?);
|
||||
Ok(self.assembled.clone())
|
||||
}
|
||||
|
||||
/// Move out the original payload, leaving this collector empty.
|
||||
pub fn take_reassembled(&mut self) -> Result<Vec<u8>, ResourceError> {
|
||||
if !self.is_complete() {
|
||||
return Err(ResourceError::Incomplete);
|
||||
}
|
||||
Ok(result)
|
||||
let mut payload = std::mem::take(&mut self.assembled);
|
||||
payload.shrink_to_fit();
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
pub fn assembled_count(&self) -> usize {
|
||||
self.assembled_segments
|
||||
.iter()
|
||||
.filter(|s| s.is_some())
|
||||
.count()
|
||||
self.assembled_through
|
||||
+ self
|
||||
.assembled_segments
|
||||
.iter()
|
||||
.filter(|s| s.is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Fraction of segments assembled so far, in `0.0..=1.0`.
|
||||
@@ -4440,6 +4484,32 @@ mod tests {
|
||||
assert_eq!(&blob[4..], &[0xCC; 4]);
|
||||
}
|
||||
|
||||
/// In-order payloads join one buffer as they arrive; a later one waits for
|
||||
/// the gap, and a repeat of either is refused.
|
||||
#[test]
|
||||
fn multi_segment_payloads_join_in_order_as_they_arrive() {
|
||||
let mut inbound = MultiSegmentInbound::new(3, [0x11; 32]);
|
||||
inbound.set_segment_data(1, vec![1; 4]).unwrap();
|
||||
assert_eq!(inbound.assembled, [1; 4]);
|
||||
inbound.set_segment_data(3, vec![3; 2]).unwrap();
|
||||
assert_eq!(inbound.assembled_count(), 2);
|
||||
assert!(matches!(
|
||||
inbound.set_segment_data(1, vec![9]),
|
||||
Err(ResourceError::DuplicateSegment)
|
||||
));
|
||||
assert!(matches!(
|
||||
inbound.set_segment_data(3, vec![9]),
|
||||
Err(ResourceError::DuplicateSegment)
|
||||
));
|
||||
assert!(inbound.take_reassembled().is_err());
|
||||
inbound.set_segment_data(2, vec![2; 4]).unwrap();
|
||||
assert!(inbound.assembled_segments.iter().all(Option::is_none));
|
||||
assert_eq!(
|
||||
inbound.take_reassembled().unwrap(),
|
||||
[vec![1; 4], vec![2; 4], vec![3; 2]].concat()
|
||||
);
|
||||
}
|
||||
|
||||
/// Out-of-range indices (`0` and `> total_segments`) must surface as
|
||||
/// `InvalidAdvertisement`, distinct from the duplicate path.
|
||||
#[test]
|
||||
|
||||
@@ -298,12 +298,15 @@ pub enum Admission<T> {
|
||||
Dropped(T),
|
||||
}
|
||||
|
||||
/// Per-destination stamp state for an owner's event loop. Parked path
|
||||
/// responses are kept in order; ordinary announces coalesce to the latest.
|
||||
/// Per-destination stamp state for an owner's event loop, shaped like
|
||||
/// Python's stamp queue: the announce that started the job is in progress and
|
||||
/// leaves first; parked path responses follow in order, then the parked
|
||||
/// announce, which coalesces to the latest.
|
||||
pub struct DestinationStamps<T> {
|
||||
owner: u64,
|
||||
tx: mpsc::UnboundedSender<StampOutcome>,
|
||||
rx: mpsc::UnboundedReceiver<StampOutcome>,
|
||||
in_progress: Option<(T, bool)>,
|
||||
parked_path_responses: VecDeque<T>,
|
||||
parked_announce: Option<T>,
|
||||
job: Option<Arc<AtomicBool>>,
|
||||
@@ -316,6 +319,7 @@ impl<T> Default for DestinationStamps<T> {
|
||||
owner: NEXT_OWNER.fetch_add(1, Ordering::Relaxed),
|
||||
tx,
|
||||
rx,
|
||||
in_progress: None,
|
||||
parked_path_responses: VecDeque::new(),
|
||||
parked_announce: None,
|
||||
job: None,
|
||||
@@ -347,18 +351,16 @@ impl<T> DestinationStamps<T> {
|
||||
if destination.destination_stamp_meets(target) {
|
||||
return Admission::Ready(item, destination.announce_stamp_ext(policy.lr_cost));
|
||||
}
|
||||
if path_response {
|
||||
if self.parked_path_responses.len() >= STAMPER_PR_QUEUE_LENGTH {
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
return Admission::Dropped(item);
|
||||
}
|
||||
self.parked_path_responses.push_back(item);
|
||||
} else {
|
||||
self.parked_announce = Some(item);
|
||||
}
|
||||
if self.job.is_some() {
|
||||
if path_response {
|
||||
if self.parked_path_responses.len() >= STAMPER_PR_QUEUE_LENGTH {
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
return Admission::Dropped(item);
|
||||
}
|
||||
self.parked_path_responses.push_back(item);
|
||||
promote(self.owner);
|
||||
} else {
|
||||
self.parked_announce = Some(item);
|
||||
}
|
||||
return Admission::Queued;
|
||||
}
|
||||
@@ -374,22 +376,18 @@ impl<T> DestinationStamps<T> {
|
||||
cancel: cancel.clone(),
|
||||
reply: self.tx.clone(),
|
||||
};
|
||||
let priority = if self.parked_path_responses.is_empty() {
|
||||
Priority::Announce
|
||||
} else {
|
||||
let priority = if path_response {
|
||||
Priority::PathResponse
|
||||
} else {
|
||||
Priority::Announce
|
||||
};
|
||||
if submit(job, priority) {
|
||||
self.job = Some(cancel);
|
||||
self.in_progress = Some((item, path_response));
|
||||
return Admission::Queued;
|
||||
}
|
||||
tracing::debug!(dest = %destination, "stamp queue full, dropping announce");
|
||||
let dropped = if path_response {
|
||||
self.parked_path_responses.pop_back()
|
||||
} else {
|
||||
self.parked_announce.take()
|
||||
};
|
||||
Admission::Dropped(dropped.expect("item was parked above"))
|
||||
Admission::Dropped(item)
|
||||
}
|
||||
|
||||
/// Wait for the in-flight job. Cancellation safe.
|
||||
@@ -405,8 +403,9 @@ impl<T> DestinationStamps<T> {
|
||||
self.rx.try_recv().ok()
|
||||
}
|
||||
|
||||
/// Install a finished stamp and release the parked announces, path
|
||||
/// responses first. A failed job cancels them, as `_announce` does.
|
||||
/// Install a finished stamp and release the announce in progress, then the
|
||||
/// parked path responses, then the parked announce. A failed job cancels
|
||||
/// them, as `_announce` does.
|
||||
pub fn complete(
|
||||
&mut self,
|
||||
destination: &mut Destination,
|
||||
@@ -414,9 +413,11 @@ impl<T> DestinationStamps<T> {
|
||||
outcome: StampOutcome,
|
||||
) -> Vec<(T, Option<AnnounceStampExt>)> {
|
||||
self.job = None;
|
||||
let in_progress = self.in_progress.take();
|
||||
let Some((stamp, value)) = outcome.stamp else {
|
||||
let cancelled =
|
||||
self.parked_path_responses.len() + usize::from(self.parked_announce.is_some());
|
||||
let cancelled = usize::from(in_progress.is_some())
|
||||
+ self.parked_path_responses.len()
|
||||
+ usize::from(self.parked_announce.is_some());
|
||||
self.parked_path_responses.clear();
|
||||
self.parked_announce = None;
|
||||
if cancelled > 0 {
|
||||
@@ -426,11 +427,12 @@ impl<T> DestinationStamps<T> {
|
||||
return Vec::new();
|
||||
};
|
||||
destination.set_destination_stamp(stamp, value);
|
||||
let mut parked: Vec<(T, bool)> = self
|
||||
.parked_path_responses
|
||||
.drain(..)
|
||||
.map(|item| (item, true))
|
||||
.collect();
|
||||
let mut parked: Vec<(T, bool)> = in_progress.into_iter().collect();
|
||||
parked.extend(
|
||||
self.parked_path_responses
|
||||
.drain(..)
|
||||
.map(|item| (item, true)),
|
||||
);
|
||||
parked.extend(self.parked_announce.take().map(|item| (item, false)));
|
||||
let mut ready = Vec::new();
|
||||
for (item, path_response) in parked {
|
||||
@@ -612,6 +614,44 @@ mod tests {
|
||||
dir
|
||||
}
|
||||
|
||||
/// Python's stamper finishes the announce it is generating for before it
|
||||
/// takes a queued path response, so a registration path response cannot
|
||||
/// overtake the application's own first announce.
|
||||
#[test]
|
||||
fn the_announce_that_started_a_stamp_leaves_first() {
|
||||
let _settings = test_settings::blocking_exclusive(quick_policy(), None);
|
||||
let identity = Identity::new();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
for (first, second) in [
|
||||
((false, "announce"), (true, "path response")),
|
||||
((true, "path response"), (false, "announce")),
|
||||
] {
|
||||
let mut destination = Destination::new(
|
||||
Some(&identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
"test.stamp.order",
|
||||
)
|
||||
.unwrap();
|
||||
let mut stamps = DestinationStamps::new();
|
||||
for (path_response, name) in [first, second] {
|
||||
assert!(matches!(
|
||||
stamps.admit(&destination, &identity, path_response, name),
|
||||
Admission::Queued
|
||||
));
|
||||
}
|
||||
let outcome = runtime.block_on(stamps.recv());
|
||||
let order: Vec<_> = stamps
|
||||
.complete(&mut destination, &identity, outcome)
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect();
|
||||
assert_eq!(order, [first.1, second.1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_saves_a_stamp_the_first_announce_loads_without_waiting() {
|
||||
let dir = scratch_dir("saves");
|
||||
|
||||
@@ -4731,7 +4731,7 @@ impl LinkManager {
|
||||
if coordinator.is_complete() {
|
||||
let total_segments = coordinator.total_segments;
|
||||
coordinator
|
||||
.reassemble()
|
||||
.take_reassembled()
|
||||
.map(|blob| {
|
||||
Some((
|
||||
blob,
|
||||
|
||||
@@ -3552,7 +3552,7 @@ async fn complete_inbound_segment(
|
||||
coordinator.set_metadata(metadata);
|
||||
}
|
||||
if coordinator.is_complete() {
|
||||
match coordinator.reassemble() {
|
||||
match coordinator.take_reassembled() {
|
||||
Ok(data) => {
|
||||
complete_data = Some(data);
|
||||
complete_metadata = coordinator.metadata.take();
|
||||
|
||||
@@ -845,6 +845,7 @@ impl TransportActor {
|
||||
let announce_identity_hash = Some(validated.identity_hash);
|
||||
let announce_random_hash = announce_data.random_hash;
|
||||
let announce_stamp_value = validated.stamp_value.unwrap_or(0.0);
|
||||
let announce_emitted = announce_timebase(&announce_random_hash);
|
||||
|
||||
// Python remembers every freshly validated announce, replays included,
|
||||
// before it decides whether the path changes; a validation-cache hit
|
||||
@@ -868,6 +869,7 @@ impl TransportActor {
|
||||
e.is_path_response = is_path_response;
|
||||
e.name_hash = announce_name_hash;
|
||||
e.facts_known = true;
|
||||
e.emitted = Some(announce_emitted);
|
||||
self.kd.pending.mark_dirty(header.destination_hash);
|
||||
self.remember_received_ratchet(header.destination_hash, announce_ratchet);
|
||||
}
|
||||
@@ -891,6 +893,7 @@ impl TransportActor {
|
||||
stamp_value: announce_stamp_value,
|
||||
lr_cost: validated.lr_cost,
|
||||
facts_known: true,
|
||||
emitted: Some(announce_emitted),
|
||||
});
|
||||
self.state_dirty = true;
|
||||
self.kd.pending.mark_dirty(header.destination_hash);
|
||||
@@ -915,8 +918,6 @@ impl TransportActor {
|
||||
.map(|e| e.mode)
|
||||
.unwrap_or(InterfaceMode::Gateway);
|
||||
|
||||
let announce_emitted = announce_timebase(&announce_random_hash);
|
||||
|
||||
// Cancel our queued rebroadcast when a neighbor already carried it.
|
||||
// Same-hop neighbor rebroadcast counts toward the local cap;
|
||||
// strict hops+1 forward drops our queued copy outright.
|
||||
@@ -1439,6 +1440,8 @@ impl TransportActor {
|
||||
.insert(pkt_hash, interface_id, Some(target_interface));
|
||||
self.send_to_interface(target_interface, &forwarded);
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
// A first use is persisted: the path cull keeps used paths.
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
trace!(
|
||||
@@ -1568,6 +1571,8 @@ impl TransportActor {
|
||||
return;
|
||||
}
|
||||
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
|
||||
// A first use is persisted: the path cull keeps used paths.
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
|
||||
@@ -2237,6 +2242,7 @@ impl TransportActor {
|
||||
}
|
||||
// Transport.py
|
||||
if let Some(path) = self.path_table.get_mut(&entry.destination_hash) {
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
trace!(
|
||||
|
||||
@@ -45,7 +45,9 @@ impl TransportActor {
|
||||
if now - self.last_tables_cull >= TABLES_CULL_INTERVAL {
|
||||
self.cull_path_table(now);
|
||||
self.reverse_table.cull_expired();
|
||||
self.tunnel_table.cull_expired();
|
||||
if self.tunnel_table.cull_expired() > 0 {
|
||||
self.state_dirty = true;
|
||||
}
|
||||
self.cull_stale_tunnel_paths(now);
|
||||
self.cull_path_interface_suppressions(now);
|
||||
self.cull_local_link_route_attempts(now);
|
||||
@@ -75,12 +77,6 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Cull may have removed path/tunnel entries — flag for save so
|
||||
// the on-disk file reflects the current routing state. False
|
||||
// positives (cull found nothing) cost one no-op file rewrite at
|
||||
// the next periodic flush.
|
||||
self.state_dirty = true;
|
||||
self.last_tables_cull = now;
|
||||
}
|
||||
|
||||
@@ -131,8 +127,8 @@ impl TransportActor {
|
||||
if now - self.last_blackhole_check >= BLACKHOLE_CHECK_INTERVAL {
|
||||
if self.blackhole_table.cull_expired() > 0 {
|
||||
self.publish_blackhole_snapshot();
|
||||
self.state_dirty = true;
|
||||
}
|
||||
self.state_dirty = true;
|
||||
self.last_blackhole_check = now;
|
||||
}
|
||||
|
||||
@@ -266,6 +262,7 @@ impl TransportActor {
|
||||
}
|
||||
}
|
||||
if removed > 0 {
|
||||
self.state_dirty = true;
|
||||
pathing!(removed, "removed stale paths");
|
||||
}
|
||||
}
|
||||
@@ -765,6 +762,7 @@ mod cleanup_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
};
|
||||
actor.recent_announces.insert(entry.dest_hash, entry);
|
||||
}
|
||||
|
||||
@@ -318,6 +318,8 @@ pub struct TransportActor {
|
||||
/// decides whether a queued writer is still current.
|
||||
pub(crate) routing_save_lock: std::sync::Arc<std::sync::Mutex<()>>,
|
||||
pub(crate) hashlist_save_in_flight: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
/// `packet_hashlist.revision()` as last loaded or saved.
|
||||
pub(crate) hashlist_saved_revision: u64,
|
||||
|
||||
/// Persisted path entries waiting on their interface to re-register.
|
||||
/// Drained by `drain_pending_for_interface` on `RegisterInterface`.
|
||||
@@ -389,6 +391,10 @@ pub struct RecentAnnounce {
|
||||
/// False for an entry restored from a row that carries no announce facts:
|
||||
/// `hops`, `name_hash`, and `is_path_response` are then unknown, not zero.
|
||||
pub facts_known: bool,
|
||||
/// Emission time stamped into the random hash of the packet that last
|
||||
/// refreshed this entry, which may be an older announce heard late; `None`
|
||||
/// once restored from storage.
|
||||
pub emitted: Option<u64>,
|
||||
}
|
||||
|
||||
impl RecentAnnounce {
|
||||
@@ -608,6 +614,7 @@ impl TransportActor {
|
||||
routing_save_generation: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||
routing_save_lock: std::sync::Arc::new(std::sync::Mutex::new(())),
|
||||
hashlist_save_in_flight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
||||
hashlist_saved_revision: 0,
|
||||
pending_path_entries: Vec::new(),
|
||||
recent_announces: HashMap::new(),
|
||||
startup_complete: false,
|
||||
@@ -3325,6 +3332,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3398,6 +3406,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -3497,6 +3506,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -3523,6 +3533,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
let mut target_path =
|
||||
@@ -6346,6 +6357,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -6401,6 +6413,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -8648,6 +8661,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
actor.blackhole_table.add_with_reason(
|
||||
@@ -9361,6 +9375,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
}];
|
||||
|
||||
let dir = std::env::temp_dir().join("reticulum_rs_test_announce_cache");
|
||||
@@ -9664,6 +9679,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -9928,6 +9944,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -11657,6 +11674,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -12305,6 +12323,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -12567,6 +12586,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -12658,6 +12678,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -12806,6 +12827,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -13288,6 +13310,39 @@ mod tests {
|
||||
assert_eq!(hrx.try_recv().unwrap().emitted, emitted);
|
||||
}
|
||||
|
||||
/// Once the path is gone an older announce is accepted again (Transport.py)
|
||||
/// and refreshes the cache, so the entry carries its own, older emission.
|
||||
#[test]
|
||||
fn cached_announce_reports_the_emission_of_the_packet_that_refreshed_it() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
let (entry, _rx) = make_test_interface("test_iface");
|
||||
actor.interfaces.insert(1, entry);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
for (prefix, emitted) in [(0x41, 1_700_000_100), (0x42, 1_700_000_000)] {
|
||||
let (raw, dest_hash) = make_announce_for_with_random_blob(
|
||||
&identity,
|
||||
"test.emitted",
|
||||
1,
|
||||
random_blob(prefix, emitted),
|
||||
);
|
||||
actor.on_inbound(crate::messages::InboundPacket {
|
||||
raw,
|
||||
interface_id: 1,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
let crate::messages::TransportQueryResponse::Announces(entries) =
|
||||
actor.handle_query(crate::messages::TransportQuery::GetRecentAnnounces)
|
||||
else {
|
||||
panic!("expected Announces");
|
||||
};
|
||||
let cached = entries.iter().find(|e| e.dest_hash == dest_hash).unwrap();
|
||||
assert_eq!(cached.emitted, Some(emitted));
|
||||
actor.path_table.remove(&dest_hash);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_response_bypasses_announce_rate_limit() {
|
||||
let (mut actor, _tx) = TransportActor::new();
|
||||
@@ -13583,6 +13638,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -266,6 +266,7 @@ impl TransportActor {
|
||||
|
||||
// Transport.py: traffic marks use, never liveness.
|
||||
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
|
||||
self.state_dirty |= path.used == 0.0;
|
||||
path.mark_used();
|
||||
}
|
||||
sent
|
||||
|
||||
@@ -43,6 +43,7 @@ fn recent_announce_from_cached_packet(
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: false,
|
||||
emitted: None,
|
||||
};
|
||||
|
||||
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&raw_packet)
|
||||
@@ -86,35 +87,42 @@ pub(super) struct RoutingSnapshot {
|
||||
pub transport_identity_hash: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
fn write_encoded(
|
||||
dir: &std::path::Path,
|
||||
name: &str,
|
||||
encoded: Result<Vec<u8>, crate::persistence::PersistenceError>,
|
||||
) -> bool {
|
||||
let written =
|
||||
encoded.and_then(|bytes| crate::persistence::atomic_write_bytes(&dir.join(name), &bytes));
|
||||
if let Err(e) = &written {
|
||||
trace!("failed to save {name}: {e}");
|
||||
}
|
||||
written.is_ok()
|
||||
}
|
||||
|
||||
/// Persist a routing snapshot. Runs on the blocking pool for periodic saves
|
||||
/// and inline for shutdown; must not touch the actor.
|
||||
pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSnapshot) {
|
||||
let interface_names = &snapshot.interface_names;
|
||||
use crate::persistence as p;
|
||||
let keys = p::interface_keys(&snapshot.interface_names);
|
||||
|
||||
let path_table_path = dir.join("path_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_path_table(&snapshot.path_table, interface_names, &path_table_path)
|
||||
{
|
||||
trace!("failed to save path table: {}", e);
|
||||
} else {
|
||||
if write_encoded(
|
||||
dir,
|
||||
"path_table.msgpack",
|
||||
p::encode_path_table(&snapshot.path_table, &keys),
|
||||
) {
|
||||
debug!("saved path table ({} entries)", snapshot.path_table.len());
|
||||
}
|
||||
|
||||
let destination_table_path = dir.join("destination_table");
|
||||
if let Err(e) = crate::persistence::save_python_destination_table(
|
||||
&snapshot.path_table,
|
||||
interface_names,
|
||||
&destination_table_path,
|
||||
write_encoded(
|
||||
dir,
|
||||
"destination_table",
|
||||
p::encode_python_destination_table(&snapshot.path_table, &keys),
|
||||
);
|
||||
if write_encoded(
|
||||
dir,
|
||||
"blackhole_table.msgpack",
|
||||
p::encode_blackhole_table(&snapshot.blackhole_table),
|
||||
) {
|
||||
trace!("failed to save Python destination_table: {}", e);
|
||||
}
|
||||
|
||||
let blackhole_path = dir.join("blackhole_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_blackhole_table(&snapshot.blackhole_table, &blackhole_path)
|
||||
{
|
||||
trace!("failed to save blackhole table: {}", e);
|
||||
} else {
|
||||
debug!(
|
||||
"saved blackhole table ({} entries)",
|
||||
snapshot.blackhole_table.len()
|
||||
@@ -123,39 +131,32 @@ pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSn
|
||||
|
||||
// Publisher files are written only when fetched (Discovery.py).
|
||||
if let Some(local_identity_hash) = snapshot.transport_identity_hash {
|
||||
let blackhole_dir = dir.join("blackhole");
|
||||
if let Err(e) = crate::persistence::save_local_blackhole_file(
|
||||
&snapshot.blackhole_table,
|
||||
local_identity_hash,
|
||||
&blackhole_dir,
|
||||
) {
|
||||
trace!("failed to save Python blackhole files: {}", e);
|
||||
let written =
|
||||
p::encode_local_blackhole_file(&snapshot.blackhole_table, local_identity_hash)
|
||||
.and_then(|bytes| p::write_local_blackhole_file(&bytes, &dir.join("blackhole")));
|
||||
if let Err(e) = written {
|
||||
trace!("failed to save Python blackhole files: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// Per-announce Python cache files are written event-driven at receive
|
||||
// (`cache_announce_to_disk`), not re-serialized here every cycle.
|
||||
|
||||
let tunnel_path = dir.join("tunnel_table.msgpack");
|
||||
if let Err(e) =
|
||||
crate::persistence::save_tunnel_table(&snapshot.tunnel_table, interface_names, &tunnel_path)
|
||||
{
|
||||
trace!("failed to save tunnel table: {}", e);
|
||||
} else {
|
||||
if write_encoded(
|
||||
dir,
|
||||
"tunnel_table.msgpack",
|
||||
p::encode_tunnel_table(&snapshot.tunnel_table, &keys),
|
||||
) {
|
||||
debug!(
|
||||
"saved tunnel table ({} entries)",
|
||||
snapshot.tunnel_table.len()
|
||||
);
|
||||
}
|
||||
|
||||
let python_tunnels_path = dir.join("tunnels");
|
||||
if let Err(e) = crate::persistence::save_python_tunnel_table(
|
||||
&snapshot.tunnel_table,
|
||||
interface_names,
|
||||
&python_tunnels_path,
|
||||
) {
|
||||
trace!("failed to save Python tunnels table: {}", e);
|
||||
}
|
||||
write_encoded(
|
||||
dir,
|
||||
"tunnels",
|
||||
p::encode_python_tunnel_table(&snapshot.tunnel_table, &keys),
|
||||
);
|
||||
|
||||
debug!(
|
||||
paths = snapshot.path_table.len(),
|
||||
@@ -430,6 +431,7 @@ impl TransportActor {
|
||||
trace!("failed to save hashlist: {}", e);
|
||||
} else {
|
||||
info!(entries = hashes.len(), "flushed hashlist");
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
}
|
||||
save_announce_rate_table(dir, &self.rate_table.to_bytes());
|
||||
}
|
||||
@@ -438,15 +440,22 @@ impl TransportActor {
|
||||
/// Falling-edge (foreground→background) flush. Same coverage as
|
||||
/// `save_state` but entirely off-actor: on desktop the edge fires on
|
||||
/// every window focus loss, and the inline fsync chain (F_FULLFSYNC per
|
||||
/// file on macOS) stalls routing + control queries for seconds.
|
||||
/// file on macOS) stalls routing + control queries for seconds. What
|
||||
/// is already on disk is not written again.
|
||||
pub(super) fn save_state_async(&mut self) {
|
||||
self.save_routing_state_async();
|
||||
if self.state_dirty {
|
||||
self.save_routing_state_async();
|
||||
}
|
||||
if !self.owns_persistent_hashlist() {
|
||||
return;
|
||||
}
|
||||
let Some(dir) = self.storage_dir.clone() else {
|
||||
return;
|
||||
};
|
||||
let revision = self.packet_hashlist.revision();
|
||||
if revision == self.hashlist_saved_revision {
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.hashlist_save_in_flight
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
@@ -456,6 +465,7 @@ impl TransportActor {
|
||||
}
|
||||
self.hashlist_save_in_flight
|
||||
.store(true, std::sync::atomic::Ordering::Release);
|
||||
self.hashlist_saved_revision = revision;
|
||||
let hashes = self.packet_hashlist.current_hashes();
|
||||
let rate_table = self.rate_table.to_bytes();
|
||||
let in_flight = self.hashlist_save_in_flight.clone();
|
||||
@@ -548,6 +558,7 @@ impl TransportActor {
|
||||
);
|
||||
}
|
||||
self.packet_hashlist.load_from(loaded.hashes);
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
debug!(count, "loaded canonical packet hashlist from disk");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -575,6 +586,7 @@ impl TransportActor {
|
||||
self.packet_hashlist.load_from(hashes.clone());
|
||||
match crate::persistence::save_raw_hashes(&hashes, &raw_path) {
|
||||
Ok(()) => {
|
||||
self.hashlist_saved_revision = self.packet_hashlist.revision();
|
||||
info!(
|
||||
source = %legacy_path.display(),
|
||||
destination = %raw_path.display(),
|
||||
@@ -1271,6 +1283,7 @@ mod announce_clean_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
actor
|
||||
@@ -1451,6 +1464,46 @@ mod async_save_tests {
|
||||
actor
|
||||
}
|
||||
|
||||
/// A cull pass that removes nothing leaves the routing state clean, so the
|
||||
/// periodic save has nothing to write.
|
||||
#[test]
|
||||
fn empty_cull_pass_leaves_state_clean() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
actor.state_dirty = false;
|
||||
actor.last_tables_cull = 0.0;
|
||||
actor.last_blackhole_check = 0.0;
|
||||
actor.on_tick();
|
||||
assert!(actor.path_table.has_path(&[0x11; 16]));
|
||||
assert!(!actor.state_dirty);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A background edge writes only what changed since the last save.
|
||||
#[test]
|
||||
fn background_save_skips_unchanged_state() {
|
||||
let dir = temp_storage();
|
||||
let mut actor = dirty_actor(&dir);
|
||||
actor.is_transport_enabled = true;
|
||||
actor.state_dirty = false;
|
||||
actor.save_state_async();
|
||||
assert!(!dir.join("path_table.msgpack").exists());
|
||||
assert!(!dir.join("packet_hashlist.raw").exists());
|
||||
|
||||
actor.packet_hashlist.insert([0xAA; 32]);
|
||||
actor.save_state_async();
|
||||
assert!(!dir.join("path_table.msgpack").exists());
|
||||
let saved = crate::persistence::load_hashlist_raw(&dir.join("packet_hashlist.raw"));
|
||||
assert_eq!(saved.unwrap().hashes, vec![[0xAA; 32]]);
|
||||
|
||||
std::fs::remove_file(dir.join("packet_hashlist.raw")).unwrap();
|
||||
actor.state_dirty = true;
|
||||
actor.save_state_async();
|
||||
assert!(dir.join("path_table.msgpack").exists());
|
||||
assert!(!dir.join("packet_hashlist.raw").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Pending known-destination marks are handed to the store on the 10 s cadence,
|
||||
/// without waiting for the routing tables' periodic save.
|
||||
#[test]
|
||||
@@ -1476,6 +1529,7 @@ mod async_save_tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
},
|
||||
);
|
||||
let now = crate::now_f64();
|
||||
|
||||
@@ -243,6 +243,7 @@ impl TransportActor {
|
||||
is_path_response,
|
||||
retained: a.retained,
|
||||
facts_known: a.facts_known,
|
||||
emitted: a.emitted,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1289,6 +1289,7 @@ pub(super) fn recent_from_row(row: KnownDestinationRow) -> RecentAnnounce {
|
||||
stamp_value: row.stamp_value,
|
||||
lr_cost: row.lr_cost,
|
||||
facts_known: facts.is_some(),
|
||||
emitted: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1372,6 +1373,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: Some(3.0),
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use bytes::Bytes;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::sync::{Notify, mpsc, oneshot};
|
||||
|
||||
const MAX_REGISTERED: usize = 4096;
|
||||
type Registry = Mutex<Vec<(mpsc::WeakSender<Bytes>, Weak<Shared>)>>;
|
||||
@@ -34,6 +34,7 @@ struct State {
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
ordinary: mpsc::WeakSender<Bytes>,
|
||||
offered: Notify,
|
||||
}
|
||||
struct Offer {
|
||||
owner: Option<crate::InterfaceOwner>,
|
||||
@@ -109,6 +110,7 @@ impl BackgroundAnnounceReceiver {
|
||||
active: false,
|
||||
generation: 0,
|
||||
}),
|
||||
offered: Notify::new(),
|
||||
});
|
||||
registry.push((ordinary.downgrade(), Arc::downgrade(&shared)));
|
||||
Ok(Self { shared })
|
||||
@@ -182,6 +184,13 @@ impl BackgroundAnnounceReceiver {
|
||||
pub fn has_offer(&self) -> bool {
|
||||
self.shared.state.lock().unwrap().offer.is_some()
|
||||
}
|
||||
|
||||
/// Resolve after the next offer lands. An offer made while no one waits is
|
||||
/// remembered for the next call, so a writer can check `has_offer` and then
|
||||
/// wait without missing one. One waiter per lane.
|
||||
pub async fn offered(&self) {
|
||||
self.shared.offered.notified().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(ordinary: &mpsc::Sender<Bytes>) -> Option<BackgroundAnnounceSender> {
|
||||
@@ -242,6 +251,8 @@ impl BackgroundAnnounceSender {
|
||||
generation: state.generation,
|
||||
});
|
||||
state.active = true;
|
||||
drop(state);
|
||||
self.shared.offered.notify_one();
|
||||
Some(BackgroundOfferReceipt {
|
||||
started: rx,
|
||||
cancelled,
|
||||
@@ -275,6 +286,34 @@ mod tests {
|
||||
assert!(lookup(&tx).is_none());
|
||||
assert!(BackgroundAnnounceReceiver::register(&tx).is_ok());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn offer_wakes_a_waiting_or_later_writer() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let driver = BackgroundAnnounceReceiver::register(&tx).unwrap();
|
||||
let sender = lookup(&tx).unwrap();
|
||||
let _early = sender
|
||||
.try_offer(Bytes::from_static(b"early"), 100.0, 0.0)
|
||||
.unwrap();
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
tokio::time::timeout(wait, driver.offered())
|
||||
.await
|
||||
.expect("an offer made before the wait is remembered");
|
||||
drop(driver.try_start(1.0).unwrap());
|
||||
|
||||
let waiter = tokio::spawn({
|
||||
let driver = driver.clone();
|
||||
async move { driver.offered().await }
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!waiter.is_finished());
|
||||
let _late = sender
|
||||
.try_offer(Bytes::from_static(b"late"), 100.0, 2.0)
|
||||
.unwrap();
|
||||
tokio::time::timeout(wait, waiter)
|
||||
.await
|
||||
.expect("an offer wakes a waiting writer")
|
||||
.unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn lease_bounds_offer_through_complete_write_and_expiry() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
|
||||
@@ -13,6 +13,8 @@ pub struct PacketHashlist {
|
||||
current: HashSet<[u8; 32]>,
|
||||
previous: HashSet<[u8; 32]>,
|
||||
max_size: usize,
|
||||
/// Bumped on every change to `current`, the persisted generation.
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl PacketHashlist {
|
||||
@@ -28,6 +30,7 @@ impl PacketHashlist {
|
||||
current: HashSet::new(),
|
||||
previous: HashSet::new(),
|
||||
max_size,
|
||||
revision: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +45,7 @@ impl PacketHashlist {
|
||||
return false;
|
||||
}
|
||||
self.current.insert(hash);
|
||||
self.revision += 1;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -57,7 +61,9 @@ impl PacketHashlist {
|
||||
|
||||
/// Forget a hash from both generations.
|
||||
pub fn remove(&mut self, hash: &[u8; 32]) {
|
||||
self.current.remove(hash);
|
||||
if self.current.remove(hash) {
|
||||
self.revision += 1;
|
||||
}
|
||||
self.previous.remove(hash);
|
||||
}
|
||||
|
||||
@@ -65,6 +71,7 @@ impl PacketHashlist {
|
||||
/// begin an empty current generation.
|
||||
pub fn force_rotate(&mut self) {
|
||||
self.previous = std::mem::take(&mut self.current);
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
@@ -78,6 +85,12 @@ impl PacketHashlist {
|
||||
pub fn clear(&mut self) {
|
||||
self.current.clear();
|
||||
self.previous.clear();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
/// Changes when the current generation may have changed.
|
||||
pub(crate) fn revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
|
||||
/// Snapshot the current generation in unspecified order for persistence.
|
||||
@@ -109,6 +122,7 @@ impl PacketHashlist {
|
||||
pub fn load_from(&mut self, hashes: Vec<[u8; 32]>) {
|
||||
self.current = hashes.into_iter().collect();
|
||||
self.previous.clear();
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1381,7 +1381,7 @@ pub struct LinkDistributionRpcEntry {
|
||||
|
||||
/// Snapshot of a cached route. Times are Unix seconds; returned interface
|
||||
/// metadata can use fallback values if the interface is no longer registered.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PathTableRpcEntry {
|
||||
pub hash: [u8; 16],
|
||||
@@ -1618,6 +1618,10 @@ pub struct AnnounceRpcEntry {
|
||||
/// `hops`, `name_hash`, and `is_path_response` are then unknown, and hold
|
||||
/// zero and `false` only as placeholders.
|
||||
pub facts_known: bool,
|
||||
/// Unix seconds the announcer stamped into the cached announce's random
|
||||
/// hash. A copy of an older announce accepted late carries its own, older
|
||||
/// time; `None` for an entry restored from storage.
|
||||
pub emitted: Option<u64>,
|
||||
}
|
||||
|
||||
/// Identity-bearing metadata returned by [`TransportQuery::RecallDestination`].
|
||||
|
||||
@@ -10,11 +10,12 @@
|
||||
//! whole file and have no size limit; decoded metadata still needs validation
|
||||
//! before use. Loading a route does not establish that its peer is reachable.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::{BufReader, Read};
|
||||
use std::path::Path;
|
||||
|
||||
use rmpv::Value;
|
||||
use serde::ser::{SerializeSeq, SerializeTuple, Serializer};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::constants::PERSIST_RANDOM_BLOBS;
|
||||
@@ -75,43 +76,127 @@ pub fn save_path_table(
|
||||
interface_names: &HashMap<u64, String>,
|
||||
path: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
let mut entries = Vec::new();
|
||||
for (hash, entry) in table.iter() {
|
||||
let interface_name = interface_names.get(&entry.interface_id).cloned();
|
||||
// Skip entries whose interface has already been deregistered — we
|
||||
// can't restore them safely (no name → no remap target on load).
|
||||
if interface_name.is_none() {
|
||||
continue;
|
||||
}
|
||||
let interface_hash = interface_name
|
||||
.as_deref()
|
||||
.map(interface_hash_from_name)
|
||||
.map(|h| h.to_vec());
|
||||
entries.push(PersistedPathEntry {
|
||||
destination_hash: hash.to_vec(),
|
||||
timestamp: entry.timestamp,
|
||||
next_hop: entry.next_hop.map(|h| h.to_vec()),
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
random_blobs: entry
|
||||
.blobs_for_persist()
|
||||
.iter()
|
||||
.map(|b| b.to_vec())
|
||||
.collect(),
|
||||
interface_id: entry.interface_id,
|
||||
interface_name,
|
||||
interface_hash,
|
||||
packet_hash: entry.packet_hash.map(|h| h.to_vec()),
|
||||
used: Some(entry.used),
|
||||
});
|
||||
atomic_write_bytes(
|
||||
path,
|
||||
&encode_path_table(table, &interface_keys(interface_names))?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Interface name and name hash by interface id, hashed once per save.
|
||||
pub(crate) type InterfaceKeys<'a> = HashMap<u64, (&'a str, [u8; 32])>;
|
||||
|
||||
pub(crate) fn interface_keys(names: &HashMap<u64, String>) -> InterfaceKeys<'_> {
|
||||
names
|
||||
.iter()
|
||||
.map(|(&id, name)| (id, (name.as_str(), interface_hash_from_name(name))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, PersistenceError> {
|
||||
rmp_serde::to_vec(value).map_err(|e| PersistenceError::Serialize(e.to_string()))
|
||||
}
|
||||
|
||||
/// msgpack bin, as `Value::Binary` encodes.
|
||||
struct Bin<'a>(&'a [u8]);
|
||||
|
||||
impl Serialize for Bin<'_> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_bytes(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
let persisted = PersistedPathTable {
|
||||
entries,
|
||||
/// The newest `PERSIST_RANDOM_BLOBS` blobs, or all of them, as `Vec<Vec<u8>>`
|
||||
/// (byte arrays) or, with `bin`, as `Value::Binary` rows.
|
||||
struct Blobs<'a> {
|
||||
blobs: &'a VecDeque<[u8; 10]>,
|
||||
newest_only: bool,
|
||||
bin: bool,
|
||||
}
|
||||
|
||||
impl Serialize for Blobs<'_> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
let skip = if self.newest_only {
|
||||
self.blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let blobs = self.blobs.iter().skip(skip);
|
||||
if self.bin {
|
||||
s.collect_seq(blobs.map(|b| Bin(b)))
|
||||
} else {
|
||||
s.collect_seq(blobs.map(|b| b.as_slice()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed [`PersistedPathEntry`]; serializes to the same bytes.
|
||||
#[derive(Serialize)]
|
||||
struct PathEntryRef<'a> {
|
||||
destination_hash: &'a [u8],
|
||||
timestamp: f64,
|
||||
next_hop: Option<&'a [u8]>,
|
||||
hops: u8,
|
||||
expires: f64,
|
||||
random_blobs: Blobs<'a>,
|
||||
interface_id: u64,
|
||||
interface_name: Option<&'a str>,
|
||||
interface_hash: Option<&'a [u8]>,
|
||||
packet_hash: Option<&'a [u8]>,
|
||||
used: Option<f64>,
|
||||
}
|
||||
|
||||
struct PathRows<'a> {
|
||||
table: &'a PathTable,
|
||||
keys: &'a InterfaceKeys<'a>,
|
||||
}
|
||||
|
||||
impl Serialize for PathRows<'_> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
let rows = || {
|
||||
self.table.iter().filter_map(|(hash, entry)| {
|
||||
let (name, name_hash) = self.keys.get(&entry.interface_id)?;
|
||||
Some(PathEntryRef {
|
||||
destination_hash: hash.as_bytes(),
|
||||
timestamp: entry.timestamp,
|
||||
next_hop: entry.next_hop.as_ref().map(|h| h.as_slice()),
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
random_blobs: Blobs {
|
||||
blobs: &entry.random_blobs,
|
||||
newest_only: true,
|
||||
bin: false,
|
||||
},
|
||||
interface_id: entry.interface_id,
|
||||
interface_name: Some(name),
|
||||
interface_hash: Some(name_hash),
|
||||
packet_hash: entry.packet_hash.as_ref().map(|h| h.as_slice()),
|
||||
used: Some(entry.used),
|
||||
})
|
||||
})
|
||||
};
|
||||
let mut seq = s.serialize_seq(Some(rows().count()))?;
|
||||
for row in rows() {
|
||||
seq.serialize_element(&row)?;
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PathTableRef<'a> {
|
||||
entries: PathRows<'a>,
|
||||
version: u32,
|
||||
}
|
||||
|
||||
/// [`save_path_table`]'s file bytes, without an owned copy of the table.
|
||||
pub(crate) fn encode_path_table(
|
||||
table: &PathTable,
|
||||
keys: &InterfaceKeys<'_>,
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
encode(&PathTableRef {
|
||||
entries: PathRows { table, keys },
|
||||
version: PersistedPathTable::CURRENT_VERSION,
|
||||
};
|
||||
|
||||
atomic_write(path, &persisted)
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode a Rust path snapshot with a supported version (1 through 4).
|
||||
@@ -191,37 +276,83 @@ pub fn save_python_destination_table(
|
||||
interface_names: &HashMap<u64, String>,
|
||||
path: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
let mut entries = Vec::new();
|
||||
for (hash, entry) in table.iter() {
|
||||
let Some(interface_name) = interface_names.get(&entry.interface_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(packet_hash) = entry.packet_hash else {
|
||||
continue;
|
||||
};
|
||||
let received_from = entry.next_hop.unwrap_or(*hash.as_bytes());
|
||||
let random_blobs = entry
|
||||
.random_blobs
|
||||
.iter()
|
||||
.map(|b| Value::Binary(b.to_vec()))
|
||||
.collect();
|
||||
entries.push(Value::Array(vec![
|
||||
Value::Binary(hash.to_vec()),
|
||||
Value::F64(entry.timestamp),
|
||||
Value::Binary(received_from.to_vec()),
|
||||
Value::Integer((entry.hops as u64).into()),
|
||||
Value::F64(entry.expires),
|
||||
Value::Array(random_blobs),
|
||||
Value::Binary(interface_hash_from_name(interface_name).to_vec()),
|
||||
Value::Binary(packet_hash.to_vec()),
|
||||
Value::F64(entry.used),
|
||||
]));
|
||||
}
|
||||
atomic_write_bytes(
|
||||
path,
|
||||
&encode_python_destination_table(table, &interface_keys(interface_names))?,
|
||||
)
|
||||
}
|
||||
|
||||
let mut serialized = Vec::new();
|
||||
rmpv::encode::write_value(&mut serialized, &Value::Array(entries))
|
||||
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
|
||||
atomic_write_bytes(path, &serialized)
|
||||
/// One Python `destination_table` row (Transport.py).
|
||||
struct PythonPathRow<'a> {
|
||||
destination_hash: &'a [u8],
|
||||
timestamp: f64,
|
||||
received_from: &'a [u8],
|
||||
hops: u8,
|
||||
expires: f64,
|
||||
random_blobs: Blobs<'a>,
|
||||
interface_hash: &'a [u8],
|
||||
packet_hash: &'a [u8],
|
||||
used: f64,
|
||||
}
|
||||
|
||||
impl Serialize for PythonPathRow<'_> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
let mut row = s.serialize_tuple(9)?;
|
||||
row.serialize_element(&Bin(self.destination_hash))?;
|
||||
row.serialize_element(&self.timestamp)?;
|
||||
row.serialize_element(&Bin(self.received_from))?;
|
||||
row.serialize_element(&u64::from(self.hops))?;
|
||||
row.serialize_element(&self.expires)?;
|
||||
row.serialize_element(&self.random_blobs)?;
|
||||
row.serialize_element(&Bin(self.interface_hash))?;
|
||||
row.serialize_element(&Bin(self.packet_hash))?;
|
||||
row.serialize_element(&self.used)?;
|
||||
row.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct Rows<F>(F);
|
||||
|
||||
impl<'a, F, I> Serialize for Rows<F>
|
||||
where
|
||||
F: Fn() -> I,
|
||||
I: Iterator<Item = PythonPathRow<'a>>,
|
||||
{
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
let mut seq = s.serialize_seq(Some((self.0)().count()))?;
|
||||
for row in (self.0)() {
|
||||
seq.serialize_element(&row)?;
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`save_python_destination_table`]'s file bytes, without a `Value` tree.
|
||||
pub(crate) fn encode_python_destination_table(
|
||||
table: &PathTable,
|
||||
keys: &InterfaceKeys<'_>,
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
encode(&Rows(|| {
|
||||
table.iter().filter_map(|(hash, entry)| {
|
||||
let (_, name_hash) = keys.get(&entry.interface_id)?;
|
||||
let packet_hash = entry.packet_hash.as_ref()?;
|
||||
Some(PythonPathRow {
|
||||
destination_hash: hash.as_bytes(),
|
||||
timestamp: entry.timestamp,
|
||||
received_from: entry.next_hop.as_ref().unwrap_or(hash.as_bytes()),
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
random_blobs: Blobs {
|
||||
blobs: &entry.random_blobs,
|
||||
newest_only: false,
|
||||
bin: true,
|
||||
},
|
||||
interface_hash: name_hash,
|
||||
packet_hash,
|
||||
used: entry.used,
|
||||
})
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/// Decode Python-compatible destination rows from a local file.
|
||||
@@ -395,12 +526,22 @@ pub fn save_python_tunnel_table(
|
||||
interface_names: &HashMap<u64, String>,
|
||||
path: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
atomic_write_bytes(
|
||||
path,
|
||||
&encode_python_tunnel_table(table, &interface_keys(interface_names))?,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn encode_python_tunnel_table(
|
||||
table: &crate::tunnel::TunnelTable,
|
||||
keys: &InterfaceKeys<'_>,
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
let mut tunnel_values = Vec::new();
|
||||
for (_, tunnel) in table.iter() {
|
||||
let interface_hash = tunnel
|
||||
.interface_id
|
||||
.and_then(|id| interface_names.get(&id))
|
||||
.map(|name| Value::Binary(interface_hash_from_name(name).to_vec()))
|
||||
.and_then(|id| keys.get(&id))
|
||||
.map(|(_, hash)| Value::Binary(hash.to_vec()))
|
||||
.unwrap_or(Value::Nil);
|
||||
|
||||
let mut path_values = Vec::new();
|
||||
@@ -440,10 +581,7 @@ pub fn save_python_tunnel_table(
|
||||
]));
|
||||
}
|
||||
|
||||
let mut serialized = Vec::new();
|
||||
rmpv::encode::write_value(&mut serialized, &Value::Array(tunnel_values))
|
||||
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
|
||||
atomic_write_bytes(path, &serialized)
|
||||
encode_value(&Value::Array(tunnel_values))
|
||||
}
|
||||
|
||||
/// Decode a local Python-compatible tunnel table. Malformed tunnel or path
|
||||
@@ -614,14 +752,10 @@ pub fn save_hashlist_legacy(
|
||||
}
|
||||
|
||||
/// Replace `path` with the supplied hashes concatenated as raw 32-byte records.
|
||||
/// Input order and duplicates are preserved. The full output is allocated in
|
||||
/// memory before writing through the shared atomic-file helper.
|
||||
/// Input order and duplicates are preserved. The records are written in place
|
||||
/// through the shared atomic-file helper.
|
||||
pub fn save_raw_hashes(hashes: &[[u8; 32]], path: &Path) -> Result<(), PersistenceError> {
|
||||
let mut serialized = Vec::with_capacity(hashes.len().saturating_mul(32));
|
||||
for hash in hashes {
|
||||
serialized.extend_from_slice(hash);
|
||||
}
|
||||
atomic_write_bytes(path, &serialized)
|
||||
atomic_write_bytes(path, hashes.as_flattened())
|
||||
}
|
||||
|
||||
/// Load raw 32-byte hash records through a 64 KiB reader buffer.
|
||||
@@ -712,13 +846,14 @@ pub fn load_hashlist(path: &Path) -> Result<Vec<[u8; 32]>, PersistenceError> {
|
||||
|
||||
/// Write to a sibling `.tmp` file and rename on top of the target so a crash
|
||||
/// mid-write cannot leave a half-written snapshot on disk.
|
||||
#[cfg(test)]
|
||||
fn atomic_write<T: Serialize>(path: &Path, data: &T) -> Result<(), PersistenceError> {
|
||||
let serialized =
|
||||
rmp_serde::to_vec(data).map_err(|e| PersistenceError::Serialize(e.to_string()))?;
|
||||
atomic_write_bytes(path, &serialized)
|
||||
}
|
||||
|
||||
fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> {
|
||||
pub(crate) fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> {
|
||||
// Single canonical atomic-write implementation (fsync + rename + dir
|
||||
// sync) lives in rns-identity; transport tables share it (AF-2026-04.2).
|
||||
rns_identity::persistence::atomic_write(path, serialized).map_err(PersistenceError::Io)
|
||||
@@ -753,6 +888,12 @@ pub fn save_blackhole_table(
|
||||
table: &crate::blackhole::BlackholeTable,
|
||||
path: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
atomic_write_bytes(path, &encode_blackhole_table(table)?)
|
||||
}
|
||||
|
||||
pub(crate) fn encode_blackhole_table(
|
||||
table: &crate::blackhole::BlackholeTable,
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
let mut entries = Vec::new();
|
||||
for (hash, entry) in table.iter_entries() {
|
||||
if entry.source.is_some() {
|
||||
@@ -767,12 +908,10 @@ pub fn save_blackhole_table(
|
||||
});
|
||||
}
|
||||
|
||||
let persisted = PersistedBlackholeTable {
|
||||
encode(&PersistedBlackholeTable {
|
||||
entries,
|
||||
version: PersistedBlackholeTable::CURRENT_VERSION,
|
||||
};
|
||||
|
||||
atomic_write(path, &persisted)
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode a version-1 or version-2 Rust blackhole snapshot. Stored hash lengths,
|
||||
@@ -848,8 +987,25 @@ pub fn save_local_blackhole_file(
|
||||
table: &crate::blackhole::BlackholeTable,
|
||||
local_identity_hash: [u8; 16],
|
||||
blackhole_dir: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
write_local_blackhole_file(
|
||||
&encode_local_blackhole_file(table, local_identity_hash)?,
|
||||
blackhole_dir,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn write_local_blackhole_file(
|
||||
bytes: &[u8],
|
||||
blackhole_dir: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
std::fs::create_dir_all(blackhole_dir).map_err(PersistenceError::Io)?;
|
||||
atomic_write_bytes(&blackhole_dir.join("local"), bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn encode_local_blackhole_file(
|
||||
table: &crate::blackhole::BlackholeTable,
|
||||
local_identity_hash: [u8; 16],
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
let local_entries = table
|
||||
.iter_entries()
|
||||
.filter(|(_, entry)| {
|
||||
@@ -865,7 +1021,7 @@ pub fn save_local_blackhole_file(
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
write_value_file(&blackhole_dir.join("local"), &Value::Map(local_entries))
|
||||
encode_value(&Value::Map(local_entries))
|
||||
}
|
||||
|
||||
/// Store a publisher's fetched `/list` reply as `blackhole_dir/<publisher>`,
|
||||
@@ -1005,11 +1161,15 @@ fn blackhole_entry_value(source: [u8; 16], until: Option<f64>, reason: Option<&s
|
||||
])
|
||||
}
|
||||
|
||||
fn write_value_file(path: &Path, value: &Value) -> Result<(), PersistenceError> {
|
||||
fn encode_value(value: &Value) -> Result<Vec<u8>, PersistenceError> {
|
||||
let mut serialized = Vec::new();
|
||||
rmpv::encode::write_value(&mut serialized, value)
|
||||
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
|
||||
atomic_write_bytes(path, &serialized)
|
||||
Ok(serialized)
|
||||
}
|
||||
|
||||
fn write_value_file(path: &Path, value: &Value) -> Result<(), PersistenceError> {
|
||||
atomic_write_bytes(path, &encode_value(value)?)
|
||||
}
|
||||
|
||||
fn map_get<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a Value> {
|
||||
@@ -1266,13 +1426,20 @@ pub fn save_tunnel_table(
|
||||
interface_names: &HashMap<u64, String>,
|
||||
path: &Path,
|
||||
) -> Result<(), PersistenceError> {
|
||||
atomic_write_bytes(
|
||||
path,
|
||||
&encode_tunnel_table(table, &interface_keys(interface_names))?,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn encode_tunnel_table(
|
||||
table: &crate::tunnel::TunnelTable,
|
||||
keys: &InterfaceKeys<'_>,
|
||||
) -> Result<Vec<u8>, PersistenceError> {
|
||||
let entries: Vec<PersistedTunnelEntry> = table
|
||||
.iter()
|
||||
.map(|(_, entry)| {
|
||||
let interface_name = entry
|
||||
.interface_id
|
||||
.and_then(|id| interface_names.get(&id))
|
||||
.cloned();
|
||||
let interface = entry.interface_id.and_then(|id| keys.get(&id));
|
||||
let paths: Vec<PersistedTunnelPath> = entry
|
||||
.tunnel_paths
|
||||
.iter()
|
||||
@@ -1299,20 +1466,16 @@ pub fn save_tunnel_table(
|
||||
interface_id: entry.interface_id.unwrap_or_default(),
|
||||
expires: entry.expires,
|
||||
paths,
|
||||
interface_hash: interface_name
|
||||
.as_deref()
|
||||
.map(|name| interface_hash_from_name(name).to_vec()),
|
||||
interface_name,
|
||||
interface_hash: interface.map(|(_, hash)| hash.to_vec()),
|
||||
interface_name: interface.map(|(name, _)| name.to_string()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let persisted = PersistedTunnelTable {
|
||||
encode(&PersistedTunnelTable {
|
||||
entries,
|
||||
version: PersistedTunnelTable::CURRENT_VERSION,
|
||||
};
|
||||
|
||||
atomic_write(path, &persisted)
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode a supported Rust tunnel snapshot (versions 1 through 3). This returns
|
||||
@@ -1364,6 +1527,101 @@ mod tests {
|
||||
dir
|
||||
}
|
||||
|
||||
fn varied_path_table() -> (PathTable, HashMap<u64, String>) {
|
||||
let mut table = PathTable::new();
|
||||
for i in 0..40u8 {
|
||||
let mut entry = PathEntry::new(
|
||||
(i % 3 != 0).then_some([i; 16]),
|
||||
i % 9,
|
||||
u64::from(i % 4),
|
||||
InterfaceMode::Full,
|
||||
);
|
||||
entry.timestamp = 1_700_000_000.25 + f64::from(i);
|
||||
entry.expires = entry.timestamp + 604_800.5;
|
||||
entry.used = if i % 2 == 0 {
|
||||
0.0
|
||||
} else {
|
||||
entry.timestamp + 3.5
|
||||
};
|
||||
entry.packet_hash = (i % 5 != 0).then_some([i.wrapping_mul(7); 32]);
|
||||
for b in 0..u16::from(i) {
|
||||
entry.add_random_blob([(b % 251) as u8; 10]);
|
||||
}
|
||||
table.insert([i.wrapping_add(100); 16], entry);
|
||||
}
|
||||
let names = (0..3u64)
|
||||
.map(|id| (id, format!("Interface[{id}]")))
|
||||
.collect();
|
||||
(table, names)
|
||||
}
|
||||
|
||||
/// The borrowed encoders write the bytes the owned-copy encoders did.
|
||||
#[test]
|
||||
fn path_table_encoders_match_owned_reference() {
|
||||
let (table, names) = varied_path_table();
|
||||
let keys = interface_keys(&names);
|
||||
|
||||
let entries: Vec<PersistedPathEntry> = table
|
||||
.iter()
|
||||
.filter_map(|(hash, entry)| {
|
||||
let name = names.get(&entry.interface_id)?;
|
||||
Some(PersistedPathEntry {
|
||||
destination_hash: hash.to_vec(),
|
||||
timestamp: entry.timestamp,
|
||||
next_hop: entry.next_hop.map(|h| h.to_vec()),
|
||||
hops: entry.hops,
|
||||
expires: entry.expires,
|
||||
random_blobs: entry
|
||||
.blobs_for_persist()
|
||||
.iter()
|
||||
.map(|b| b.to_vec())
|
||||
.collect(),
|
||||
interface_id: entry.interface_id,
|
||||
interface_name: Some(name.clone()),
|
||||
interface_hash: Some(interface_hash_from_name(name).to_vec()),
|
||||
packet_hash: entry.packet_hash.map(|h| h.to_vec()),
|
||||
used: Some(entry.used),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let reference = rmp_serde::to_vec(&PersistedPathTable {
|
||||
entries,
|
||||
version: PersistedPathTable::CURRENT_VERSION,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(encode_path_table(&table, &keys).unwrap(), reference);
|
||||
|
||||
let rows: Vec<Value> = table
|
||||
.iter()
|
||||
.filter_map(|(hash, entry)| {
|
||||
let name = names.get(&entry.interface_id)?;
|
||||
let packet_hash = entry.packet_hash?;
|
||||
Some(Value::Array(vec![
|
||||
Value::Binary(hash.to_vec()),
|
||||
Value::F64(entry.timestamp),
|
||||
Value::Binary(entry.next_hop.unwrap_or(*hash.as_bytes()).to_vec()),
|
||||
Value::Integer((entry.hops as u64).into()),
|
||||
Value::F64(entry.expires),
|
||||
Value::Array(
|
||||
entry
|
||||
.random_blobs
|
||||
.iter()
|
||||
.map(|b| Value::Binary(b.to_vec()))
|
||||
.collect(),
|
||||
),
|
||||
Value::Binary(interface_hash_from_name(name).to_vec()),
|
||||
Value::Binary(packet_hash.to_vec()),
|
||||
Value::F64(entry.used),
|
||||
]))
|
||||
})
|
||||
.collect();
|
||||
assert!(rows.len() > 10);
|
||||
assert_eq!(
|
||||
encode_python_destination_table(&table, &keys).unwrap(),
|
||||
encode_value(&Value::Array(rows)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_save_load_path_table() {
|
||||
let mut table = PathTable::new();
|
||||
@@ -2038,6 +2296,7 @@ mod tests {
|
||||
stamp_value: 0.0,
|
||||
lr_cost: None,
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
}];
|
||||
|
||||
let dir = std::env::temp_dir().join("reticulum_rs_test_announce_persist");
|
||||
@@ -2078,6 +2337,7 @@ mod tests {
|
||||
stamp_value: 25.5,
|
||||
lr_cost: Some(12.5),
|
||||
facts_known: true,
|
||||
emitted: None,
|
||||
};
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("rns_announce_stamp_fields_{}", std::process::id()));
|
||||
|
||||
@@ -4,7 +4,7 @@ use alloc::vec::Vec;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::constants::MTU;
|
||||
use crate::hash::{packet_hash, truncated_packet_hash};
|
||||
use crate::hash::packet_hash_pair;
|
||||
use crate::header::{HeaderError, PacketHeader};
|
||||
|
||||
/// Errors surfaced by [`Packet::new`] and [`Packet::from_raw`].
|
||||
@@ -63,8 +63,7 @@ impl Packet {
|
||||
return Err(PacketError::ExceedsMtu(raw.len()));
|
||||
}
|
||||
|
||||
let hash = packet_hash(&raw, header.flags.header_type);
|
||||
let trunc = truncated_packet_hash(&raw, header.flags.header_type);
|
||||
let (hash, trunc) = packet_hash_pair(&raw, header.flags.header_type);
|
||||
|
||||
Ok(Self {
|
||||
header,
|
||||
@@ -95,8 +94,7 @@ impl Packet {
|
||||
}
|
||||
|
||||
let (header, data_offset) = PacketHeader::unpack(&raw)?;
|
||||
let hash = packet_hash(&raw, header.flags.header_type);
|
||||
let trunc = truncated_packet_hash(&raw, header.flags.header_type);
|
||||
let (hash, trunc) = packet_hash_pair(&raw, header.flags.header_type);
|
||||
|
||||
Ok(Self {
|
||||
header,
|
||||
|
||||
Reference in new issue
Block a user