link: follow upstream on request replies, file responses, and deadlines

This commit is contained in:
DeFiDude committed 2026-11-10 02:16:45 -07:00
1 parent 12e3882b55
commit 52488d778d
12 files changed
+1536 -292

No files matched your search

+243 -69
View File
@@ -119,15 +119,18 @@ pub enum RequestSendMode {
Resource(Vec<u8>),
}
fn msgpack_value_from_bytes_or_binary(data: &[u8]) -> rmpv::Value {
let mut cursor = std::io::Cursor::new(data);
/// Decode exactly one complete MessagePack value, rejecting trailing bytes.
pub fn decode_single_value(packed: &[u8]) -> Option<rmpv::Value> {
let mut cursor = std::io::Cursor::new(packed);
match rmpv::decode::read_value(&mut cursor) {
Ok(value) if cursor.position() as usize == data.len() => value,
_ => rmpv::Value::Binary(data.to_vec()),
Ok(value) if cursor.position() as usize == packed.len() => Some(value),
_ => None,
}
}
fn msgpack_value_to_bytes(value: &rmpv::Value) -> Result<Vec<u8>, LinkCryptoError> {
/// Byte view of a decoded request or response value: binary and string
/// contents as-is, any other value re-encoded as MessagePack.
pub fn value_bytes_view(value: &rmpv::Value) -> Result<Vec<u8>, LinkCryptoError> {
if let Some(bytes) = value.as_slice() {
Ok(bytes.to_vec())
} else if let Some(text) = value.as_str() {
@@ -260,6 +263,16 @@ pub type LinkCallback = Box<dyn Fn(&Link) + Send + Sync>;
/// Parsed REQUEST data: `(request_id, path_hash, timestamp, payload)`.
pub type ParsedRequestData = ([u8; 16], [u8; 16], f64, Vec<u8>);
/// A parsed Link request with its data as the decoded MessagePack value.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedRequest {
/// Truncated hash of the packed request body.
pub request_id: [u8; 16],
pub path_hash: [u8; 16],
pub requested_at: f64,
pub data: rmpv::Value,
}
impl Link {
/// Create an outbound link and return `(link, request_data)` to transmit.
#[tracing::instrument(
@@ -782,13 +795,13 @@ impl Link {
self.remote_identity_pub.as_ref()
}
/// Build a REQUEST payload and return `(encrypted, request_id)`.
/// Build a REQUEST payload from pre-encoded data and return
/// `(encrypted, request_id)`.
///
/// Plaintext is msgpack `[timestamp_f64, sha256_trunc(path), data]`. Send with
/// context REQUEST (0x09). The initial ID hashes the plaintext body. For an
/// inline packet, the owner must replace it with that packet's truncated
/// hash via [`Self::update_pending_request_id`]. Resource requests retain
/// the body hash. This method does not enforce the MDU or send data.
/// `data` is one already-encoded MessagePack value placed in the request
/// as-is; anything else is refused. `None` sends nil. Use
/// [`Self::request_value`] to pass a value, e.g. `Value::Binary` for bytes.
/// See [`Self::request_value`] for request ID handling.
pub fn request(
&mut self,
path: &str,
@@ -796,33 +809,25 @@ impl Link {
timeout: Duration,
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
let (packed, request_id) = self.prepare_request(path, data, timeout)?;
match self.encrypt(&packed) {
Ok(encrypted) => Ok((encrypted, request_id)),
Err(error) => {
self.discard_pending_request(&request_id);
Err(error)
}
}
self.encrypt_request(packed, request_id)
}
/// Build the plaintext MsgPack request body and register its receipt.
/// Build a REQUEST payload whose data is `data`, packed by type as
/// Link.request packs `[time.time(), path_hash, data]`.
///
/// Packet-sized callers encrypt the returned body directly. Bodies larger
/// than the Link MDU are passed to Resource with the returned request ID.
/// A complete MessagePack value in `data` is embedded as that value; other
/// bytes become a binary field. `None` becomes nil. Inline packet callers
/// replace the initial body-hash ID after packing the packet, as described
/// on [`Self::request`].
pub fn prepare_request(
/// Send with context REQUEST (0x09). The initial ID hashes the plaintext
/// body. For an inline packet, the owner must replace it with that
/// packet's truncated hash via [`Self::update_pending_request_id`].
/// Resource requests retain the body hash. This method does not enforce
/// the MDU or send data.
pub fn request_value(
&mut self,
path: &str,
data: Option<&[u8]>,
data: &rmpv::Value,
timeout: Duration,
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
let data_value = data
.map(msgpack_value_from_bytes_or_binary)
.unwrap_or(rmpv::Value::Nil);
self.prepare_request_value(path, data_value, timeout)
let (packed, request_id) = self.prepare_request_value(path, data, timeout)?;
self.encrypt_request(packed, request_id)
}
/// Build a REQUEST payload with a MsgPack string body.
@@ -835,8 +840,14 @@ impl Link {
data: &str,
timeout: Duration,
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
let (packed, request_id) =
self.prepare_request_value(path, rmpv::Value::String(data.into()), timeout)?;
self.request_value(path, &rmpv::Value::String(data.into()), timeout)
}
fn encrypt_request(
&mut self,
packed: Vec<u8>,
request_id: [u8; 16],
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
match self.encrypt(&packed) {
Ok(encrypted) => Ok((encrypted, request_id)),
Err(error) => {
@@ -846,10 +857,32 @@ impl Link {
}
}
fn prepare_request_value(
/// Build the plaintext MsgPack request body from one already-encoded
/// MessagePack value (`None` for nil) and register its receipt. Refuses
/// `data` unless it is exactly one complete value.
pub fn prepare_request(
&mut self,
path: &str,
data_value: rmpv::Value,
data: Option<&[u8]>,
timeout: Duration,
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
let value = match data {
None => rmpv::Value::Nil,
Some(packed) => decode_single_value(packed).ok_or(LinkCryptoError::EncryptionFailed)?,
};
self.prepare_request_value(path, &value, timeout)
}
/// Build the plaintext MsgPack request body and register its receipt.
///
/// Packet-sized callers encrypt the returned body directly. Bodies larger
/// than the Link MDU are passed to Resource with the returned request ID.
/// Inline packet callers replace the initial body-hash ID after packing
/// the packet, as described on [`Self::request_value`].
pub fn prepare_request_value(
&mut self,
path: &str,
data: &rmpv::Value,
timeout: Duration,
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
if self.state != LinkState::Active {
@@ -865,7 +898,7 @@ impl Link {
let array = rmpv::Value::Array(vec![
rmpv::Value::F64(timestamp),
rmpv::Value::Binary(path_hash.to_vec()),
data_value,
data.clone(),
]);
let mut packed = Vec::new();
rmpv::encode::write_value(&mut packed, &array)
@@ -909,6 +942,20 @@ impl Link {
true
}
/// Move a pending request to `Receiving` once its response Resource is
/// accepted; the request deadline no longer applies after that. Returns
/// `false` when no pending receipt matches.
pub fn mark_request_receiving(&mut self, request_id: &[u8; 16]) -> bool {
let Some(receipt) = self
.pending_requests
.iter_mut()
.find(|receipt| receipt.request_id[..16] == request_id[..])
else {
return false;
};
receipt.mark_receiving()
}
/// Fail and remove a pending request by its truncated request ID.
pub fn fail_pending_request(&mut self, request_id: &[u8; 16]) -> bool {
let Some(receipt) = self
@@ -969,6 +1016,19 @@ impl Link {
/// not authorize a handler or validate timestamp freshness. Binary/string
/// payloads become raw bytes; other MessagePack values are re-encoded.
pub fn parse_request(plaintext: &[u8]) -> Result<ParsedRequestData, LinkCryptoError> {
let request = Self::parse_request_value(plaintext)?;
let data = value_bytes_view(&request.data)?;
Ok((
request.request_id,
request.path_hash,
request.requested_at,
data,
))
}
/// As [`Self::parse_request`], keeping the request data as its decoded
/// value so bytes and structured request data stay distinct.
pub fn parse_request_value(plaintext: &[u8]) -> Result<ParsedRequest, LinkCryptoError> {
// request_id = SHA-256(packed_request)[:16]
let request_id = truncated_hash(plaintext);
@@ -992,41 +1052,76 @@ impl Link {
let mut path_hash = [0u8; 16];
path_hash.copy_from_slice(path_hash_bytes);
let data = msgpack_value_to_bytes(&array[2])?;
Ok((request_id, path_hash, timestamp, data))
Ok(ParsedRequest {
request_id,
path_hash,
requested_at: timestamp,
data: array[2].clone(),
})
}
/// Build a RESPONSE payload: `encrypt(msgpack([request_id, response_data]))`.
///
/// Send with context RESPONSE (0x0A).
/// Build a RESPONSE payload: `encrypt(msgpack([request_id, response]))`,
/// with `response` one already-encoded MessagePack value (refused
/// otherwise). Send with context RESPONSE (0x0A).
pub fn create_response(
&self,
request_id: &[u8; 16],
response_data: &[u8],
response: &[u8],
) -> Result<Vec<u8>, LinkCryptoError> {
let packed = Self::pack_response(request_id, response_data)?;
let packed = Self::pack_response(request_id, response)?;
self.encrypt(&packed)
}
/// Build plaintext msgpack `[request_id, response_data]` for a Link
/// response packet or response resource. A complete MessagePack value in
/// `response_data` is embedded as that value; other bytes become binary.
pub fn pack_response(
/// As [`Self::create_response`], packing `response` by type.
pub fn create_response_value(
&self,
request_id: &[u8; 16],
response_data: &[u8],
response: &rmpv::Value,
) -> Result<Vec<u8>, LinkCryptoError> {
let packed = Self::pack_response_value(request_id, response)?;
self.encrypt(&packed)
}
/// Build plaintext msgpack `[request_id, response]` for a Link response
/// packet or response resource, as Link.handle_request packs a handler's
/// return value. Use `Value::Binary` for a bytes response.
pub fn pack_response_value(
request_id: &[u8; 16],
response: &rmpv::Value,
) -> Result<Vec<u8>, LinkCryptoError> {
let response_value = msgpack_value_from_bytes_or_binary(response_data);
let array = rmpv::Value::Array(vec![
rmpv::Value::Binary(request_id.to_vec()),
response_value,
]);
let mut packed = Vec::new();
rmpv::encode::write_value(&mut packed, &array)
Self::write_response_prefix(&mut packed, request_id)?;
rmpv::encode::write_value(&mut packed, response)
.map_err(|_| LinkCryptoError::EncryptionFailed)?;
Ok(packed)
}
/// As [`Self::pack_response_value`], with the response supplied as one
/// already-encoded MessagePack value. Fails unless `packed_value` is
/// exactly one complete value.
pub fn pack_response(
request_id: &[u8; 16],
packed_value: &[u8],
) -> Result<Vec<u8>, LinkCryptoError> {
if decode_single_value(packed_value).is_none() {
return Err(LinkCryptoError::EncryptionFailed);
}
let mut packed = Vec::with_capacity(19 + packed_value.len());
Self::write_response_prefix(&mut packed, request_id)?;
packed.extend_from_slice(packed_value);
Ok(packed)
}
fn write_response_prefix(
packed: &mut Vec<u8>,
request_id: &[u8; 16],
) -> Result<(), LinkCryptoError> {
// fixarray(2) header, then the request id as bin.
packed.push(0x92);
rmpv::encode::write_value(packed, &rmpv::Value::Binary(request_id.to_vec()))
.map_err(|_| LinkCryptoError::EncryptionFailed)
}
/// Decrypt a RESPONSE payload, deliver it to the matching receipt, and return
/// `(request_id, response_data)`. A well-formed response is returned even
/// when no pending receipt matches; successful parsing is not proof that a
@@ -1060,10 +1155,21 @@ impl Link {
pub fn parse_response_plaintext(
plaintext: &[u8],
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
let (request_id, response) = Self::parse_response_value(plaintext)?;
Ok((request_id, value_bytes_view(&response)?))
}
/// Parse plaintext MsgPack `[request_id, response]`, keeping the response
/// as its decoded value so bytes and structured responses stay distinct.
pub fn parse_response_value(
plaintext: &[u8],
) -> Result<([u8; 16], rmpv::Value), LinkCryptoError> {
let value = rmpv::decode::read_value(&mut &plaintext[..])
.map_err(|_| LinkCryptoError::DecryptionFailed)?;
let array = value.as_array().ok_or(LinkCryptoError::DecryptionFailed)?;
let rmpv::Value::Array(mut array) = value else {
return Err(LinkCryptoError::DecryptionFailed);
};
if array.len() < 2 {
return Err(LinkCryptoError::DecryptionFailed);
}
@@ -1077,9 +1183,9 @@ impl Link {
let mut request_id = [0u8; 16];
request_id.copy_from_slice(id_bytes);
let response_data = msgpack_value_to_bytes(&array[1])?;
let response = array.swap_remove(1);
Ok((request_id, response_data))
Ok((request_id, response))
}
/// Deliver already-decoded response bytes to a pending request.
@@ -2685,7 +2791,11 @@ mod tests {
let (mut initiator, responder, _) = make_active_link();
let (request_data, request_id) = initiator
.request("test.path", Some(b"request data"), Duration::from_secs(10))
.request_value(
"test.path",
&rmpv::Value::Binary(b"request data".to_vec()),
Duration::from_secs(10),
)
.unwrap();
assert!(!initiator.pending_requests.is_empty());
@@ -2698,7 +2808,7 @@ mod tests {
assert_eq!(path_hash, expected_path_hash);
let response_data = responder
.create_response(&request_id, b"response data")
.create_response_value(&request_id, &rmpv::Value::Binary(b"response data".to_vec()))
.unwrap();
let (resp_id, resp_data) = initiator.handle_response(&response_data).unwrap();
@@ -2714,9 +2824,9 @@ mod tests {
let (mut initiator, responder, _) = make_active_link();
let (encrypted, request_id) = initiator
.request(
.request_value(
"resource.path",
Some(b"resource request data"),
&rmpv::Value::Binary(b"resource request data".to_vec()),
Duration::from_secs(10),
)
.unwrap();
@@ -2782,13 +2892,11 @@ mod tests {
let (mut initiator, responder, _) = make_active_link();
let request_body = Value::Array(vec![Value::Nil, Value::Nil]);
let mut request_body_bytes = Vec::new();
rmpv::encode::write_value(&mut request_body_bytes, &request_body).unwrap();
let (request_data, request_id) = initiator
.request(
.request_value(
"lxmf.propagation.get",
Some(&request_body_bytes),
&request_body,
Duration::from_secs(10),
)
.unwrap();
@@ -2799,11 +2907,9 @@ mod tests {
assert_eq!(decoded_request, request_body);
let response_body = Value::Array(vec![Value::Binary(vec![0xAA; 32])]);
let mut response_body_bytes = Vec::new();
rmpv::encode::write_value(&mut response_body_bytes, &response_body).unwrap();
let response_data = responder
.create_response(&request_id, &response_body_bytes)
.create_response_value(&request_id, &response_body)
.unwrap();
let (resp_id, resp_data) = initiator.handle_response(&response_data).unwrap();
@@ -2813,6 +2919,74 @@ mod tests {
assert!(initiator.pending_requests.is_empty());
}
#[test]
fn bytes_response_is_packed_as_bin_even_when_it_looks_like_msgpack() {
let request_id: [u8; 16] = core::array::from_fn(|i| i as u8);
let packed =
Link::pack_response_value(&request_id, &rmpv::Value::Binary(vec![0x0a])).unwrap();
assert_eq!(
hex::encode(packed),
"92c410000102030405060708090a0b0c0d0e0fc4010a"
);
}
#[test]
fn packed_response_value_is_embedded_and_validated() {
let request_id: [u8; 16] = core::array::from_fn(|i| i as u8);
let packed = Link::pack_response(&request_id, &[0xcc, 0xf0]).unwrap();
assert_eq!(
hex::encode(&packed),
"92c410000102030405060708090a0b0c0d0e0fccf0"
);
assert_eq!(
Link::parse_response_value(&packed).unwrap().1,
rmpv::Value::from(240u8)
);
assert!(Link::pack_response(&request_id, &[0x81]).is_err());
assert!(Link::pack_response(&request_id, &[0xc3, 0xc3]).is_err());
assert!(Link::pack_response(&request_id, &[]).is_err());
}
#[test]
fn bytes_request_data_reaches_parser_as_binary() {
let (mut initiator, responder, _) = make_active_link();
let (encrypted, _) = initiator
.request_value(
"p",
&rmpv::Value::Binary(vec![0xc3]),
Duration::from_secs(10),
)
.unwrap();
let plaintext = responder.decrypt(&encrypted).unwrap();
let parsed = Link::parse_request_value(&plaintext).unwrap();
assert_eq!(parsed.data, rmpv::Value::Binary(vec![0xc3]));
}
#[test]
fn packed_request_data_must_be_one_complete_value() {
let (mut initiator, responder, _) = make_active_link();
assert!(
initiator
.request("p", Some(b"not msgpack \xc1"), Duration::from_secs(10))
.is_err()
);
assert!(initiator.pending_requests.is_empty());
let (encrypted, _) = initiator
.request("p", Some(&[0x92, 0x01, 0x02]), Duration::from_secs(10))
.unwrap();
let parsed = Link::parse_request_value(&responder.decrypt(&encrypted).unwrap()).unwrap();
assert_eq!(parsed.data, rmpv::Value::Array(vec![1.into(), 2.into()]));
}
#[test]
fn receiving_request_survives_tick_past_deadline() {
let (mut initiator, _responder, _) = make_active_link();
let (_, request_id) = initiator.request("p", None, Duration::ZERO).unwrap();
assert!(initiator.mark_request_receiving(&request_id));
initiator.tick();
assert_eq!(initiator.pending_requests.len(), 1);
}
#[test]
fn test_request_str_roundtrip_as_plain_utf8_body() {
let (mut initiator, responder, _) = make_active_link();
+27 -16
View File
@@ -94,9 +94,21 @@ impl RequestReceipt {
}
}
/// Only a request still waiting for its response can time out. Once a
/// response Resource is being received, its own watchdogs end it.
pub fn is_timed_out(&self) -> bool {
matches!(self.state, RequestState::Sent | RequestState::Receiving)
&& self.sent_at.elapsed() >= self.timeout
self.state == RequestState::Sent && self.sent_at.elapsed() >= self.timeout
}
/// Enter `Receiving` when a response Resource is accepted. Returns `false`
/// if the receipt is no longer pending, so the caller cancels the Resource.
pub fn mark_receiving(&mut self) -> bool {
if self.is_pending() {
self.state = RequestState::Receiving;
true
} else {
false
}
}
pub fn is_pending(&self) -> bool {
@@ -326,21 +338,20 @@ mod tests {
}
#[test]
fn test_receiving_request_times_out_and_fires_failure_callback() {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let fired = Arc::new(AtomicBool::new(false));
let callback_fired = fired.clone();
fn receiving_request_is_not_timed_out() {
let mut receipt = RequestReceipt::new([0x77; 32], [0x88; 16], Duration::ZERO);
receipt.state = RequestState::Receiving;
receipt.set_failed_callback(move |receipt| {
assert_eq!(receipt.state, RequestState::Failed);
callback_fired.store(true, Ordering::SeqCst);
});
assert!(receipt.mark_receiving());
assert_eq!(receipt.state, RequestState::Receiving);
assert!(receipt.check_timeout());
assert!(fired.load(Ordering::SeqCst));
assert!(!receipt.is_pending());
assert!(!receipt.check_timeout());
assert!(receipt.is_pending());
}
#[test]
fn failed_request_does_not_enter_receiving() {
let mut receipt = RequestReceipt::new([0x77; 32], [0x88; 16], Duration::ZERO);
receipt.fail();
assert!(!receipt.mark_receiving());
assert_eq!(receipt.state, RequestState::Failed);
}
}
+45 -11
View File
@@ -1080,6 +1080,8 @@ impl LazyMultiSegmentOutbound {
)?;
resource.flags.split = true;
resource.flags.is_response = self.is_response;
// Later segments advertise the metadata flag without carrying metadata.
resource.flags.has_metadata |= self.metadata_wire_size > 0;
resource.segment_index = segment_index;
resource.total_segments = self.total_segments;
resource.request_id = self.request_id.clone();
@@ -1442,6 +1444,9 @@ pub struct OutboundTransfer {
// requests and local polling are not Resource progress.
last_progress: Instant,
last_request_parts: usize,
/// Advertisement wait per attempt before PROCESSING_GRACE; `None` uses
/// `rtt * TRAFFIC_TIMEOUT_FACTOR`, as Resource does without a timeout.
pub advertisement_timeout: Option<Duration>,
}
impl OutboundTransfer {
@@ -1497,9 +1502,19 @@ impl OutboundTransfer {
req_hashlist: HashSet::new(),
last_progress: Instant::now(),
last_request_parts: 0,
advertisement_timeout: None,
}
}
fn advertisement_attempt_timeout(&self) -> Duration {
self.advertisement_timeout
.unwrap_or_else(|| {
self.rtt
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
})
.saturating_add(Duration::from_secs_f64(PROCESSING_GRACE))
}
/// Advertise and drive bounded phase timeouts. Parts are emitted only in
/// response to the receiver's [`Self::handle_request`] (or
/// [`Self::handle_request_packet`]); polling never sends unsolicited parts.
@@ -1571,10 +1586,7 @@ impl OutboundTransfer {
return TransferAction::None;
}
let timeout = self
.rtt
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
.saturating_add(Duration::from_secs_f64(PROCESSING_GRACE));
let timeout = self.advertisement_attempt_timeout();
if self.started_at.elapsed() <= timeout {
return TransferAction::None;
}
@@ -1606,10 +1618,7 @@ impl OutboundTransfer {
pub fn timeout_window(&self) -> Option<(Instant, Duration)> {
match self.resource.state {
ResourceState::Advertised => {
let attempt = self
.rtt
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
.saturating_add(Duration::from_secs_f64(PROCESSING_GRACE));
let attempt = self.advertisement_attempt_timeout();
Some((
self.started_at,
attempt.saturating_mul(
@@ -3070,6 +3079,26 @@ mod tests {
assert_eq!(transfer.resource.state, ResourceState::Advertised);
}
#[test]
fn explicit_advertisement_timeout_delays_readvertisement() {
let mut transfer =
OutboundTransfer::new(b"request body".to_vec(), false, Duration::from_millis(1))
.unwrap();
transfer.advertisement_timeout = Some(Duration::from_secs(30));
transfer.tick();
transfer.started_at = ago_or_skip!(Duration::from_secs(20));
assert!(matches!(transfer.check_timeout(), TransferAction::None));
assert_eq!(transfer.retries, 0);
transfer.started_at = ago_or_skip!(Duration::from_secs(32));
assert!(matches!(
transfer.check_timeout(),
TransferAction::SendAdvertisement(_)
));
assert_eq!(transfer.retries, 1);
}
#[test]
fn test_outbound_advertisement_watchdog_fails_after_retry_limit() {
let mut transfer = OutboundTransfer::new(
@@ -3953,7 +3982,8 @@ mod tests {
.is_some_and(|wire| wire.ends_with(&metadata))
);
assert_eq!(first.metadata_size, metadata.len() + 3);
assert!(!second.flags.has_metadata);
assert!(second.flags.has_metadata);
assert!(second.metadata.is_none());
assert_eq!(first.request_id, Some(request_id.clone()));
assert_eq!(second.request_id, Some(request_id));
assert!(first.flags.is_response);
@@ -4367,20 +4397,24 @@ mod tests {
multi_out.segments[0].metadata_size + multi_out.segments[0].data.len()
<= MAX_EFFICIENT_SIZE
);
assert!(!multi_out.segments[1].flags.has_metadata);
assert!(multi_out.segments[1].flags.has_metadata);
assert!(multi_out.segments[1].metadata.is_none());
let total_segments = multi_out.total_segments;
let original_hash = multi_out.original_hash;
let mut multi_in = MultiSegmentInbound::new(total_segments, original_hash);
for mut segment in multi_out.segments {
// Receivers strip metadata from segment 1 only (Resource.py:718).
let mut flags = segment.flags;
flags.has_metadata &= segment.segment_index == 1;
let mut inbound = InboundTransfer::from_advertisement(
segment.num_parts(),
segment.total_size,
segment.data.len(),
segment.random_hash,
segment.resource_hash,
segment.flags,
flags,
segment.map_hashes.clone(),
Duration::from_millis(500),
)
+1 -1
View File
@@ -41,7 +41,7 @@ async fn server(args: ExampleArgs) -> ExampleResult {
request.data.len(),
request.path,
);
RequestOutcome::Reply(request.data)
RequestOutcome::ReplyBytes(request.data)
},
)
.await?;
+17 -5
View File
@@ -95,7 +95,13 @@ impl DeferredRequestResponder {
return Err(DeferredResponseError::Closed);
}
let capacity = match &outcome {
RequestOutcome::Reply(data) => Some(data.capacity()),
RequestOutcome::ReplyBytes(data) | RequestOutcome::ReplyValue(data) => {
Some(data.capacity())
}
// The file source is streamed; only the metadata is held here.
RequestOutcome::ReplyFile { metadata, .. } => {
Some(metadata.as_ref().map_or(0, Vec::capacity))
}
RequestOutcome::ReplyWithResource {
ack,
data,
@@ -232,7 +238,9 @@ mod tests {
assert_eq!(counts.lock().unwrap().jobs, 1);
assert!(worker.is_cancelled());
assert_eq!(
worker.respond(RequestOutcome::Reply(vec![1])).unwrap_err(),
worker
.respond(RequestOutcome::ReplyBytes(vec![1]))
.unwrap_err(),
DeferredResponseError::Closed
);
assert_eq!(counts.lock().unwrap().jobs, 0);
@@ -248,7 +256,9 @@ mod tests {
let (worker, pending) = jobs.pop().unwrap();
let bytes = Vec::with_capacity(101);
assert_eq!(
worker.respond(RequestOutcome::Reply(bytes)).unwrap_err(),
worker
.respond(RequestOutcome::ReplyBytes(bytes))
.unwrap_err(),
DeferredResponseError::TooLarge
);
drop(pending);
@@ -270,7 +280,9 @@ mod tests {
.unwrap();
assert!(worker.is_cancelled());
assert_eq!(
worker.respond(RequestOutcome::Reply(vec![1])).unwrap_err(),
worker
.respond(RequestOutcome::ReplyBytes(vec![1]))
.unwrap_err(),
DeferredResponseError::Closed
);
drop(pending);
@@ -282,7 +294,7 @@ mod tests {
let counts = Arc::new(Mutex::new(Counts::default()));
let (worker, mut pending) =
reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap();
let mut ack = worker.respond(RequestOutcome::Reply(vec![1])).unwrap();
let mut ack = worker.respond(RequestOutcome::ReplyBytes(vec![1])).unwrap();
assert_eq!(counts.lock().unwrap().jobs, 1);
let resolution = pending.try_recv().unwrap();
let resource_lease = pending.lease();
+22 -2
View File
@@ -244,7 +244,7 @@ impl DestinationHandle {
path: impl Into<String>,
allow: AllowPolicy,
allowed_list: Vec<[u8; 16]>,
auto_compress: bool,
auto_compress: impl Into<crate::resource_source::AutoCompress>,
handler: F,
) -> Result<bool, DestinationRuntimeError>
where
@@ -256,7 +256,7 @@ impl DestinationHandle {
path: path.into(),
allow,
allowed_list,
auto_compress,
auto_compress: auto_compress.into(),
handler: Box::new(handler),
result_tx: Some(result_tx),
})
@@ -267,6 +267,26 @@ impl DestinationHandle {
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
/// Destination.set_max_request_size: REQUEST packets larger than `limit`
/// bytes are ignored and larger request Resources are rejected. `None`
/// accepts any size.
pub async fn set_max_request_size(
&self,
limit: Option<usize>,
) -> Result<(), DestinationRuntimeError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkManagerCommand::SetMaxRequestSize {
limit,
result_tx: Some(result_tx),
})
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
result_rx
.await
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
}
pub async fn deregister_request_handler(
&self,
path: impl Into<String>,
+2 -2
View File
@@ -44,9 +44,9 @@ pub mod prelude {
pub use crate::link_session::{
LinkSession, LinkSessionChannelError, LinkSessionChannelHandle, LinkSessionCloseReason,
LinkSessionError, LinkSessionEvent, LinkSessionHandle, LinkSessionResourceError,
LinkSessionResourceOffer, LinkSessionResponse,
LinkSessionResourceOffer, LinkSessionResponse, RequestOptions,
};
pub use crate::resource_source::{ResourceOptions, ResourceSource};
pub use crate::resource_source::{AutoCompress, ResourceOptions, ResourceSource};
pub use crate::reticulum::{
AnnounceSubscription, ControlError, InitOptions, InterfaceStats, LinkConnectError,
LinkConnectOptions, OutboundPacket, PacketReceiptHandle, PacketReceiptStatus,
+111 -9
View File
@@ -72,6 +72,7 @@ impl LinkClient {
/// Open a Link to `app_name` on the supplied identity hash, identify the local
/// identity, send one request and return its response bytes. For the current
/// remote-management service, this is the remote transport identity hash.
/// `payload` is one encoded MessagePack value, or empty to send nil.
///
/// `overall_timeout` supplies remaining budgets for discovery, Link proof and
/// response waits. Registration, endpoint binding, sends and teardown can
@@ -200,8 +201,10 @@ impl LinkClient {
self.send_link_packet(link_id, identify_pkt).await?;
let req_timeout = Duration::from_secs(5);
// An empty payload sends nil, as Link.request(path) does.
let packed_data = (!payload.is_empty()).then_some(payload.as_slice());
let (encrypted_req, request_id) = link
.request(path, Some(&payload), req_timeout)
.request(path, packed_data, req_timeout)
.map_err(|e| LinkClientError::LinkCrypto(format!("request: {e:?}")))?;
let request_pkt = build_data_packet(
link_id,
@@ -303,10 +306,26 @@ async fn wait_for_response(
request_id: [u8; 16],
deadline: Duration,
) -> Result<Vec<u8>, LinkClientError> {
let fut = async {
let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new();
// The request deadline applies until a response Resource is accepted;
// after that the Resource watchdog ends a stalled transfer (Link.py:1475-1522).
let deadline_at = Instant::now() + deadline;
let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new();
// Split response: segment payloads in order, file metadata flag of segment 1.
let mut split_response: Vec<u8> = Vec::new();
let mut segments: HashMap<[u8; 32], (usize, usize, bool)> = HashMap::new();
let mut completed_segments = 0usize;
let mut receiving = false;
{
loop {
let wait = if !receiving {
let remaining = deadline_at.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(LinkClientError::Timeout("response"));
}
remaining.min(WATCHDOG_TICK)
} else {
WATCHDOG_TICK
};
let ev = tokio::select! {
event = endpoint.delivery_rx.recv() => event.ok_or_else(|| LinkClientError::HandshakeFailed(
"destination channel closed".into(),
@@ -316,6 +335,11 @@ async fn wait_for_response(
"link endpoint terminated: {terminal:?}"
)));
}
_ = tokio::time::sleep(wait) => {
poll_response_resources(transport_tx, link, link_id, &mut inbound_resources)
.await?;
continue;
}
};
match ev {
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
@@ -372,19 +396,31 @@ async fn wait_for_response(
{
continue;
}
// Segments are appended as they complete, so only the next one fits.
if adv.total_segments > rns_protocol::resource::MAX_SEGMENTS
|| adv.segment_index != completed_segments + 1
|| adv.segment_index > adv.total_segments
{
continue;
}
let mut random_hash = [0u8; rns_protocol::resource::RANDOM_HASH_SIZE];
let copy_len = adv.random_hash.len().min(random_hash.len());
random_hash[..copy_len].copy_from_slice(&adv.random_hash[..copy_len]);
let rtt = link.rtt.unwrap_or(Duration::from_millis(500));
let mut flags = adv.flags;
// Only segment 1 carries metadata bytes (Resource.py:718).
if adv.segment_index > 1 {
flags.has_metadata = false;
}
let mut transfer = InboundTransfer::from_advertisement(
adv.num_parts,
adv.transfer_size,
adv.data_size,
random_hash,
adv.resource_hash,
adv.flags,
flags,
adv.get_map_hashes(),
rtt,
)
@@ -406,6 +442,15 @@ async fn wait_for_response(
.await?;
}
receiving = true;
segments.insert(
adv.resource_hash,
(
adv.segment_index,
adv.total_segments,
adv.flags.has_metadata,
),
);
inbound_resources.insert(adv.resource_hash, transfer);
}
rns_wire::context::PacketContext::Resource => {
@@ -487,6 +532,19 @@ async fn wait_for_response(
send_link_proof(transport_tx, link_id, &proof).await?;
inbound_resources.remove(&rh);
let (segment_index, total_segments, file_response) =
segments.remove(&rh).unwrap_or((1, 1, false));
split_response.extend_from_slice(&assembled);
completed_segments = segment_index;
if segment_index < total_segments {
continue;
}
let assembled = std::mem::take(&mut split_response);
// Link.response_resource_concluded: metadata marks a file response.
if file_response {
link.deliver_response_data(&request_id, Vec::new());
return Ok(assembled);
}
match link.handle_response_plaintext(&assembled) {
Ok((id, response_data)) => {
if id == request_id {
@@ -566,10 +624,54 @@ async fn wait_for_response(
_ => {}
}
}
};
timeout(deadline, fut)
.await
.map_err(|_| LinkClientError::Timeout("response"))?
}
}
const WATCHDOG_TICK: Duration = Duration::from_secs(1);
async fn poll_response_resources(
transport_tx: &mpsc::Sender<TransportMessage>,
link: &mut Link,
link_id: [u8; 16],
inbound_resources: &mut HashMap<[u8; 32], InboundTransfer>,
) -> Result<(), LinkClientError> {
let actions: Vec<TransferAction> = inbound_resources
.values_mut()
.map(InboundTransfer::check_timeout)
.collect();
for action in actions {
match action {
TransferAction::Failed(reason) => {
return Err(LinkClientError::UnexpectedResponse(format!(
"resource transfer failed: {reason}"
)));
}
TransferAction::SendRequest(req) => {
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceReq,
&req,
true,
)
.await?;
}
TransferAction::SendHmu(hmu) => {
send_link_data(
transport_tx,
link,
link_id,
rns_wire::context::PacketContext::ResourceHmu,
&hmu,
true,
)
.await?;
}
_ => {}
}
}
Ok(())
}
async fn send_link_data(
+447 -102
View File
@@ -20,6 +20,7 @@ pub use crate::inbound_link_packet::{
InboundLinkPacket, LinkPacketConfigurationError, LinkPacketReceipt, LinkPacketReceiptOutcome,
LinkPacketRejection,
};
use crate::resource_source::{AutoCompress, PreparedResourceSource, ResourceSource};
use bytes::Bytes;
use rns_identity::destination::ProofStrategy;
use tokio::sync::{mpsc, oneshot};
@@ -65,6 +66,37 @@ enum LegacyTerminalNotification {
LinkClosed([u8; 16]),
}
/// Remaining segments of an outbound split Resource: prepared up front, or
/// read from a source one segment at a time as each segment is proved.
enum OutboundSplitQueue {
Prebuilt(VecDeque<OutboundTransfer>),
Source(Box<PreparedResourceSource>),
}
impl OutboundSplitQueue {
/// Next segment transfer and whether the queue is now exhausted. An error
/// means a remaining segment could not be produced.
fn next(&mut self, link: &Link) -> Result<(Option<OutboundTransfer>, bool), String> {
match self {
Self::Prebuilt(queue) => {
let next = queue.pop_front();
Ok((next, queue.is_empty()))
}
Self::Source(source) => {
let rtt = link.rtt.unwrap_or(std::time::Duration::from_millis(500));
let keys = link
.session_keys()
.ok_or_else(|| "link keys are unavailable".to_string())?;
let segment = source
.next_segment(&keys, rtt)
.map_err(|error| error.to_string())?
.ok_or_else(|| "Resource source ended early".to_string())?;
Ok((Some(segment.transfer), source.is_exhausted()))
}
}
}
}
struct ActiveLink {
link: Link,
_interface_id: u64,
@@ -74,7 +106,7 @@ struct ActiveLink {
channel: Option<LinkChannel>,
inbound_resources: HashMap<[u8; 32], InboundTransfer>,
outbound_resources: HashMap<[u8; 32], OutboundTransfer>,
outbound_split_queues: HashMap<[u8; 32], VecDeque<OutboundTransfer>>,
outbound_split_queues: HashMap<[u8; 32], OutboundSplitQueue>,
/// Split-resource reassembly keyed by `original_hash`; dropped on full delivery or cancel.
inbound_split_resources: HashMap<[u8; 32], MultiSegmentInbound>,
/// Reverse index per-segment `resource_hash` → coordinator; routes assembled
@@ -363,10 +395,15 @@ pub enum LinkManagerCommand {
path: String,
allow: AllowPolicy,
allowed_list: Vec<[u8; 16]>,
auto_compress: bool,
auto_compress: AutoCompress,
handler: DestinationRequestHandler,
result_tx: Option<oneshot::Sender<bool>>,
},
/// Set or clear Destination.max_request_size.
SetMaxRequestSize {
limit: Option<usize>,
result_tx: Option<oneshot::Sender<()>>,
},
/// Remove a per-path request handler.
DeregisterRequestHandler {
path: String,
@@ -511,15 +548,29 @@ impl std::fmt::Debug for LinkManagerAccountingEvent {
}
}
/// Request-handler response. `Reply` uses a RESPONSE packet or, when the packed
/// response exceeds the Link MDU, a response Resource. `ReplyWithResource`
/// stages the acknowledgment and a separate ordinary Resource, as used by rncp
/// fetch. Neither staging
/// operation confirms delivery; arrival order is not guaranteed.
#[derive(Debug, Clone)]
/// Request-handler response, packed as Link.handle_request packs a handler's
/// return value. `ReplyBytes` and `ReplyValue` use a RESPONSE packet or, when
/// the packed response exceeds the Link MDU, a response Resource.
/// `ReplyWithResource` stages the acknowledgment and a separate ordinary
/// Resource, as used by rncp fetch. Neither staging operation confirms
/// delivery; arrival order is not guaranteed.
pub enum RequestOutcome {
Reply(Vec<u8>),
/// A byte string, received by a Python requester as `bytes`.
ReplyBytes(Vec<u8>),
/// Exactly one already-encoded MessagePack value (a list, map, int, bool,
/// nil, ...). A reply that is not one complete value is not sent.
ReplyValue(Vec<u8>),
/// A file response: one response Resource correlated with the request,
/// as a handler returning `[file, metadata]` sends. The source is read one
/// segment at a time. `metadata` is the packed MessagePack metadata; with
/// `None` the requester receives a plain response Resource, as for a
/// handler returning `[file]`.
ReplyFile {
source: Box<dyn ResourceSource>,
metadata: Option<Vec<u8>>,
},
ReplyWithResource {
/// One already-encoded MessagePack value sent as the response.
ack: Vec<u8>,
data: Vec<u8>,
/// Optional opaque Resource metadata. rncp expects a MessagePack map
@@ -532,6 +583,32 @@ pub enum RequestOutcome {
Drop,
}
impl std::fmt::Debug for RequestOutcome {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ReplyBytes(data) => f.debug_tuple("ReplyBytes").field(&data.len()).finish(),
Self::ReplyValue(data) => f.debug_tuple("ReplyValue").field(&data.len()).finish(),
Self::ReplyFile { metadata, .. } => f
.debug_struct("ReplyFile")
.field("metadata_len", &metadata.as_ref().map(Vec::len))
.finish_non_exhaustive(),
Self::ReplyWithResource {
ack,
data,
metadata,
auto_compress,
} => f
.debug_struct("ReplyWithResource")
.field("ack_len", &ack.len())
.field("data_len", &data.len())
.field("metadata_len", &metadata.as_ref().map(Vec::len))
.field("auto_compress", auto_compress)
.finish(),
Self::Drop => f.write_str("Drop"),
}
}
}
/// Context for a per-path Destination request handler. `remote_identity`
/// comes from verified LinkIdentify, when present; the registered `AllowPolicy`
/// is applied separately. `requested_at` is the sender's timestamp, not a
@@ -539,7 +616,11 @@ pub enum RequestOutcome {
#[derive(Clone)]
pub struct DestinationRequest {
pub path: String,
/// Byte view of the request data: binary and string contents as-is, any
/// other value re-encoded as MessagePack. Use `value` to tell them apart.
pub data: Vec<u8>,
/// The request data as sent, e.g. `Value::Binary` for Python `bytes`.
pub value: rmpv::Value,
pub request_id: [u8; 16],
pub link_id: [u8; 16],
pub remote_identity: Option<Identity>,
@@ -569,7 +650,7 @@ struct PendingDeferredRequest {
path_hash: [u8; 16],
generation: u64,
owner: Option<rns_transport::messages::InterfaceOwnerId>,
auto_compress: bool,
auto_compress: AutoCompress,
response: crate::deferred_request::PendingResponse,
}
struct DeferredResourceLease {
@@ -581,7 +662,7 @@ struct RegisteredRequestHandler {
path: String,
allow: AllowPolicy,
allowed_list: Vec<[u8; 16]>,
auto_compress: bool,
auto_compress: AutoCompress,
handler: RegisteredHandler,
}
@@ -637,8 +718,10 @@ pub struct LinkManager {
/// Private ratchets for a live inbound destination. The manager owns this
/// alongside `destination` so enforced decryption cannot outlive its keys.
destination_ratchets: Option<PersistentRatchetRing>,
/// `(link_id, path_hash, data) -> Option<response>`.
/// `(link_id, path_hash, data) -> Option<packed MessagePack response>`.
request_handler: Option<RequestHandler>,
/// Destination.max_request_size: larger requests are ignored or rejected.
max_request_size: Option<usize>,
deferred_request_notify: Arc<tokio::sync::Notify>,
pending_deferred_requests: Vec<PendingDeferredRequest>,
deferred_resource_leases: Vec<DeferredResourceLease>,
@@ -763,6 +846,7 @@ impl LinkManager {
identity: None,
destination_ratchets: None,
request_handler: None,
max_request_size: None,
deferred_request_notify: Arc::new(tokio::sync::Notify::new()),
pending_deferred_requests: Vec::new(),
deferred_resource_leases: Vec::new(),
@@ -857,6 +941,7 @@ impl LinkManager {
identity: manager_identity,
destination_ratchets: None,
request_handler: None,
max_request_size: None,
deferred_request_notify: Arc::new(tokio::sync::Notify::new()),
pending_deferred_requests: Vec::new(),
deferred_resource_leases: Vec::new(),
@@ -2023,6 +2108,13 @@ impl LinkManager {
}
true
}
LinkManagerCommand::SetMaxRequestSize { limit, result_tx } => {
self.set_max_request_size(limit);
if let Some(tx) = result_tx {
let _ = tx.send(());
}
true
}
LinkManagerCommand::DeregisterRequestHandler { path, result_tx } => {
let result = self.deregister_request_handler(&path);
if let Some(tx) = result_tx {
@@ -3344,6 +3436,31 @@ impl LinkManager {
break 'adv;
}
if is_request
&& self
.max_request_size
.is_some_and(|limit| adv.data_size > limit)
{
Self::reject_inbound_advertisement(
&self.transport_tx,
&mut self.pending_link_control,
&mut self.pending_endpoint_sends,
active,
&mut self.active_inbound_lifecycles,
&mut self.pending_inbound_request_resources,
&self.resource_event_tx,
&self.accounting_event_tx,
link_id,
resource_id,
adv.resource_hash,
format!(
"rejected request with excessive size {}",
adv.data_size
),
);
break 'adv;
}
// Preserve AcceptNone as a cheap first-offer drop: it
// invokes no application code and allocates no Resource
// state. A strategy change during a split concludes the
@@ -4121,44 +4238,53 @@ impl LinkManager {
let mut next_segment_failed = false;
let completed_resource_hash = queue_key.unwrap_or(rh);
if let Some(key) = queue_key {
let (next, empty) = if let Some(queue) =
active.outbound_split_queues.get_mut(&key)
{
let next = queue.pop_front();
(next, queue.is_empty())
} else {
(None, false)
let step = match active.outbound_split_queues.get_mut(&key) {
Some(queue) => queue.next(&active.link),
None => Ok((None, false)),
};
if empty {
active.outbound_split_queues.remove(&key);
}
if let Some(next) = next {
started_next_segment = Self::start_outbound_transfer(
&self.transport_tx,
&mut self.pending_link_control,
&mut self.pending_endpoint_sends,
active,
&link_id,
next,
)
.is_some();
next_segment_failed = !started_next_segment;
if next_segment_failed {
active.outbound_split_queues.remove(&key);
Self::emit_resource_event(
&self.resource_event_tx,
&self.accounting_event_tx,
LinkResourceEvent::Concluded {
link_id,
resource_id: completed_resource_hash,
direction: LinkResourceDirection::Outbound,
conclusion: LinkResourceConclusion::Failed(
let mut failure = None;
match step {
Ok((next, empty)) => {
if empty {
active.outbound_split_queues.remove(&key);
}
if let Some(next) = next {
started_next_segment = Self::start_outbound_transfer(
&self.transport_tx,
&mut self.pending_link_control,
&mut self.pending_endpoint_sends,
active,
&link_id,
next,
)
.is_some();
if !started_next_segment {
failure = Some(
"could not retain next Resource segment advertisement"
.into(),
),
},
);
.to_string(),
);
}
}
}
Err(reason) => {
failure = Some(format!(
"next Resource segment could not be prepared: {reason}"
));
}
}
if let Some(reason) = failure {
next_segment_failed = true;
active.outbound_split_queues.remove(&key);
Self::emit_resource_event(
&self.resource_event_tx,
&self.accounting_event_tx,
LinkResourceEvent::Concluded {
link_id,
resource_id: completed_resource_hash,
direction: LinkResourceDirection::Outbound,
conclusion: LinkResourceConclusion::Failed(reason),
},
);
}
}
if !started_next_segment && !next_segment_failed {
@@ -4188,13 +4314,23 @@ impl LinkManager {
}
}
rns_wire::context::PacketContext::Request => {
let max_request_size = self.max_request_size;
let parsed = self.active_links.get_mut(&link_id).and_then(|active| {
active.link.record_inbound();
active.link.record_rx(data.len());
active.link.handle_request(data).ok()
let plaintext = active.link.decrypt(data).ok()?;
if max_request_size.is_some_and(|limit| plaintext.len() > limit) {
tracing::debug!(
link_id = hex::encode(link_id),
size = plaintext.len(),
"ignored request with excessive size"
);
return None;
}
Link::parse_request_value(&plaintext).ok()
});
if let Some((_packed_request_id, path_hash, requested_at, request_data)) = parsed {
if let Some(request) = parsed {
// Packet-sized requests use the truncated RNS packet hash.
// Resource-sized requests use the packed-request hash.
let request_id =
@@ -4202,9 +4338,9 @@ impl LinkManager {
self.handle_parsed_request(
link_id,
request_id,
path_hash,
requested_at,
request_data,
request.path_hash,
request.requested_at,
request.data,
);
}
}
@@ -4240,14 +4376,14 @@ impl LinkManager {
}
if let Some(payload) = completed_request_resource {
match Link::parse_request(&payload) {
Ok((request_id, path_hash, requested_at, request_data)) => {
match Link::parse_request_value(&payload) {
Ok(request) => {
self.handle_parsed_request(
link_id,
request_id,
path_hash,
requested_at,
request_data,
request.request_id,
request.path_hash,
request.requested_at,
request.data,
);
}
Err(error) => {
@@ -5391,8 +5527,9 @@ impl LinkManager {
request_id: [u8; 16],
path_hash: [u8; 16],
requested_at: f64,
data: Vec<u8>,
value: rmpv::Value,
) {
let data = rns_link::link::value_bytes_view(&value).unwrap_or_default();
let request_ready = self.active_links.get(&link_id).is_some_and(|active| {
active.link.state == LinkState::Active
|| (!active.link.is_initiator && active.link.state == LinkState::Handshake)
@@ -5412,7 +5549,7 @@ impl LinkManager {
.and_then(|active| active.link.remote_identity())
.and_then(|public_key| Identity::from_public_key(public_key).ok());
let mut response_auto_compress = false;
let mut response_auto_compress = AutoCompress::Off;
let outcome = if let Some(registered) = self.destination_request_handlers.get(&path_hash) {
let allowed = match registered.allow {
AllowPolicy::AllowNone => false,
@@ -5430,6 +5567,7 @@ impl LinkManager {
let request = DestinationRequest {
path: registered.path.clone(),
data,
value,
request_id,
link_id,
remote_identity,
@@ -5490,7 +5628,7 @@ impl LinkManager {
handler(link_id, path_hash, data.clone())
} else if let Some(ref handler) = self.request_handler {
match handler(link_id, path_hash, data) {
Some(response) => RequestOutcome::Reply(response),
Some(response) => RequestOutcome::ReplyValue(response),
None => RequestOutcome::Drop,
}
} else {
@@ -5512,24 +5650,46 @@ impl LinkManager {
link_id: [u8; 16],
request_id: [u8; 16],
path_hash: [u8; 16],
response_auto_compress: bool,
response_auto_compress: AutoCompress,
outcome: RequestOutcome,
lease: Option<Arc<crate::deferred_request::RequestLease>>,
) -> bool {
let mut sent = false;
let (response, fetch_spec) = match outcome {
RequestOutcome::Reply(response) => (Some(response), None),
RequestOutcome::ReplyBytes(bytes) => (
Some(Link::pack_response_value(
&request_id,
&rmpv::Value::Binary(bytes),
)),
None,
),
RequestOutcome::ReplyValue(value) => {
(Some(Link::pack_response(&request_id, &value)), None)
}
RequestOutcome::ReplyFile { source, metadata } => {
return self.start_file_response(
link_id,
request_id,
source,
metadata,
response_auto_compress,
lease,
);
}
RequestOutcome::ReplyWithResource {
ack,
data,
metadata,
auto_compress,
} => (Some(ack), Some((data, metadata, auto_compress))),
} => (
Some(Link::pack_response(&request_id, &ack)),
Some((data, metadata, auto_compress)),
),
RequestOutcome::Drop => (None, None),
};
if let Some(response) = response {
match Link::pack_response(&request_id, &response) {
if let Some(packed) = response {
match packed {
Ok(packed_response) => {
let mdu = self
.active_links
@@ -5569,16 +5729,21 @@ impl LinkManager {
tracing::debug!(
link_id = hex::encode(link_id),
request_id = hex::encode(request_id),
response_len = response.len(),
response_len = packed_response.len(),
"link request handled — response sent"
);
}
} else if let Some(resource_id) = self.start_response_resource(
&link_id,
packed_response,
request_id,
response_auto_compress,
) {
} else if let Some(resource_id) = {
let auto_compress =
response_auto_compress.applies_to(packed_response.len());
self.start_response_resource(
&link_id,
packed_response,
None,
request_id,
auto_compress,
)
} {
sent = true;
if let Some(lease) = &lease {
self.deferred_resource_leases.push(DeferredResourceLease {
@@ -5605,7 +5770,7 @@ impl LinkManager {
link_id = hex::encode(link_id),
request_id = hex::encode(request_id),
error = %error,
"link request response could not be packed"
"link request response is not one MessagePack value; not sent"
);
}
}
@@ -5644,6 +5809,90 @@ impl LinkManager {
sent
}
/// Link.handle_request file response: the file is the only response,
/// sent as one Resource carrying the request id and metadata. Later
/// segments are read from the source as earlier ones are proved.
fn start_file_response(
&mut self,
link_id: [u8; 16],
request_id: [u8; 16],
source: Box<dyn ResourceSource>,
metadata: Option<Vec<u8>>,
auto_compress: AutoCompress,
lease: Option<Arc<crate::deferred_request::RequestLease>>,
) -> bool {
let Some(resource_id) =
self.start_streamed_response(&link_id, request_id, source, metadata, auto_compress)
else {
tracing::warn!(
link_id = hex::encode(link_id),
request_id = hex::encode(request_id),
"link request file response could not be started"
);
return false;
};
if let Some(lease) = lease {
self.deferred_resource_leases.push(DeferredResourceLease {
link_id,
resource_id,
_lease: lease,
});
}
true
}
fn start_streamed_response(
&mut self,
link_id: &[u8; 16],
request_id: [u8; 16],
source: Box<dyn ResourceSource>,
metadata: Option<Vec<u8>>,
auto_compress: AutoCompress,
) -> Option<[u8; 32]> {
let active = self.active_links.get_mut(link_id)?;
if !matches!(active.link.state, LinkState::Active | LinkState::Stale) {
return None;
}
let keys = active.link.session_keys()?;
let rtt = active
.link
.rtt
.unwrap_or(std::time::Duration::from_millis(500));
let mut prepared =
PreparedResourceSource::prepare_response(source, request_id, metadata, auto_compress)
.map_err(|error| tracing::warn!(%error, "file response source refused"))
.ok()?;
let first = prepared.next_segment(&keys, rtt).ok()??;
let resource_key = first.logical_hash;
let total_segments = first.total_segments;
let data_size = first.data_size;
Self::start_outbound_transfer(
&self.transport_tx,
&mut self.pending_link_control,
&mut self.pending_endpoint_sends,
active,
link_id,
first.transfer,
)?;
if !prepared.is_exhausted() {
active
.outbound_split_queues
.insert(resource_key, OutboundSplitQueue::Source(Box::new(prepared)));
}
Self::emit_resource_event(
&self.resource_event_tx,
&self.accounting_event_tx,
LinkResourceEvent::Started {
link_id: *link_id,
resource_id: resource_key,
direction: LinkResourceDirection::Outbound,
data_size,
total_segments,
},
);
Some(resource_key)
}
fn poll_deferred_requests(&mut self) -> bool {
self.deferred_resource_leases.retain(|pending| {
self.active_links
@@ -5709,6 +5958,8 @@ impl LinkManager {
/// Install a synchronous fallback `(link_id, path_hash, data)` handler.
/// Per-path handlers and `set_request_handler_ex` take precedence. This
/// fallback must check authorization itself; `None` sends no response.
/// `Some` must hold exactly one encoded MessagePack value, sent as
/// [`RequestOutcome::ReplyValue`].
pub fn set_request_handler<F>(&mut self, handler: F)
where
F: Fn([u8; 16], [u8; 16], Vec<u8>) -> Option<Vec<u8>> + Send + 'static,
@@ -5740,7 +5991,7 @@ impl LinkManager {
path: &str,
allow: AllowPolicy,
allowed_list: Option<Vec<[u8; 16]>>,
auto_compress: bool,
auto_compress: impl Into<AutoCompress>,
handler: F,
) -> bool
where
@@ -5750,7 +6001,7 @@ impl LinkManager {
path,
allow,
allowed_list.unwrap_or_default(),
auto_compress,
auto_compress.into(),
Box::new(handler),
)
}
@@ -5760,7 +6011,7 @@ impl LinkManager {
path: &str,
allow: AllowPolicy,
allowed_list: Vec<[u8; 16]>,
auto_compress: bool,
auto_compress: AutoCompress,
handler: DestinationRequestHandler,
) -> bool {
if path.is_empty() {
@@ -5772,7 +6023,7 @@ impl LinkManager {
path,
allow,
Some(allowed_list.clone()),
auto_compress,
auto_compress.is_enabled(),
);
}
@@ -5803,7 +6054,7 @@ impl LinkManager {
path: &str,
allow: AllowPolicy,
allowed_list: Option<Vec<[u8; 16]>>,
auto_compress: bool,
auto_compress: impl Into<AutoCompress>,
response_byte_limit: usize,
handler: F,
) -> bool
@@ -5818,12 +6069,13 @@ impl LinkManager {
return false;
}
let allowed_list = allowed_list.unwrap_or_default();
let auto_compress = auto_compress.into();
if let Some(destination) = self.destination.as_mut() {
destination.register_request_handler(
path,
allow,
Some(allowed_list.clone()),
auto_compress,
auto_compress.is_enabled(),
);
}
self.destination_request_handlers.insert(
@@ -5842,6 +6094,13 @@ impl LinkManager {
true
}
/// Destination.set_max_request_size: REQUEST packets larger than `limit`
/// are ignored and larger request Resources are rejected. `None` accepts
/// any size.
pub fn set_max_request_size(&mut self, limit: Option<usize>) {
self.max_request_size = limit;
}
/// Remove the request handler registered for `path`.
pub fn deregister_request_handler(&mut self, path: &str) -> bool {
if let Some(destination) = self.destination.as_mut() {
@@ -6731,15 +6990,16 @@ impl LinkManager {
fn start_response_resource(
&mut self,
link_id: &[u8; 16],
packed_response: Vec<u8>,
data: Vec<u8>,
metadata: Option<Vec<u8>>,
request_id: [u8; 16],
auto_compress: bool,
) -> Option<[u8; 32]> {
self.start_resource_transfer_inner(
link_id,
ResourceTransferStart {
data: packed_response,
metadata: None,
data,
metadata,
auto_compress,
request_id: Some(request_id.to_vec()),
is_response: true,
@@ -6846,7 +7106,9 @@ impl LinkManager {
first,
)?;
if !transfers.is_empty() {
active.outbound_split_queues.insert(resource_key, transfers);
active
.outbound_split_queues
.insert(resource_key, OutboundSplitQueue::Prebuilt(transfers));
}
Self::emit_resource_event(
&self.resource_event_tx,
@@ -8298,7 +8560,9 @@ mod tests {
let transfer = active.outbound_resources.get_mut(&failed).unwrap();
transfer.resource.request_id = Some(vec![0; 500]);
transfer.started_at = ago_or_skip!(std::time::Duration::from_secs(60));
active.outbound_split_queues.insert(failed, VecDeque::new());
active
.outbound_split_queues
.insert(failed, OutboundSplitQueue::Prebuilt(VecDeque::new()));
manager.on_tick();
let active = &manager.active_links[&id];
assert_eq!(active.link.state, LinkState::Active);
@@ -8432,14 +8696,14 @@ mod tests {
false,
move |_| {
handler_calls.fetch_add(1, Ordering::SeqCst);
RequestOutcome::Reply(b"ready".to_vec())
RequestOutcome::ReplyBytes(b"ready".to_vec())
},
));
let (encrypted_request, _) = initiator
.request(
.request_value(
"fetch",
Some(b"file.bin"),
&rmpv::Value::Binary(b"file.bin".to_vec()),
std::time::Duration::from_secs(5),
)
.unwrap();
@@ -8554,6 +8818,55 @@ mod tests {
(initiator, responder)
}
#[test]
fn streamed_split_queue_reports_a_source_that_fails_mid_transfer() {
use std::io::{Cursor, Read, Seek, SeekFrom};
struct FailingSource {
inner: Cursor<Vec<u8>>,
budget: usize,
}
impl Read for FailingSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let read = self.inner.read(buf)?;
if read > self.budget {
return Err(std::io::Error::other("source went away"));
}
self.budget -= read;
Ok(read)
}
}
impl Seek for FailingSource {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
self.inner.seek(pos)
}
}
let size = rns_protocol::resource::MAX_EFFICIENT_SIZE + 1024;
// Enough for the hashing pass and the first segment only.
let source = FailingSource {
inner: Cursor::new(vec![0x5A; size]),
budget: size + rns_protocol::resource::MAX_EFFICIENT_SIZE,
};
let (link, _) = handshaken_link_pair();
let keys = link.session_keys().unwrap();
let mut prepared =
PreparedResourceSource::prepare_response(source, [3; 16], None, AutoCompress::Off)
.unwrap();
let first = prepared
.next_segment(&keys, std::time::Duration::from_millis(100))
.unwrap()
.unwrap();
assert_eq!(first.total_segments, 2);
assert!(!prepared.is_exhausted());
let mut queue = OutboundSplitQueue::Source(Box::new(prepared));
let Err(error) = queue.next(&link) else {
panic!("a failed read must not end the transfer as complete");
};
assert!(error.contains("source went away"), "{error}");
}
fn active_link_entry_at(link: Link, interface_id: InterfaceId) -> ActiveLink {
ActiveLink {
link,
@@ -9738,17 +10051,23 @@ mod tests {
}
));
let path = truncated_hash(b"/get");
manager.handle_parsed_request(link_id, [1; 16], path, 0.0, b"request".to_vec());
manager.handle_parsed_request(
link_id,
[1; 16],
path,
0.0,
rmpv::Value::Binary(b"request".to_vec()),
);
assert_eq!(manager.pending_deferred_requests.len(), 1);
assert!(transport_rx.try_recv().is_err());
// The worker may remain blocked while an unrelated synchronous handler
// still progresses through the same manager.
manager.set_request_handler(|_, _, _| Some(b"live".to_vec()));
manager.handle_parsed_request(link_id, [2; 16], [9; 16], 0.0, Vec::new());
manager.set_request_handler(|_, _, _| Some(b"\xa4live".to_vec()));
manager.handle_parsed_request(link_id, [2; 16], [9; 16], 0.0, rmpv::Value::Nil);
assert!(next_transport_message(&mut transport_rx).is_ok());
let worker = jobs.lock().unwrap().pop().unwrap();
let mut ack = worker
.respond(RequestOutcome::Reply(b"done".to_vec()))
.respond(RequestOutcome::ReplyBytes(b"done".to_vec()))
.unwrap();
assert!(manager.try_step());
assert_eq!(ack.try_recv().unwrap(), DeferredResponseOutcome::Sent);
@@ -9762,10 +10081,16 @@ mod tests {
assert_eq!(response, b"done");
// A reused Link ID with a new generation cannot consume an old result.
manager.handle_parsed_request(link_id, [3; 16], path, 0.0, b"request".to_vec());
manager.handle_parsed_request(
link_id,
[3; 16],
path,
0.0,
rmpv::Value::Binary(b"request".to_vec()),
);
let worker = jobs.lock().unwrap().pop().unwrap();
let mut ack = worker
.respond(RequestOutcome::Reply(b"stale".to_vec()))
.respond(RequestOutcome::ReplyBytes(b"stale".to_vec()))
.unwrap();
manager.active_endpoint_generations.insert(link_id, 8);
manager.poll_deferred_requests();
@@ -9774,10 +10099,16 @@ mod tests {
// A response beyond packet MDU owns its credit until the Resource is
// terminal, even though the worker and completion receiver are gone.
manager.handle_parsed_request(link_id, [4; 16], path, 0.0, b"request".to_vec());
manager.handle_parsed_request(
link_id,
[4; 16],
path,
0.0,
rmpv::Value::Binary(b"request".to_vec()),
);
let worker = jobs.lock().unwrap().pop().unwrap();
let mut ack = worker
.respond(RequestOutcome::Reply(vec![0x37; 3000]))
.respond(RequestOutcome::ReplyBytes(vec![0x37; 3000]))
.unwrap();
manager.poll_deferred_requests();
assert_eq!(ack.try_recv().unwrap(), DeferredResponseOutcome::Sent);
@@ -9794,7 +10125,13 @@ mod tests {
manager.poll_deferred_requests();
assert!(manager.deferred_resource_leases.is_empty());
manager.handle_parsed_request(link_id, [5; 16], path, 0.0, b"request".to_vec());
manager.handle_parsed_request(
link_id,
[5; 16],
path,
0.0,
rmpv::Value::Binary(b"request".to_vec()),
);
let worker = jobs.lock().unwrap().pop().unwrap();
drop(manager);
assert!(worker.is_cancelled());
@@ -9933,12 +10270,16 @@ mod tests {
remote_hash,
request.requested_at,
));
RequestOutcome::Reply(b"ok".to_vec())
RequestOutcome::ReplyBytes(b"ok".to_vec())
},
));
let (encrypted_request, _) = sender_link
.request("status", Some(b"hello"), std::time::Duration::from_secs(5))
.request_value(
"status",
&rmpv::Value::Binary(b"hello".to_vec()),
std::time::Duration::from_secs(5),
)
.unwrap();
let request_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
@@ -9993,12 +10334,16 @@ mod tests {
false,
move |_| {
denied_calls_handler.fetch_add(1, Ordering::SeqCst);
RequestOutcome::Reply(b"must not run".to_vec())
RequestOutcome::ReplyBytes(b"must not run".to_vec())
},
));
let (denied_request, _) = sender_link
.request("status", Some(b"denied"), std::time::Duration::from_secs(5))
.request_value(
"status",
&rmpv::Value::Binary(b"denied".to_vec()),
std::time::Duration::from_secs(5),
)
.unwrap();
let mut denied_raw = request_header.pack();
denied_raw.extend_from_slice(&denied_request);
@@ -10060,7 +10405,7 @@ mod tests {
move |request| {
*observed_handler.lock().unwrap() =
Some((request.request_id, request.data, request.requested_at));
RequestOutcome::Reply(b"accepted".to_vec())
RequestOutcome::ReplyBytes(b"accepted".to_vec())
},
));
+496 -61
View File
@@ -7,7 +7,8 @@
//! queue can stall the actor, including its protocol timers and close handling.
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::Cursor;
use std::io::{Cursor, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};
use bytes::Bytes;
@@ -141,13 +142,47 @@ pub struct LinkSessionPacketReceipt {
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq)]
pub struct LinkSessionResponse {
pub request_id: [u8; 16],
/// Byte view of the response: binary and string contents as-is, any other
/// value re-encoded as MessagePack. For a file response, the file bytes,
/// unless they were spooled to `file`.
pub data: Vec<u8>,
/// Metadata attached to a file-style Resource response.
/// The response value as sent, e.g. `Value::Binary` for Python `bytes`.
/// `Value::Nil` for a file response.
pub value: rmpv::Value,
/// Packed metadata of a file response; `None` for ordinary responses.
pub metadata: Option<Vec<u8>>,
/// Spooled response data: always for a file response (one with
/// metadata), and for other Resource responses when
/// [`RequestOptions::spool_dir`] is set. The caller owns and removes it.
pub file: Option<PathBuf>,
pub response_time: Duration,
/// RequestReceipt.response_size: the advertised response data size.
pub response_size: Option<u64>,
/// RequestReceipt.response_transfer_size: bytes on the wire.
pub response_transfer_size: Option<u64>,
/// RequestReceipt.started_at: request sent, or request Resource delivered.
pub started_at: Option<Instant>,
/// RequestReceipt.response_concluded_at.
pub response_concluded_at: Option<Instant>,
}
/// Options for [`LinkSessionHandle::request_with_options`], as the optional
/// arguments of Link.request.
#[derive(Debug, Clone, Default)]
pub struct RequestOptions {
/// `None` selects the Link's RTT-based response timeout.
pub timeout: Option<Duration>,
/// Larger responses are rejected and fail the request.
pub max_response_size: Option<usize>,
/// Receives response Resource progress in `[0.0, 1.0]`.
pub progress: Option<watch::Sender<f64>>,
/// Directory for spooled responses. File responses are always spooled,
/// by default to the system temporary directory; with this set, other
/// Resource responses are spooled too instead of held in memory.
pub spool_dir: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -244,6 +279,8 @@ pub struct LinkSessionReceivedResource {
pub link_id: [u8; 16],
pub resource_id: [u8; 32],
pub data: Vec<u8>,
/// Set instead of `data` when a request response was spooled to disk.
pub file: Option<PathBuf>,
pub metadata: Option<Vec<u8>>,
pub total_segments: usize,
pub request_id: Option<Vec<u8>>,
@@ -484,6 +521,8 @@ pub enum LinkSessionError {
RequestResourceFailed(String),
#[error("too many Link requests are already pending")]
TooManyPendingRequests,
#[error("response of {size} bytes exceeds the {max}-byte limit")]
ResponseRejected { size: u64, max: usize },
#[error("Link session task is no longer running")]
SessionClosed,
}
@@ -495,8 +534,8 @@ enum LinkSessionCommand {
},
Request {
path: String,
data: Vec<u8>,
timeout: Option<Duration>,
data: rmpv::Value,
options: RequestOptions,
result_tx: oneshot::Sender<Result<LinkSessionResponse, LinkSessionError>>,
},
RequestResourceConcluded {
@@ -586,6 +625,72 @@ struct ResourceStartInfo {
struct PendingSessionRequest {
sent_at: Instant,
result_tx: oneshot::Sender<Result<LinkSessionResponse, LinkSessionError>>,
max_response_size: Option<usize>,
progress_tx: Option<watch::Sender<f64>>,
spool_dir: Option<PathBuf>,
response_size: Option<u64>,
response_transfer_size: Option<u64>,
started_at: Option<Instant>,
}
impl PendingSessionRequest {
fn new(
result_tx: oneshot::Sender<Result<LinkSessionResponse, LinkSessionError>>,
options: RequestOptions,
sent_as_packet: bool,
) -> Self {
let now = Instant::now();
Self {
sent_at: now,
result_tx,
max_response_size: options.max_response_size,
progress_tx: options.progress,
spool_dir: options.spool_dir,
response_size: None,
response_transfer_size: None,
started_at: sent_as_packet.then_some(now),
}
}
fn add_transfer_size(&mut self, size: usize) {
let total = self.response_transfer_size.get_or_insert(0);
*total = total.saturating_add(size as u64);
}
fn into_response(
self,
request_id: [u8; 16],
body: ResponseBody,
) -> (
oneshot::Sender<Result<LinkSessionResponse, LinkSessionError>>,
LinkSessionResponse,
) {
let response = LinkSessionResponse {
request_id,
data: body.data,
value: body.value,
metadata: body.metadata,
file: body.file,
response_time: self.sent_at.elapsed(),
response_size: self.response_size,
response_transfer_size: self.response_transfer_size,
started_at: self.started_at,
response_concluded_at: Some(Instant::now()),
};
(self.result_tx, response)
}
}
struct ResponseBody {
data: Vec<u8>,
value: rmpv::Value,
metadata: Option<Vec<u8>>,
file: Option<PathBuf>,
}
struct ResponseSpool {
path: PathBuf,
file: std::fs::File,
}
struct SessionOutboundResource {
@@ -627,11 +732,13 @@ struct SessionInboundLogical {
current_segment: Option<[u8; 32]>,
reported_bytes: usize,
reported_progress: f64,
spool: Option<ResponseSpool>,
}
struct InboundResourceLifecycle {
progress_tx: watch::Sender<f64>,
conclusion_tx: oneshot::Sender<Result<LinkSessionReceivedResource, LinkSessionResourceError>>,
spool: Option<ResponseSpool>,
}
struct InboundResourceSinks<'a> {
@@ -906,18 +1013,42 @@ impl LinkSessionHandle {
/// does not bound queueing, transfer or every transport wait. Apply a caller
/// deadline when needed. Dropping this future does not cancel an admitted
/// request or its remote work. At most 64 requests may be pending.
/// `data` is sent as a byte string (Python `bytes`); use
/// [`Self::request_with_options`] to send another MessagePack value.
pub async fn request(
&self,
path: &str,
data: &[u8],
timeout: Option<Duration>,
) -> Result<LinkSessionResponse, LinkSessionError> {
self.request_with_options(
path,
rmpv::Value::Binary(data.to_vec()),
RequestOptions {
timeout,
..RequestOptions::default()
},
)
.await
}
/// Send a request whose data is packed by type, as Link.request packs
/// `data` (`Value::Nil` for none), and wait for its response.
///
/// Once a response Resource is accepted the request timeout no longer
/// applies; the Resource's own watchdogs end a stalled transfer.
pub async fn request_with_options(
&self,
path: &str,
data: rmpv::Value,
options: RequestOptions,
) -> Result<LinkSessionResponse, LinkSessionError> {
let (result_tx, result_rx) = oneshot::channel();
self.command_tx
.send(LinkSessionCommand::Request {
path: path.to_string(),
data: data.to_vec(),
timeout,
data,
options,
result_tx,
})
.await
@@ -1287,7 +1418,7 @@ async fn run_session_actor(
Some(LinkSessionCommand::Request {
path,
data,
timeout,
options,
result_tx,
}) => {
if state.requests.len() >= MAX_PENDING_REQUESTS {
@@ -1305,15 +1436,12 @@ async fn run_session_actor(
},
&path,
&data,
timeout,
options.timeout,
).await {
Ok(request_id) => {
Ok((request_id, sent_as_packet)) => {
state.requests.insert(
request_id,
PendingSessionRequest {
sent_at: Instant::now(),
result_tx,
},
PendingSessionRequest::new(result_tx, options, sent_as_packet),
);
}
Err(error) => {
@@ -1340,6 +1468,9 @@ async fn run_session_actor(
);
} else {
let _ = link.mark_request_resource_sent(&request_id);
if let Some(pending) = state.requests.get_mut(&request_id) {
pending.started_at.get_or_insert_with(Instant::now);
}
}
}
Some(LinkSessionCommand::RequestResourceReceived {
@@ -1506,6 +1637,10 @@ async fn run_session_actor(
}
};
command_rx.close();
while let Ok(command) = command_rx.try_recv() {
discard_undelivered_spool(&command);
}
state.channel.shutdown();
fail_pending_requests(&mut state.requests, &event_tx);
fail_outbound_resources(&mut link, &mut state.resources, &event_tx);
@@ -1748,6 +1883,7 @@ async fn handle_resource_command(
InboundResourceLifecycle {
progress_tx,
conclusion_tx,
spool: None,
},
)
.await;
@@ -2422,6 +2558,7 @@ async fn accept_inbound_offer(
current_segment: Some(segment_hash),
reported_bytes: 0,
reported_progress: 0.0,
spool: lifecycle.spool,
},
);
resources.inbound.insert(
@@ -2493,6 +2630,11 @@ fn conclude_inbound_resource(
let Some(logical) = resources.inbound_logicals.remove(&resource_id) else {
return;
};
if result.is_err()
&& let Some(spool) = logical.spool
{
let _ = std::fs::remove_file(spool.path);
}
let succeeded = result.is_ok();
let _ = logical.conclusion_tx.send(result);
let _ = event_tx.try_send(LinkSessionEvent::ResourceConcluded {
@@ -2606,7 +2748,7 @@ async fn process_inbound_resource_advertisement(
attached_interface: InterfaceId,
link: &mut Link,
resources: &mut SessionResources,
pending_requests: &HashMap<[u8; 16], PendingSessionRequest>,
pending_requests: &mut HashMap<[u8; 16], PendingSessionRequest>,
sinks: InboundResourceSinks<'_>,
encrypted_advertisement: &[u8],
) -> bool {
@@ -2667,6 +2809,15 @@ async fn process_inbound_resource_advertisement(
}
if resources.inbound_logicals.contains_key(&resource_id) {
if advertisement.flags.is_response
&& let Some(pending) = advertisement
.request_id
.as_deref()
.and_then(|id| <[u8; 16]>::try_from(id).ok())
.and_then(|id| pending_requests.get_mut(&id))
{
pending.add_transfer_size(advertisement.transfer_size);
}
return match accept_followup_inbound_segment(
transport_tx,
attached_interface,
@@ -2723,6 +2874,53 @@ async fn process_inbound_resource_advertisement(
{
return false;
}
let pending = pending_requests
.get_mut(&request_id)
.expect("pending request checked above");
if let Some(max) = pending.max_response_size
&& advertisement.data_size > max
{
let size = advertisement.data_size as u64;
let transport_failed = matches!(
send_resource_action(
transport_tx,
attached_interface,
link,
TransferAction::SendCancel(CancelType::Rcl, segment_hash),
)
.await,
Err(LinkSessionResourceError::TransportUnavailable)
);
tracing::debug!(size, max, "rejected response with excessive size");
fail_session_request(
link,
pending_requests,
sinks.event_tx,
request_id,
LinkSessionError::ResponseRejected { size, max },
);
return transport_failed;
}
if !link.mark_request_receiving(&request_id) {
return false;
}
pending
.response_size
.get_or_insert(advertisement.data_size as u64);
pending.add_transfer_size(advertisement.transfer_size);
pending.started_at.get_or_insert_with(Instant::now);
let progress_tx = pending
.progress_tx
.clone()
.unwrap_or_else(|| watch::channel(0.0).0);
// A file response is handed over as a file, as Resource.assemble does;
// other responses are unpacked in memory unless a spool dir is given.
let spool = pending
.spool_dir
.clone()
.or_else(|| advertisement.flags.has_metadata.then(std::env::temp_dir))
.and_then(|dir| open_response_spool(&dir, &resource_id));
let spool_path = spool.as_ref().map(|spool| spool.path.clone());
resources.pending_inbound.insert(
segment_hash,
@@ -2731,7 +2929,6 @@ async fn process_inbound_resource_advertisement(
offered_at: Instant::now(),
},
);
let (progress_tx, _progress_rx) = watch::channel(0.0);
let (conclusion_tx, conclusion_rx) = oneshot::channel();
let result = accept_inbound_offer(
transport_tx,
@@ -2743,17 +2940,26 @@ async fn process_inbound_resource_advertisement(
InboundResourceLifecycle {
progress_tx,
conclusion_tx,
spool,
},
)
.await;
if result.is_err()
&& let Some(path) = spool_path
{
let _ = std::fs::remove_file(path);
}
let completion_tx = sinks.command_tx.clone();
tokio::spawn(async move {
let result = conclusion_rx
.await
.unwrap_or(Err(LinkSessionResourceError::SessionClosed));
let _ = completion_tx
if let Err(mpsc::error::SendError(command)) = completion_tx
.send(LinkSessionCommand::RequestResourceReceived { request_id, result })
.await;
.await
{
discard_undelivered_spool(&command);
}
});
return matches!(result, Err(LinkSessionResourceError::TransportUnavailable));
}
@@ -2935,7 +3141,18 @@ async fn complete_inbound_segment(
let mut coordinator_error = None;
if let Some(logical) = resources.inbound_logicals.get_mut(&resource_id) {
logical.current_segment = None;
if let Some(coordinator) = logical.coordinator.as_mut() {
// A spooled response keeps only segment order in memory.
let data = match logical.spool.as_mut() {
Some(spool) => {
if let Err(error) = spool.file.write_all(&data) {
coordinator_error = Some(error.to_string());
}
Vec::new()
}
None => data,
};
if coordinator_error.is_some() {
} else if let Some(coordinator) = logical.coordinator.as_mut() {
if let Err(error) = coordinator.set_segment_data(segment_index, data) {
coordinator_error = Some(error.to_string());
} else {
@@ -2973,10 +3190,12 @@ async fn complete_inbound_segment(
let Some(logical) = resources.inbound_logicals.get(&resource_id) else {
return false;
};
let file = logical.spool.as_ref().map(|spool| spool.path.clone());
let received = LinkSessionReceivedResource {
link_id: link.link_id,
resource_id,
data,
file,
metadata: complete_metadata,
total_segments: logical.total_segments,
request_id: logical.request_id.clone(),
@@ -3354,9 +3573,9 @@ async fn resend_timed_out_channel_messages(
async fn send_link_request(
context: SessionRequestContext<'_>,
path: &str,
data: &[u8],
data: &rmpv::Value,
timeout: Option<Duration>,
) -> Result<[u8; 16], LinkSessionError> {
) -> Result<([u8; 16], bool), LinkSessionError> {
let SessionRequestContext {
transport_tx,
attached_interface,
@@ -3370,7 +3589,7 @@ async fn send_link_request(
}
let timeout = timeout.unwrap_or_else(|| link.default_request_timeout());
let (packed, initial_request_id) = link
.prepare_request(path, Some(data), timeout)
.prepare_request_value(path, data, timeout)
.map_err(|_| LinkSessionError::LinkCrypto)?;
if packed.len() > link.mdu {
@@ -3391,7 +3610,7 @@ async fn send_link_request(
return Err(LinkSessionError::LinkCrypto);
};
let rtt = Duration::from_secs_f64(link.rtt_secs().max(0.001));
let segment = source
let mut segment = source
.next_segment(&keys, rtt)
.map_err(|error| {
link.fail_pending_request(&initial_request_id);
@@ -3403,6 +3622,8 @@ async fn send_link_request(
"request Resource source produced no segment".into(),
)
})?;
// Link.request passes its timeout to the request Resource.
segment.transfer.advertisement_timeout = Some(timeout);
let (progress_tx, _progress_rx) = watch::channel(0.0);
let (conclusion_tx, conclusion_rx) = oneshot::channel();
let mut outbound =
@@ -3441,7 +3662,7 @@ async fn send_link_request(
})
.await;
});
return Ok(initial_request_id);
return Ok((initial_request_id, false));
}
let encrypted = match link.encrypt(&packed) {
@@ -3467,7 +3688,7 @@ async fn send_link_request(
return Err(error);
}
link.record_tx(encrypted.len());
Ok(request_id)
Ok((request_id, true))
}
fn reap_concluded_requests(
@@ -3510,6 +3731,7 @@ fn conclude_request_resource_response(
result: Result<LinkSessionReceivedResource, LinkSessionResourceError>,
) {
if !pending_requests.contains_key(&request_id) {
remove_spooled_response(&result);
return;
}
let received = match result {
@@ -3521,6 +3743,7 @@ fn conclude_request_resource_response(
received
}
Ok(_) => {
remove_spooled_response(&result);
fail_session_request(
link,
pending_requests,
@@ -3544,11 +3767,36 @@ fn conclude_request_resource_response(
}
};
let (response_data, metadata) = if received.metadata.is_some() {
(received.data, received.metadata)
let body = if received.metadata.is_some() {
// Link.response_resource_concluded: metadata marks a file response.
ResponseBody {
data: received.data,
value: rmpv::Value::Nil,
metadata: received.metadata,
file: received.file,
}
} else {
let Ok((packed_request_id, response_data)) = Link::parse_response_plaintext(&received.data)
else {
let packed = match &received.file {
Some(path) => {
let read = std::fs::read(path);
let _ = std::fs::remove_file(path);
match read {
Ok(packed) => packed,
Err(error) => {
fail_session_request(
link,
pending_requests,
event_tx,
request_id,
LinkSessionError::RequestResourceFailed(error.to_string()),
);
return;
}
}
}
None => received.data,
};
let Ok((packed_request_id, value)) = Link::parse_response_value(&packed) else {
fail_session_request(
link,
pending_requests,
@@ -3572,10 +3820,71 @@ fn conclude_request_resource_response(
);
return;
}
(response_data, None)
ResponseBody {
data: rns_link::link::value_bytes_view(&value).unwrap_or_default(),
value,
metadata: None,
file: None,
}
};
if !link.deliver_response_data(&request_id, response_data.clone()) {
deliver_session_response(link, pending_requests, event_tx, request_id, body);
}
/// Link.handle_response for a single-packet response, with the
/// max_response_size check applied to `len(packb(response)) - 2`.
fn conclude_packet_response(
link: &mut Link,
pending_requests: &mut HashMap<[u8; 16], PendingSessionRequest>,
event_tx: &mpsc::Sender<LinkSessionEvent>,
request_id: [u8; 16],
value: rmpv::Value,
) {
let Some(pending) = pending_requests.get_mut(&request_id) else {
return;
};
let mut packed = Vec::new();
let _ = rmpv::encode::write_value(&mut packed, &value);
let size = packed.len().saturating_sub(2);
pending.response_size = Some(size as u64);
pending.add_transfer_size(size);
if let Some(max) = pending.max_response_size
&& size > max
{
tracing::debug!(size, max, "rejected response with excessive size");
fail_session_request(
link,
pending_requests,
event_tx,
request_id,
LinkSessionError::ResponseRejected {
size: size as u64,
max,
},
);
return;
}
let body = ResponseBody {
data: rns_link::link::value_bytes_view(&value).unwrap_or_default(),
value,
metadata: None,
file: None,
};
deliver_session_response(link, pending_requests, event_tx, request_id, body);
}
fn deliver_session_response(
link: &mut Link,
pending_requests: &mut HashMap<[u8; 16], PendingSessionRequest>,
event_tx: &mpsc::Sender<LinkSessionEvent>,
request_id: [u8; 16],
body: ResponseBody,
) {
// The response goes to the caller directly; the receipt keeps no copy.
if !link.deliver_response_data(&request_id, Vec::new()) {
if let Some(path) = &body.file {
let _ = std::fs::remove_file(path);
}
fail_session_request(
link,
pending_requests,
@@ -3586,21 +3895,63 @@ fn conclude_request_resource_response(
return;
}
let Some(pending) = pending_requests.remove(&request_id) else {
if let Some(path) = &body.file {
let _ = std::fs::remove_file(path);
}
return;
};
let response = LinkSessionResponse {
request_id,
data: response_data,
metadata,
response_time: pending.sent_at.elapsed(),
};
let _ = pending.result_tx.send(Ok(response));
if let Some(progress_tx) = &pending.progress_tx {
progress_tx.send_replace(1.0);
}
let (result_tx, response) = pending.into_response(request_id, body);
if let Err(Ok(response)) = result_tx.send(Ok(response))
&& let Some(path) = response.file
{
// The requester is gone, so nobody else can remove the file.
let _ = std::fs::remove_file(path);
}
let _ = event_tx.try_send(LinkSessionEvent::RequestConcluded {
request_id,
succeeded: true,
});
}
fn open_response_spool(dir: &std::path::Path, resource_id: &[u8; 32]) -> Option<ResponseSpool> {
// The id is chosen by the peer and the directory may be shared: never
// reuse or follow an existing entry.
let nonce = rns_crypto::random::random_bytes(8);
let path = dir.join(format!(
"{}-{}",
hex::encode(resource_id),
hex::encode(nonce)
));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
match options.open(&path) {
Ok(file) => Some(ResponseSpool { path, file }),
Err(error) => {
tracing::warn!(%error, path = %path.display(), "response spool unavailable; receiving in memory");
None
}
}
}
fn remove_spooled_response(result: &Result<LinkSessionReceivedResource, LinkSessionResourceError>) {
if let Ok(received) = result
&& let Some(path) = &received.file
{
let _ = std::fs::remove_file(path);
}
}
fn discard_undelivered_spool(command: &LinkSessionCommand) {
if let LinkSessionCommand::RequestResourceReceived { result, .. } = command {
remove_spooled_response(result);
}
}
fn fail_session_request(
link: &mut Link,
pending_requests: &mut HashMap<[u8; 16], PendingSessionRequest>,
@@ -3794,20 +4145,17 @@ async fn process_destination_event(
rns_wire::context::PacketContext::Response => {
link.record_inbound();
link.record_rx(body.len());
if let Ok((request_id, data)) = link.handle_response(body)
&& let Some(request) = state.requests.remove(&request_id)
if let Ok(plaintext) = link.decrypt(body)
&& let Ok((request_id, value)) = Link::parse_response_value(&plaintext)
&& state.requests.contains_key(&request_id)
{
let response = LinkSessionResponse {
conclude_packet_response(
link,
&mut state.requests,
event_tx,
request_id,
data,
metadata: None,
response_time: request.sent_at.elapsed(),
};
let _ = request.result_tx.send(Ok(response));
let _ = event_tx.try_send(LinkSessionEvent::RequestConcluded {
request_id,
succeeded: true,
});
value,
);
}
}
rns_wire::context::PacketContext::None => {
@@ -3859,7 +4207,7 @@ async fn process_destination_event(
attached_interface,
link,
&mut state.resources,
&state.requests,
&mut state.requests,
InboundResourceSinks {
event_tx,
command_tx,
@@ -4363,7 +4711,7 @@ mod tests {
let (command_tx, _command_rx) = mpsc::channel::<LinkSessionCommand>(4);
let mut resources = SessionResources::default();
let request_id = send_link_request(
let (request_id, _) = send_link_request(
SessionRequestContext {
transport_tx: &transport_tx,
attached_interface: 1,
@@ -4373,7 +4721,7 @@ mod tests {
command_tx: &command_tx,
},
"/large",
&payload,
&rmpv::Value::Binary(payload.clone()),
Some(Duration::from_secs(1)),
)
.await
@@ -4414,18 +4762,23 @@ mod tests {
responder.receive_rtt_packet(&rtt_data).unwrap();
let (_packed_request, request_id) = initiator
.prepare_request("/large-response", Some(b""), Duration::from_secs(5))
.prepare_request_value(
"/large-response",
&rmpv::Value::Binary(Vec::new()),
Duration::from_secs(5),
)
.unwrap();
let (result_tx, result_rx) = oneshot::channel();
let mut pending_requests = HashMap::from([(
request_id,
PendingSessionRequest {
sent_at: Instant::now(),
result_tx,
},
PendingSessionRequest::new(result_tx, RequestOptions::default(), true),
)]);
let packed_response = Link::pack_response(&request_id, b"resource response").unwrap();
let packed_response = Link::pack_response_value(
&request_id,
&rmpv::Value::Binary(b"resource response".to_vec()),
)
.unwrap();
let mut response_sender = OutboundTransfer::new_encrypted(
packed_response,
false,
@@ -4451,7 +4804,7 @@ mod tests {
1,
&mut initiator,
&mut resources,
&pending_requests,
&mut pending_requests,
InboundResourceSinks {
event_tx: &event_tx,
command_tx: &command_tx,
@@ -4523,6 +4876,88 @@ mod tests {
assert!(initiator.pending_requests.is_empty());
}
#[test]
fn spooled_response_is_removed_unless_a_requester_receives_it() {
let dir = std::env::temp_dir().join(format!(
"rns-response-spool-{}",
hex::encode(rns_crypto::random::random_bytes(8))
));
std::fs::create_dir(&dir).unwrap();
let queued = open_response_spool(&dir, &[7; 32]).unwrap();
let orphaned = open_response_spool(&dir, &[7; 32]).unwrap();
assert_ne!(queued.path, orphaned.path);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&queued.path)
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
// A completion still queued when the session ends.
discard_undelivered_spool(&LinkSessionCommand::RequestResourceReceived {
request_id: [1; 16],
result: Ok(LinkSessionReceivedResource {
link_id: [0; 16],
resource_id: [7; 32],
data: Vec::new(),
file: Some(queued.path.clone()),
metadata: Some(vec![0x80]),
total_segments: 1,
request_id: Some(vec![1; 16]),
is_request: false,
is_response: true,
}),
});
assert!(!queued.path.exists());
// A requester that stopped waiting.
let destination_hash = [0xBE; 16];
let server_signing = Ed25519PrivateKey::generate();
let server_public = server_signing.public_key();
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
let (_responder, proof_data) =
Link::new_responder(&request_data, &server_signing, destination_hash, 1).unwrap();
initiator
.validate_proof(&proof_data, &server_public, &server_public.to_bytes())
.unwrap();
let (_packed, request_id) = initiator
.prepare_request_value("/file", &rmpv::Value::Nil, Duration::from_secs(5))
.unwrap();
let (result_tx, result_rx) = oneshot::channel();
drop(result_rx);
let (progress_tx, progress_rx) = watch::channel(0.0);
let options = RequestOptions {
progress: Some(progress_tx),
..RequestOptions::default()
};
let mut pending_requests = HashMap::from([(
request_id,
PendingSessionRequest::new(result_tx, options, true),
)]);
let (event_tx, _event_rx) = mpsc::channel::<LinkSessionEvent>(8);
deliver_session_response(
&mut initiator,
&mut pending_requests,
&event_tx,
request_id,
ResponseBody {
data: Vec::new(),
value: rmpv::Value::Nil,
metadata: Some(vec![0x80]),
file: Some(orphaned.path.clone()),
},
);
assert!(!orphaned.path.exists());
assert!(pending_requests.is_empty());
assert_eq!(*progress_rx.borrow(), 1.0);
std::fs::remove_dir(&dir).unwrap();
}
#[tokio::test]
async fn session_actor_recovers_and_answers_data_received_after_stale() {
let destination_hash = [0xBD; 16];
@@ -5112,7 +5547,7 @@ mod tests {
let request_id =
rns_wire::hash::truncated_packet_hash(&request.raw, request_header.flags.header_type);
let response = responder
.create_response(&request_id, b"response body")
.create_response_value(&request_id, &rmpv::Value::Binary(b"response body".to_vec()))
.unwrap();
delivery_tx
.send(DestinationEvent::InboundPacket {
+122 -11
View File
@@ -30,6 +30,40 @@ pub struct ResourceOptions {
pub metadata: Option<Vec<u8>>,
}
/// Compression policy for request and response Resources, as Resource's
/// `auto_compress` option: a bool, or an int byte limit that enables
/// compression only for data no larger than the limit.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AutoCompress {
Off,
/// Compress data up to Resource.AUTO_COMPRESS_MAX_SIZE.
#[default]
On,
/// Compress data no larger than this many bytes.
Limit(usize),
}
impl AutoCompress {
pub fn is_enabled(self) -> bool {
!matches!(self, Self::Off)
}
/// Whether data of `data_size` bytes is compressed under this policy.
pub fn applies_to(self, data_size: usize) -> bool {
match self {
Self::Off => false,
Self::On => data_size <= rns_protocol::compression::AUTO_COMPRESS_MAX_SIZE,
Self::Limit(limit) => data_size <= limit,
}
}
}
impl From<bool> for AutoCompress {
fn from(value: bool) -> Self {
if value { Self::On } else { Self::Off }
}
}
#[derive(Debug, thiserror::Error)]
pub enum ResourceSourceError {
#[error("resource source I/O failed: {0}")]
@@ -56,13 +90,28 @@ pub(crate) enum ResourcePurpose {
#[default]
Ordinary,
Request([u8; 16]),
Response([u8; 16]),
}
impl ResourcePurpose {
fn apply(self, resource: &mut OutboundResource) {
if let Self::Request(request_id) = self {
resource.flags.is_request = true;
resource.request_id = Some(request_id.to_vec());
match self {
Self::Ordinary => {}
Self::Request(request_id) => {
resource.flags.is_request = true;
resource.request_id = Some(request_id.to_vec());
}
Self::Response(request_id) => {
resource.flags.is_response = true;
resource.request_id = Some(request_id.to_vec());
}
}
}
fn request_id(&self) -> Option<&[u8]> {
match self {
Self::Ordinary => None,
Self::Request(id) | Self::Response(id) => Some(id.as_slice()),
}
}
}
@@ -93,9 +142,10 @@ impl PreparedResourceSource {
where
S: ResourceSource + 'static,
{
Self::prepare_with_purpose(source, options, ResourcePurpose::Ordinary)
Self::prepare_with_purpose(source, options, None, ResourcePurpose::Ordinary)
}
/// Request bodies use Resource's default `auto_compress=True`.
pub(crate) fn prepare_request<S>(
source: S,
request_id: [u8; 16],
@@ -106,13 +156,50 @@ impl PreparedResourceSource {
Self::prepare_with_purpose(
source,
ResourceOptions::default(),
Some(AutoCompress::On),
ResourcePurpose::Request(request_id),
)
}
/// A response Resource correlated with `request_id`, as Link.handle_request
/// sends a file response. Compression is judged against the whole source
/// size, as Resource does for file input.
pub(crate) fn prepare_response<S>(
source: S,
request_id: [u8; 16],
metadata: Option<Vec<u8>>,
auto_compress: AutoCompress,
) -> Result<Self, ResourceSourceError>
where
S: ResourceSource + 'static,
{
Self::prepare_with_purpose(
source,
ResourceOptions {
auto_compress: false,
metadata,
},
Some(auto_compress),
ResourcePurpose::Response(request_id),
)
}
/// Whether every segment has been produced.
pub(crate) fn is_exhausted(&self) -> bool {
match self {
Self::Single { data, .. } => data.is_none(),
Self::Split {
total_segments,
next_segment,
..
} => next_segment >= total_segments,
}
}
fn prepare_with_purpose<S>(
mut source: S,
options: ResourceOptions,
mut options: ResourceOptions,
auto_compress: Option<AutoCompress>,
purpose: ResourcePurpose,
) -> Result<Self, ResourceSourceError>
where
@@ -124,21 +211,20 @@ impl PreparedResourceSource {
}
source.seek(SeekFrom::Start(0))?;
let data_size = data_size as usize;
if let Some(policy) = auto_compress {
options.auto_compress = policy.applies_to(data_size);
}
let metadata_wire_size = options
.metadata
.as_ref()
.map(|metadata| 3usize.saturating_add(metadata.len()))
.unwrap_or(0);
let request_id = match &purpose {
ResourcePurpose::Request(id) => Some(id.as_slice()),
ResourcePurpose::Ordinary => None,
};
rns_protocol::resource_control::preflight_outbound(
data_size,
options.metadata.as_ref().map(Vec::len),
request_id,
false,
purpose.request_id(),
matches!(purpose, ResourcePurpose::Response(_)),
true,
rns_wire::constants::MTU,
)?;
@@ -281,6 +367,8 @@ impl PreparedResourceSource {
)?;
purpose.apply(&mut resource);
resource.flags.split = true;
// Later segments advertise the metadata flag without carrying metadata.
resource.flags.has_metadata |= *metadata_wire_size > 0;
resource.segment_index = segment_index;
resource.total_segments = *total_segments;
resource.original_hash = Some(*original_hash);
@@ -317,6 +405,29 @@ mod tests {
LinkKeys::derive(&local, &remote.public_key(), &[0xA5; 16], MODE_AES256_CBC).unwrap()
}
#[test]
fn auto_compress_limit_follows_resource_option_types() {
assert!(!AutoCompress::from(false).applies_to(10));
assert!(AutoCompress::from(true).applies_to(10));
assert!(AutoCompress::Limit(1024).applies_to(1024));
assert!(!AutoCompress::Limit(1024).applies_to(1025));
assert!(
!AutoCompress::On.applies_to(rns_protocol::compression::AUTO_COMPRESS_MAX_SIZE + 1)
);
}
#[test]
fn request_source_is_compressed_by_default() {
let mut prepared =
PreparedResourceSource::prepare_request(Cursor::new(vec![0u8; 4096]), [7; 16]).unwrap();
let segment = prepared
.next_segment(&test_keys(), Duration::from_millis(100))
.unwrap()
.unwrap();
assert!(segment.transfer.resource.flags.compressed);
assert!(segment.transfer.resource.flags.is_request);
}
#[test]
fn small_source_prepares_one_segment() {
let mut prepared = PreparedResourceSource::prepare(
+3 -3
View File
@@ -334,7 +334,7 @@ pub async fn spawn_rncp_listener(
link_id,
reason: "not in allow-list".into(),
});
return RequestOutcome::Reply(vec![REQ_FETCH_NOT_ALLOWED]);
return RequestOutcome::ReplyValue(vec![REQ_FETCH_NOT_ALLOWED]);
}
}
}
@@ -358,11 +358,11 @@ pub async fn spawn_rncp_listener(
auto_compress,
}
}
Err(_) => RequestOutcome::Reply(vec![0xC2]), // msgpack `false`
Err(_) => RequestOutcome::ReplyValue(vec![0xC2]), // msgpack `false`
},
Err(reason) => {
let _ = fetch_events.try_send(RncpEvent::FetchDenied { link_id, reason });
RequestOutcome::Reply(vec![REQ_FETCH_NOT_ALLOWED])
RequestOutcome::ReplyValue(vec![REQ_FETCH_NOT_ALLOWED])
}
}
});