mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
runtime: deferred handlers declare memory use and a refusal reply
This commit is contained in:
1 parent
29db8b25b8
commit
ca7f2e9fa1
5 files changed
+488
-75
No files matched your search
@@ -21,7 +21,8 @@ use rns_runtime::config::ConfigError;
|
||||
use rns_runtime::destination_runtime::DestinationRuntimeOptions;
|
||||
use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
|
||||
use rns_runtime::link_manager::{
|
||||
DeferredRequestResponder, DestinationAnnounceOptions, DestinationRequest, RequestOutcome,
|
||||
DeferredAdmission, DeferredRequestResponder, DestinationAnnounceOptions, DestinationRequest,
|
||||
RequestOutcome,
|
||||
};
|
||||
use rns_tools::{LogLevel, RS_RETICULUM_VERSION};
|
||||
|
||||
@@ -30,6 +31,21 @@ const JOBS_INTERVAL: Duration = Duration::from_secs(5);
|
||||
/// Ceiling for a deferred reply held in memory: status bytes or file metadata.
|
||||
const REPLY_LIMIT: usize = 64 * 1024;
|
||||
|
||||
/// Admission for the git handlers: the manager's three copies of the request
|
||||
/// (payload, value, byte view) and a status-byte or file-backed reply; a refused
|
||||
/// job answers with `RES_REMOTE_FAIL` and a reason the remote helper prints.
|
||||
fn admission() -> DeferredAdmission {
|
||||
let refusal = |message: &str| {
|
||||
let mut reply = vec![rns_git::server::RES_REMOTE_FAIL];
|
||||
reply.extend_from_slice(message.as_bytes());
|
||||
reply
|
||||
};
|
||||
DeferredAdmission::new(REPLY_LIMIT)
|
||||
.request_copies(3)
|
||||
.busy_reply(refusal("Node busy, try again later"))
|
||||
.too_large_reply(refusal("Request too large for this node"))
|
||||
}
|
||||
|
||||
/// Bundle directories kept until their Link closes (`link.temporary_directories`).
|
||||
type LinkTempDirs = Arc<Mutex<HashMap<[u8; 16], Vec<tempfile::TempDir>>>>;
|
||||
|
||||
@@ -526,12 +542,12 @@ async fn main() {
|
||||
] {
|
||||
let ok = registered
|
||||
.handle
|
||||
.register_deferred_request_handler(
|
||||
.register_deferred_request_handler_with(
|
||||
path,
|
||||
AllowPolicy::AllowAll,
|
||||
Vec::new(),
|
||||
true,
|
||||
REPLY_LIMIT,
|
||||
admission(),
|
||||
deferred(repositories.clone(), tempdirs.clone(), handler),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -12,6 +12,93 @@ const JOBS: usize = 4;
|
||||
const BYTES: usize = 256 * 1024 * 1024;
|
||||
const SCRATCH: usize = 16 * 1024 * 1024;
|
||||
pub(crate) const MAX_RESPONSE: usize = 64 * 1024 * 1024;
|
||||
/// Largest refusal reply; it always fits one RESPONSE packet on a default Link.
|
||||
pub const MAX_REFUSAL_REPLY: usize = 256;
|
||||
const DEFAULT_REQUEST_COPIES: usize = 16;
|
||||
const DEFAULT_RESPONSE_COPIES: usize = 8;
|
||||
|
||||
/// How a deferred handler's job is charged against the process-wide budget
|
||||
/// (four jobs, 256 MiB), and what a refused requester is told.
|
||||
///
|
||||
/// A job is charged `request_copies` times the request capacity, plus 16 MiB of
|
||||
/// Resource construction scratch, plus `response_copies` times the effective
|
||||
/// response limit. The defaults (16 and 8, no refusal replies) are the
|
||||
/// conservative charge for a handler whose reply can be a large in-memory
|
||||
/// Resource. A handler that holds fewer copies, or whose large replies are
|
||||
/// file-backed ([`RequestOutcome::ReplyFile`] streams one segment at a time
|
||||
/// within the scratch allowance), can declare lower counts. Declarations change
|
||||
/// what one job costs, never the global job count or byte cap.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DeferredAdmission {
|
||||
response_byte_limit: usize,
|
||||
request_copies: usize,
|
||||
response_copies: usize,
|
||||
busy_reply: Option<Vec<u8>>,
|
||||
too_large_reply: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl DeferredAdmission {
|
||||
/// Today's default accounting with a ceiling for an in-memory reply.
|
||||
pub fn new(response_byte_limit: usize) -> Self {
|
||||
Self {
|
||||
response_byte_limit,
|
||||
request_copies: DEFAULT_REQUEST_COPIES,
|
||||
response_copies: DEFAULT_RESPONSE_COPIES,
|
||||
busy_reply: None,
|
||||
too_large_reply: None,
|
||||
}
|
||||
}
|
||||
/// Copies of the request held while the job runs. The manager itself holds
|
||||
/// three (reassembled payload, decoded value and byte view) at admission.
|
||||
pub fn request_copies(mut self, copies: usize) -> Self {
|
||||
self.request_copies = copies;
|
||||
self
|
||||
}
|
||||
/// Response buffers charged per byte of the effective response limit.
|
||||
pub fn response_copies(mut self, copies: usize) -> Self {
|
||||
self.response_copies = copies;
|
||||
self
|
||||
}
|
||||
/// Bytes sent as the response when the job count or the remaining budget
|
||||
/// refuses a job. Without it the request is dropped with no response.
|
||||
pub fn busy_reply(mut self, reply: Vec<u8>) -> Self {
|
||||
self.busy_reply = Some(reply);
|
||||
self
|
||||
}
|
||||
/// Bytes sent as the response when the request can never fit the budget.
|
||||
/// Without it the request is dropped with no response.
|
||||
pub fn too_large_reply(mut self, reply: Vec<u8>) -> Self {
|
||||
self.too_large_reply = Some(reply);
|
||||
self
|
||||
}
|
||||
pub fn response_byte_limit(&self) -> usize {
|
||||
self.response_byte_limit
|
||||
}
|
||||
pub(crate) fn is_valid(&self) -> bool {
|
||||
self.response_byte_limit > 0
|
||||
&& self.response_byte_limit <= MAX_RESPONSE
|
||||
&& self.request_copies > 0
|
||||
&& self.response_copies > 0
|
||||
&& [&self.busy_reply, &self.too_large_reply]
|
||||
.iter()
|
||||
.all(|reply| reply.as_ref().is_none_or(|r| r.len() <= MAX_REFUSAL_REPLY))
|
||||
}
|
||||
pub(crate) fn refusal_reply(&self, refusal: AdmissionRefusal) -> Option<&[u8]> {
|
||||
match refusal {
|
||||
AdmissionRefusal::Busy => self.busy_reply.as_deref(),
|
||||
AdmissionRefusal::TooLarge => self.too_large_reply.as_deref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why admission refused a deferred job.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum AdmissionRefusal {
|
||||
/// All jobs are taken or the remaining budget is too small.
|
||||
Busy,
|
||||
/// The job exceeds the budget even when nothing else runs.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DeferredResponseOutcome {
|
||||
@@ -28,7 +115,7 @@ pub enum DeferredResponseError {
|
||||
#[error("response allocation exceeds the admitted byte limit")]
|
||||
TooLarge,
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
struct Counts {
|
||||
jobs: usize,
|
||||
bytes: usize,
|
||||
@@ -58,10 +145,11 @@ struct State {
|
||||
/// dropping a caller's async task must not detach an uncharged blocking job.
|
||||
///
|
||||
/// The effective response limit can be lower than the registered ceiling. The
|
||||
/// reservation includes sixteen times request capacity, eight response buffers and 16 MiB of
|
||||
/// construction scratch. This is a conservative bound for the current Resource
|
||||
/// construction path, not a claim that unrelated application allocations are
|
||||
/// globally capped. Responses must fit by allocation capacity, not just length.
|
||||
/// reservation follows the handler's [`DeferredAdmission`]: by default sixteen
|
||||
/// times request capacity, eight response buffers and 16 MiB of construction
|
||||
/// scratch. This bounds the Resource construction path, not unrelated
|
||||
/// application allocations. Responses must fit by allocation capacity, not just
|
||||
/// length.
|
||||
#[derive(Debug)]
|
||||
pub struct DeferredRequestResponder {
|
||||
state: Arc<State>,
|
||||
@@ -154,29 +242,29 @@ impl Drop for PendingResponse {
|
||||
}
|
||||
pub(crate) fn reserve(
|
||||
input_capacity: usize,
|
||||
requested_limit: usize,
|
||||
admission: &DeferredAdmission,
|
||||
notify: Arc<Notify>,
|
||||
) -> Option<(DeferredRequestResponder, PendingResponse)> {
|
||||
) -> Result<(DeferredRequestResponder, PendingResponse), AdmissionRefusal> {
|
||||
static GLOBAL: OnceLock<Arc<Mutex<Counts>>> = OnceLock::new();
|
||||
reserve_with(
|
||||
GLOBAL
|
||||
.get_or_init(|| Arc::new(Mutex::new(Counts::default())))
|
||||
.clone(),
|
||||
input_capacity,
|
||||
requested_limit,
|
||||
admission,
|
||||
notify,
|
||||
)
|
||||
}
|
||||
fn reserve_with(
|
||||
counts: Arc<Mutex<Counts>>,
|
||||
input_capacity: usize,
|
||||
requested_limit: usize,
|
||||
admission: &DeferredAdmission,
|
||||
notify: Arc<Notify>,
|
||||
) -> Option<(DeferredRequestResponder, PendingResponse)> {
|
||||
) -> Result<(DeferredRequestResponder, PendingResponse), AdmissionRefusal> {
|
||||
reserve_with_deadline(
|
||||
counts,
|
||||
input_capacity,
|
||||
requested_limit,
|
||||
admission,
|
||||
notify,
|
||||
Instant::now() + LIFETIME,
|
||||
)
|
||||
@@ -184,20 +272,30 @@ fn reserve_with(
|
||||
fn reserve_with_deadline(
|
||||
counts: Arc<Mutex<Counts>>,
|
||||
input_capacity: usize,
|
||||
requested_limit: usize,
|
||||
admission: &DeferredAdmission,
|
||||
notify: Arc<Notify>,
|
||||
deadline: Instant,
|
||||
) -> Option<(DeferredRequestResponder, PendingResponse)> {
|
||||
let overhead = input_capacity.checked_mul(16)?.checked_add(SCRATCH)?;
|
||||
let limit = requested_limit.min(BYTES.checked_sub(overhead)? / 8);
|
||||
) -> Result<(DeferredRequestResponder, PendingResponse), AdmissionRefusal> {
|
||||
let too_large = AdmissionRefusal::TooLarge;
|
||||
let response_copies = admission.response_copies.max(1);
|
||||
let overhead = input_capacity
|
||||
.checked_mul(admission.request_copies.max(1))
|
||||
.and_then(|n| n.checked_add(SCRATCH))
|
||||
.ok_or(too_large)?;
|
||||
let limit = admission
|
||||
.response_byte_limit
|
||||
.min(BYTES.checked_sub(overhead).ok_or(too_large)? / response_copies);
|
||||
if limit == 0 {
|
||||
return None;
|
||||
return Err(too_large);
|
||||
}
|
||||
let bytes = limit.checked_mul(8)?.checked_add(overhead)?;
|
||||
let bytes = limit
|
||||
.checked_mul(response_copies)
|
||||
.and_then(|n| n.checked_add(overhead))
|
||||
.ok_or(too_large)?;
|
||||
{
|
||||
let mut counts = counts.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if counts.jobs >= JOBS || bytes > BYTES.saturating_sub(counts.bytes) {
|
||||
return None;
|
||||
return Err(AdmissionRefusal::Busy);
|
||||
}
|
||||
counts.jobs += 1;
|
||||
counts.bytes += bytes;
|
||||
@@ -210,7 +308,7 @@ fn reserve_with_deadline(
|
||||
lease: Arc::new(RequestLease { counts, bytes }),
|
||||
});
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
Some((
|
||||
Ok((
|
||||
DeferredRequestResponder {
|
||||
state: state.clone(),
|
||||
sender: Some(sender),
|
||||
@@ -225,8 +323,13 @@ mod tests {
|
||||
#[test]
|
||||
fn closed_request_keeps_worker_credit_and_rejects_late_response() {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
let (worker, mut pending) =
|
||||
reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap();
|
||||
let (worker, mut pending) = reserve_with(
|
||||
counts.clone(),
|
||||
10,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new()),
|
||||
)
|
||||
.unwrap();
|
||||
pending.close(DeferredResponseOutcome::Closed);
|
||||
drop(pending);
|
||||
assert_eq!(counts.lock().unwrap().jobs, 1);
|
||||
@@ -244,9 +347,25 @@ mod tests {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
let mut jobs = Vec::new();
|
||||
for _ in 0..4 {
|
||||
jobs.push(reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap());
|
||||
jobs.push(
|
||||
reserve_with(
|
||||
counts.clone(),
|
||||
10,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new()),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert!(reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).is_none());
|
||||
assert!(
|
||||
reserve_with(
|
||||
counts.clone(),
|
||||
10,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new())
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let (worker, pending) = jobs.pop().unwrap();
|
||||
let bytes = Vec::with_capacity(101);
|
||||
assert_eq!(
|
||||
@@ -256,18 +375,42 @@ mod tests {
|
||||
DeferredResponseError::TooLarge
|
||||
);
|
||||
drop(pending);
|
||||
assert!(reserve_with(counts, 10, 100, Arc::new(Notify::new())).is_some());
|
||||
assert!(
|
||||
reserve_with(
|
||||
counts,
|
||||
10,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new())
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn expired_and_oversized_requests_never_acquire_send_authority() {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
assert!(reserve_with(counts.clone(), usize::MAX, 100, Arc::new(Notify::new())).is_none());
|
||||
assert!(reserve_with(counts.clone(), BYTES / 16, 100, Arc::new(Notify::new())).is_none());
|
||||
assert!(
|
||||
reserve_with(
|
||||
counts.clone(),
|
||||
usize::MAX,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new())
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
reserve_with(
|
||||
counts.clone(),
|
||||
BYTES / 16,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new())
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(counts.lock().unwrap().jobs, 0);
|
||||
let (worker, pending) = reserve_with_deadline(
|
||||
counts.clone(),
|
||||
1,
|
||||
100,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new()),
|
||||
Instant::now() - Duration::from_secs(1),
|
||||
)
|
||||
@@ -286,8 +429,13 @@ mod tests {
|
||||
#[test]
|
||||
fn queued_result_and_resource_owner_retain_credit() {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
let (worker, mut pending) =
|
||||
reserve_with(counts.clone(), 10, 100, Arc::new(Notify::new())).unwrap();
|
||||
let (worker, mut pending) = reserve_with(
|
||||
counts.clone(),
|
||||
10,
|
||||
&DeferredAdmission::new(100),
|
||||
Arc::new(Notify::new()),
|
||||
)
|
||||
.unwrap();
|
||||
let mut ack = worker.respond(RequestOutcome::ReplyBytes(vec![1])).unwrap();
|
||||
assert_eq!(counts.lock().unwrap().jobs, 1);
|
||||
let resolution = pending.try_recv().unwrap();
|
||||
@@ -302,4 +450,101 @@ mod tests {
|
||||
drop(resource_lease);
|
||||
assert_eq!(counts.lock().unwrap().jobs, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_accounting_sets_the_charge_and_default_keeps_todays() {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
let input = 1024 * 1024;
|
||||
let default = reserve_with(
|
||||
counts.clone(),
|
||||
input,
|
||||
&DeferredAdmission::new(1000),
|
||||
Arc::new(Notify::new()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
counts.lock().unwrap().bytes,
|
||||
16 * input + SCRATCH + 8 * 1000
|
||||
);
|
||||
drop(default);
|
||||
let declared = DeferredAdmission::new(1000)
|
||||
.request_copies(3)
|
||||
.response_copies(2);
|
||||
let job = reserve_with(counts.clone(), input, &declared, Arc::new(Notify::new())).unwrap();
|
||||
assert_eq!(counts.lock().unwrap().bytes, 3 * input + SCRATCH + 2 * 1000);
|
||||
drop(job);
|
||||
assert_eq!(counts.lock().unwrap().bytes, 0);
|
||||
// A 40 MiB request is refused by the default charge and fits as declared.
|
||||
let push = 40 * 1024 * 1024;
|
||||
assert!(matches!(
|
||||
reserve_with(
|
||||
counts.clone(),
|
||||
push,
|
||||
&DeferredAdmission::new(1000),
|
||||
Arc::new(Notify::new())
|
||||
),
|
||||
Err(AdmissionRefusal::TooLarge)
|
||||
));
|
||||
assert!(reserve_with(counts, push, &declared, Arc::new(Notify::new())).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_accounting_never_exceeds_the_global_bound() {
|
||||
let counts = Arc::new(Mutex::new(Counts::default()));
|
||||
let light = DeferredAdmission::new(1)
|
||||
.request_copies(1)
|
||||
.response_copies(1);
|
||||
let mut jobs = Vec::new();
|
||||
for _ in 0..JOBS {
|
||||
jobs.push(reserve_with(counts.clone(), 0, &light, Arc::new(Notify::new())).unwrap());
|
||||
}
|
||||
assert!(matches!(
|
||||
reserve_with(counts.clone(), 0, &light, Arc::new(Notify::new())),
|
||||
Err(AdmissionRefusal::Busy)
|
||||
));
|
||||
jobs.clear();
|
||||
// Two large jobs that each fit alone cannot run together: 130 MiB of
|
||||
// request plus scratch is 146 MiB, so the second exceeds 256 MiB.
|
||||
let big = 130 * 1024 * 1024;
|
||||
let first = reserve_with(counts.clone(), big, &light, Arc::new(Notify::new())).unwrap();
|
||||
assert!(matches!(
|
||||
reserve_with(counts.clone(), big, &light, Arc::new(Notify::new())),
|
||||
Err(AdmissionRefusal::Busy)
|
||||
));
|
||||
assert!(counts.lock().unwrap().bytes <= BYTES);
|
||||
drop(first);
|
||||
assert!(matches!(
|
||||
reserve_with(counts.clone(), BYTES, &light, Arc::new(Notify::new())),
|
||||
Err(AdmissionRefusal::TooLarge)
|
||||
));
|
||||
assert_eq!(*counts.lock().unwrap(), Counts::default());
|
||||
// Zero counts are rejected at registration and cannot reach admission as zero.
|
||||
assert!(!DeferredAdmission::new(1).request_copies(0).is_valid());
|
||||
assert!(!DeferredAdmission::new(1).response_copies(0).is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusal_replies_are_bounded_and_matched_to_the_refusal() {
|
||||
let admission = DeferredAdmission::new(100)
|
||||
.busy_reply(b"busy".to_vec())
|
||||
.too_large_reply(b"large".to_vec());
|
||||
assert!(admission.is_valid());
|
||||
assert_eq!(
|
||||
admission.refusal_reply(AdmissionRefusal::Busy),
|
||||
Some(&b"busy"[..])
|
||||
);
|
||||
assert_eq!(
|
||||
admission.refusal_reply(AdmissionRefusal::TooLarge),
|
||||
Some(&b"large"[..])
|
||||
);
|
||||
assert_eq!(
|
||||
DeferredAdmission::new(100).refusal_reply(AdmissionRefusal::Busy),
|
||||
None
|
||||
);
|
||||
assert!(
|
||||
!DeferredAdmission::new(100)
|
||||
.busy_reply(vec![0; MAX_REFUSAL_REPLY + 1])
|
||||
.is_valid()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -20,11 +20,11 @@ use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::link_manager::{
|
||||
ChannelSendError, ChannelSendReceipt, DeferredRequestResponder, DestinationAnnounceOptions,
|
||||
DestinationControlError, DestinationRequest, LinkChannelMessage, LinkManager,
|
||||
LinkManagerCommand, LinkPacketProof, LinkPacketSendReceipt, LinkPayloadSendReceipt,
|
||||
LinkResourceEvent, LinkResourceProof, LinkResourceSendReceipt, LinkSendError, RequestOutcome,
|
||||
ResourceCompletion,
|
||||
ChannelSendError, ChannelSendReceipt, DeferredAdmission, DeferredRequestResponder,
|
||||
DestinationAnnounceOptions, DestinationControlError, DestinationRequest, LinkChannelMessage,
|
||||
LinkManager, LinkManagerCommand, LinkPacketProof, LinkPacketSendReceipt,
|
||||
LinkPayloadSendReceipt, LinkResourceEvent, LinkResourceProof, LinkResourceSendReceipt,
|
||||
LinkSendError, RequestOutcome, ResourceCompletion,
|
||||
};
|
||||
|
||||
const DEFAULT_EVENT_CAPACITY: usize = 128;
|
||||
@@ -336,6 +336,32 @@ impl DestinationHandle {
|
||||
response_byte_limit: usize,
|
||||
handler: F,
|
||||
) -> Result<bool, DestinationRuntimeError>
|
||||
where
|
||||
F: Fn(DestinationRequest, DeferredRequestResponder) + Send + 'static,
|
||||
{
|
||||
self.register_deferred_request_handler_with(
|
||||
path,
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
DeferredAdmission::new(response_byte_limit),
|
||||
handler,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// [`Self::register_deferred_request_handler`] with declared admission
|
||||
/// accounting and refusal replies. See
|
||||
/// [`LinkManager::register_deferred_request_handler_with`].
|
||||
pub async fn register_deferred_request_handler_with<F>(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
allow: AllowPolicy,
|
||||
allowed_list: Vec<[u8; 16]>,
|
||||
auto_compress: impl Into<crate::resource_source::AutoCompress>,
|
||||
admission: DeferredAdmission,
|
||||
handler: F,
|
||||
) -> Result<bool, DestinationRuntimeError>
|
||||
where
|
||||
F: Fn(DestinationRequest, DeferredRequestResponder) + Send + 'static,
|
||||
{
|
||||
@@ -346,7 +372,7 @@ impl DestinationHandle {
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress: auto_compress.into(),
|
||||
response_byte_limit,
|
||||
admission,
|
||||
handler: Box::new(handler),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
|
||||
@@ -42,7 +42,9 @@ pub mod prelude {
|
||||
RegisteredDestination, ResourceAcceptPolicy,
|
||||
};
|
||||
pub use crate::lifecycle::ShutdownSignal;
|
||||
pub use crate::link_manager::{DestinationAnnounceOptions, DestinationRequest, RequestOutcome};
|
||||
pub use crate::link_manager::{
|
||||
DeferredAdmission, DestinationAnnounceOptions, DestinationRequest, RequestOutcome,
|
||||
};
|
||||
pub use crate::link_session::{
|
||||
LinkSession, LinkSessionChannelError, LinkSessionChannelHandle, LinkSessionCloseReason,
|
||||
LinkSessionError, LinkSessionEvent, LinkSessionHandle, LinkSessionResourceError,
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub use crate::deferred_request::{
|
||||
DeferredRequestResponder, DeferredResponseError, DeferredResponseOutcome,
|
||||
DeferredAdmission, DeferredRequestResponder, DeferredResponseError, DeferredResponseOutcome,
|
||||
};
|
||||
use crate::inbound_link_packet::{
|
||||
APPLICATION_PACKET_LIFETIME, Decision, PacketDispatch, PacketEpoch, PendingInboundPacket,
|
||||
@@ -672,7 +672,7 @@ pub enum LinkManagerCommand {
|
||||
allow: AllowPolicy,
|
||||
allowed_list: Vec<[u8; 16]>,
|
||||
auto_compress: AutoCompress,
|
||||
response_byte_limit: usize,
|
||||
admission: DeferredAdmission,
|
||||
handler: DeferredRequestHandler,
|
||||
result_tx: Option<oneshot::Sender<bool>>,
|
||||
},
|
||||
@@ -921,7 +921,7 @@ type DeferredRequestHandler =
|
||||
enum RegisteredHandler {
|
||||
Immediate(DestinationRequestHandler),
|
||||
Deferred {
|
||||
response_byte_limit: usize,
|
||||
admission: DeferredAdmission,
|
||||
handler: DeferredRequestHandler,
|
||||
},
|
||||
}
|
||||
@@ -2640,16 +2640,16 @@ impl LinkManager {
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
response_byte_limit,
|
||||
admission,
|
||||
handler,
|
||||
result_tx,
|
||||
} => {
|
||||
let result = self.register_deferred_request_handler(
|
||||
let result = self.register_deferred_request_handler_with(
|
||||
&path,
|
||||
allow,
|
||||
Some(allowed_list),
|
||||
auto_compress,
|
||||
response_byte_limit,
|
||||
admission,
|
||||
handler,
|
||||
);
|
||||
if let Some(tx) = result_tx {
|
||||
@@ -6518,10 +6518,7 @@ impl LinkManager {
|
||||
RegisteredHandler::Immediate(handler) => {
|
||||
run_request_handler(link_id, request_id, || handler(request))
|
||||
}
|
||||
RegisteredHandler::Deferred {
|
||||
response_byte_limit,
|
||||
handler,
|
||||
} => {
|
||||
RegisteredHandler::Deferred { admission, handler } => {
|
||||
let Some(generation) =
|
||||
self.active_endpoint_generations.get(&link_id).copied()
|
||||
else {
|
||||
@@ -6538,28 +6535,43 @@ impl LinkManager {
|
||||
.active_links
|
||||
.get(&link_id)
|
||||
.and_then(|a| a.interface_owner);
|
||||
let Some((responder, response)) = crate::deferred_request::reserve(
|
||||
match crate::deferred_request::reserve(
|
||||
request.data.capacity(),
|
||||
*response_byte_limit,
|
||||
admission,
|
||||
self.deferred_request_notify.clone(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.pending_deferred_requests.push(PendingDeferredRequest {
|
||||
link_id,
|
||||
request_id,
|
||||
path_hash,
|
||||
generation,
|
||||
owner,
|
||||
auto_compress: response_auto_compress,
|
||||
response,
|
||||
});
|
||||
// A panicking handler drops its responder, which closes the request.
|
||||
let _ = run_request_handler(link_id, request_id, || {
|
||||
handler(request, responder);
|
||||
RequestOutcome::Drop
|
||||
});
|
||||
return;
|
||||
) {
|
||||
Ok((responder, response)) => {
|
||||
self.pending_deferred_requests.push(PendingDeferredRequest {
|
||||
link_id,
|
||||
request_id,
|
||||
path_hash,
|
||||
generation,
|
||||
owner,
|
||||
auto_compress: response_auto_compress,
|
||||
response,
|
||||
});
|
||||
// A panicking handler drops its responder, which closes the request.
|
||||
let _ = run_request_handler(link_id, request_id, || {
|
||||
handler(request, responder);
|
||||
RequestOutcome::Drop
|
||||
});
|
||||
return;
|
||||
}
|
||||
Err(refusal) => {
|
||||
tracing::debug!(
|
||||
link_id = hex::encode(link_id),
|
||||
request_id = hex::encode(request_id),
|
||||
path = %registered.path,
|
||||
?refusal,
|
||||
"deferred request refused by admission"
|
||||
);
|
||||
// A refusal reply is small and owns no budget.
|
||||
match admission.refusal_reply(refusal) {
|
||||
Some(reply) => RequestOutcome::ReplyBytes(reply.to_vec()),
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -7168,6 +7180,9 @@ impl LinkManager {
|
||||
/// for a zero or greater-than-64-MiB response limit. At most four process-wide jobs or
|
||||
/// Resources share 256 MiB of conservative reservations. This is an admission
|
||||
/// budget, not a limit on arbitrary worker allocations or side effects.
|
||||
/// A refused request is dropped with no response; see
|
||||
/// [`Self::register_deferred_request_handler_with`] to declare accounting
|
||||
/// and refusal replies.
|
||||
pub fn register_deferred_request_handler<F>(
|
||||
&mut self,
|
||||
path: &str,
|
||||
@@ -7180,11 +7195,33 @@ impl LinkManager {
|
||||
where
|
||||
F: Fn(DestinationRequest, DeferredRequestResponder) + Send + 'static,
|
||||
{
|
||||
if self.endpoint_dispatch.is_none()
|
||||
|| path.is_empty()
|
||||
|| response_byte_limit == 0
|
||||
|| response_byte_limit > crate::deferred_request::MAX_RESPONSE
|
||||
{
|
||||
self.register_deferred_request_handler_with(
|
||||
path,
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
DeferredAdmission::new(response_byte_limit),
|
||||
handler,
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Self::register_deferred_request_handler`] with declared admission
|
||||
/// accounting and optional refusal replies. Registration also fails for a
|
||||
/// zero copy count or a refusal reply over
|
||||
/// [`crate::deferred_request::MAX_REFUSAL_REPLY`] bytes.
|
||||
pub fn register_deferred_request_handler_with<F>(
|
||||
&mut self,
|
||||
path: &str,
|
||||
allow: AllowPolicy,
|
||||
allowed_list: Option<Vec<[u8; 16]>>,
|
||||
auto_compress: impl Into<AutoCompress>,
|
||||
admission: DeferredAdmission,
|
||||
handler: F,
|
||||
) -> bool
|
||||
where
|
||||
F: Fn(DestinationRequest, DeferredRequestResponder) + Send + 'static,
|
||||
{
|
||||
if self.endpoint_dispatch.is_none() || path.is_empty() || !admission.is_valid() {
|
||||
return false;
|
||||
}
|
||||
let allowed_list = allowed_list.unwrap_or_default();
|
||||
@@ -7205,7 +7242,7 @@ impl LinkManager {
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
handler: RegisteredHandler::Deferred {
|
||||
response_byte_limit,
|
||||
admission,
|
||||
handler: Box::new(handler),
|
||||
},
|
||||
},
|
||||
@@ -11451,6 +11488,93 @@ mod tests {
|
||||
raw
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refused_deferred_request_answers_with_the_declared_reply() {
|
||||
let (mut sender, receiver) = handshaken_link_pair();
|
||||
let link_id = receiver.link_id;
|
||||
let (mut actor, _actor_tx) = rns_transport::actor::TransportActor::new();
|
||||
let (driver_tx, _driver_rx) = mpsc::channel(16);
|
||||
actor.interfaces.insert(
|
||||
1,
|
||||
rns_transport::messages::InterfaceEntry::new(
|
||||
"deferred refusal test".into(),
|
||||
rns_transport::constants::InterfaceMode::Full,
|
||||
rns_transport::constants::InterfaceDirection::bidirectional(),
|
||||
1_000_000,
|
||||
500,
|
||||
driver_tx,
|
||||
),
|
||||
);
|
||||
let interface_owner = Some(actor.interfaces[&1].owner.id());
|
||||
let dispatch = actor.link_endpoint_dispatch_handle();
|
||||
let _actor_task = tokio::spawn(actor.run());
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(32);
|
||||
let (_event_tx, event_rx) = mpsc::channel(8);
|
||||
let mut manager = LinkManager::new(transport_tx, event_rx, [0x92; 16], None);
|
||||
manager.active_links.insert(
|
||||
link_id,
|
||||
ActiveLink {
|
||||
link: receiver,
|
||||
_interface_id: 1,
|
||||
interface_owner,
|
||||
endpoint_authority: None,
|
||||
channel: None,
|
||||
inbound_resources: HashMap::new(),
|
||||
outbound_resources: HashMap::new(),
|
||||
outbound_split_queues: HashMap::new(),
|
||||
inbound_split_resources: HashMap::new(),
|
||||
segment_routing: HashMap::new(),
|
||||
},
|
||||
);
|
||||
manager.set_link_endpoint_dispatch_handle(dispatch.clone());
|
||||
own_test_endpoint(&mut manager, link_id);
|
||||
let authority = dispatch
|
||||
.try_bind(
|
||||
manager.owned_endpoint_bindings[&link_id].binding,
|
||||
manager.endpoint_lifecycle_tx.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
manager.endpoint_dispatch_tokens.insert(link_id, authority);
|
||||
manager.active_endpoint_generations.insert(link_id, 7);
|
||||
let called = Arc::new(AtomicBool::new(false));
|
||||
let handler_called = called.clone();
|
||||
// Default accounting charges sixteen copies of the request, so a 17 MiB
|
||||
// request can never fit the 256 MiB budget.
|
||||
assert!(
|
||||
manager.register_deferred_request_handler_with(
|
||||
"/push",
|
||||
AllowPolicy::AllowAll,
|
||||
None,
|
||||
false,
|
||||
DeferredAdmission::new(4096)
|
||||
.busy_reply(b"\xffbusy".to_vec())
|
||||
.too_large_reply(b"\xfftoo large".to_vec()),
|
||||
move |_, _| handler_called.store(true, Ordering::SeqCst),
|
||||
)
|
||||
);
|
||||
let path = truncated_hash(b"/push");
|
||||
manager.handle_parsed_request(
|
||||
link_id,
|
||||
[1; 16],
|
||||
path,
|
||||
0.0,
|
||||
rmpv::Value::Binary(vec![0u8; 17 * 1024 * 1024]),
|
||||
);
|
||||
assert!(!called.load(Ordering::SeqCst));
|
||||
assert!(manager.pending_deferred_requests.is_empty());
|
||||
let TransportMessage::Outbound(packet) = next_transport_message(&mut transport_rx).unwrap()
|
||||
else {
|
||||
panic!("refusal response packet")
|
||||
};
|
||||
let (_, offset) = rns_wire::header::PacketHeader::unpack(&packet.raw).unwrap();
|
||||
let (request, response) = sender.handle_response(&packet.raw[offset..]).unwrap();
|
||||
assert_eq!(request, [1; 16]);
|
||||
assert_eq!(response, b"\xfftoo large");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deferred_requests_keep_owner_and_resource_reservations() {
|
||||
let (mut sender, receiver) = handshaken_link_pair();
|
||||
|
||||
Reference in new issue
Block a user