use super::*;
pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
"reloading",
"supervisor_not_live",
"registration_not_active",
"no_forwarding_connection",
"relay_send_failed",
];
pub(super) struct RouteOpenRequest {
pub(super) target: RouteTarget,
pub(super) identity: BindIdentity,
pub(super) consumer_identity: Option<ConsumerIdentity>,
pub(super) consumer_capabilities: Option<Vec<String>>,
pub(super) role_versions: Option<BTreeMap<String, String>>,
pub(super) busy_refusals: Option<bool>,
pub(super) admission_facts: Option<serde_json::Value>,
pub(super) scope: Option<ScopeSelector>,
pub(super) accepts_close_reasons: Option<Vec<String>>,
}
#[derive(Clone, Copy)]
enum RouteOpenPhase {
Admission,
ProjectRoot,
EgressReservation,
BindSend,
BindAckWait,
}
pub(super) struct RouteOpenTimings {
pub(super) module_id: String,
pub(super) principal: String,
pub(super) admission: Duration,
pub(super) project_root: Duration,
pub(super) egress_reservation: Duration,
pub(super) bind_send: Duration,
pub(super) bind_ack_wait: Duration,
phase: Option<RouteOpenPhase>,
phase_started_at: Instant,
}
impl RouteOpenTimings {
pub(super) fn new() -> Self {
Self {
module_id: String::new(),
principal: "unresolved".to_string(),
admission: Duration::ZERO,
project_root: Duration::ZERO,
egress_reservation: Duration::ZERO,
bind_send: Duration::ZERO,
bind_ack_wait: Duration::ZERO,
phase: Some(RouteOpenPhase::Admission),
phase_started_at: Instant::now(),
}
}
pub(super) fn finish(&mut self) {
let elapsed = self.phase_started_at.elapsed();
match self.phase.take() {
Some(RouteOpenPhase::Admission) => self.admission += elapsed,
Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
None => {}
}
}
fn enter(&mut self, phase: RouteOpenPhase) {
self.finish();
self.phase = Some(phase);
self.phase_started_at = Instant::now();
}
}
struct RouteBindReservationGuard {
forwarding: Arc<ForwardingTable>,
endpoint: ModuleEndpointId,
relay_corr: u64,
armed: bool,
}
impl RouteBindReservationGuard {
fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
Self {
forwarding,
endpoint,
relay_corr,
armed: true,
}
}
fn release_and_disarm(&mut self) {
if !self.armed {
return;
}
if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
self.endpoint,
self.relay_corr,
RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
) {
send_goodbye_target_best_effort(
&self.forwarding.counters(),
&target,
"canceled route.bind",
);
}
self.armed = false;
}
fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for RouteBindReservationGuard {
fn drop(&mut self) {
self.release_and_disarm();
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct RouteBindBreakers {
modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct RouteBindConcurrency {
state: Arc<Mutex<RouteBindConcurrencyState>>,
}
#[derive(Debug, Default)]
struct RouteBindConcurrencyState {
modules: HashMap<String, usize>,
upgrade_producers: Option<tokio::sync::watch::Sender<usize>>,
}
pub(super) struct RouteBindConcurrencyGuard {
concurrency: RouteBindConcurrency,
module_id: String,
}
impl RouteBindConcurrency {
pub(super) fn try_admit(
&self,
module_id: &str,
limit: usize,
) -> Result<RouteBindConcurrencyGuard, usize> {
let mut state = self
.state
.lock()
.expect("route.bind concurrency mutex poisoned");
let in_flight = state.modules.entry(module_id.to_string()).or_default();
if *in_flight >= limit {
return Err(*in_flight);
}
*in_flight += 1;
if let Some(producers) = &state.upgrade_producers {
producers.send_modify(|count| *count += 1);
}
Ok(RouteBindConcurrencyGuard {
concurrency: self.clone(),
module_id: module_id.to_string(),
})
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn track_upgrade_producers(&self) -> tokio::sync::watch::Receiver<usize> {
let mut state = self
.state
.lock()
.expect("route.bind concurrency mutex poisoned");
let (sender, receiver) = tokio::sync::watch::channel(state.modules.values().sum());
state.upgrade_producers = Some(sender);
receiver
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn clear_upgrade_producers(&self) {
self.state
.lock()
.expect("route.bind concurrency mutex poisoned")
.upgrade_producers = None;
}
}
impl Drop for RouteBindConcurrencyGuard {
fn drop(&mut self) {
let mut state = self
.concurrency
.state
.lock()
.expect("route.bind concurrency mutex poisoned");
let remove = {
let in_flight = state
.modules
.get_mut(&self.module_id)
.expect("admitted route.bind has a concurrency entry");
*in_flight -= 1;
*in_flight == 0
};
if remove {
state.modules.remove(&self.module_id);
}
if let Some(producers) = &state.upgrade_producers {
producers.send_modify(|count| *count -= 1);
}
}
}
#[derive(Debug, Default)]
struct ModuleBreakerState {
consecutive_timeouts: u32,
cooldown_until: Option<Instant>,
probe_in_flight: Option<Arc<()>>,
}
pub(super) enum RouteBindAdmission<'a> {
Admitted {
guard: RouteBindBreakerGuard<'a>,
probe: bool,
},
Refused {
consecutive_timeouts: u32,
retry_in: Duration,
probe_in_flight: bool,
},
}
pub(super) struct RouteBindBreakerGuard<'a> {
breakers: RouteBindBreakers,
module_id: &'a str,
probe_token: Option<Arc<()>>,
settled: bool,
}
impl RouteBindBreakerGuard<'_> {
fn record_accepted(&mut self) -> bool {
self.settled = true;
self.breakers.record_accepted(self.module_id)
}
pub(super) fn record_timeout(
&mut self,
threshold: u32,
cooldown: Duration,
) -> Option<BreakerOpened> {
self.settled = true;
self.breakers.record_timeout(
self.module_id,
self.probe_token.as_ref(),
threshold,
cooldown,
)
}
pub(super) fn record_inconclusive(&mut self) {
self.settled = true;
self.breakers
.record_inconclusive(self.module_id, self.probe_token.as_ref());
}
}
impl Drop for RouteBindBreakerGuard<'_> {
fn drop(&mut self) {
if !self.settled {
self.breakers
.record_inconclusive(self.module_id, self.probe_token.as_ref());
}
}
}
pub(super) struct BreakerOpened {
consecutive_timeouts: u32,
pub(super) reopened_after_probe: bool,
}
impl RouteBindBreakers {
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
self.modules
.lock()
.expect("route.bind breaker mutex poisoned")
}
pub(super) fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
probe: probe_token.is_some(),
guard: RouteBindBreakerGuard {
breakers: self.clone(),
module_id,
probe_token,
settled: false,
},
};
let mut modules = self.lock();
let Some(state) = modules.get_mut(module_id) else {
return admitted(None);
};
let Some(cooldown_until) = state.cooldown_until else {
return admitted(None);
};
if state.probe_in_flight.is_some() {
return RouteBindAdmission::Refused {
consecutive_timeouts: state.consecutive_timeouts,
retry_in: Duration::ZERO,
probe_in_flight: true,
};
}
let now = Instant::now();
if now < cooldown_until {
return RouteBindAdmission::Refused {
consecutive_timeouts: state.consecutive_timeouts,
retry_in: cooldown_until - now,
probe_in_flight: false,
};
}
let token = Arc::new(());
state.probe_in_flight = Some(Arc::clone(&token));
admitted(Some(token))
}
fn record_accepted(&self, module_id: &str) -> bool {
self.lock()
.remove(module_id)
.is_some_and(|state| state.cooldown_until.is_some())
}
pub(super) fn record_timeout(
&self,
module_id: &str,
probe_token: Option<&Arc<()>>,
threshold: u32,
cooldown: Duration,
) -> Option<BreakerOpened> {
let mut modules = self.lock();
let state = modules.entry(module_id.to_string()).or_default();
let was_open = state.cooldown_until.is_some();
let was_probe = Self::owns_probe(state, probe_token);
if was_probe {
state.probe_in_flight = None;
}
state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
if state.consecutive_timeouts < threshold {
return None;
}
state.cooldown_until = Some(Instant::now() + cooldown);
Some(BreakerOpened {
consecutive_timeouts: state.consecutive_timeouts,
reopened_after_probe: was_open && was_probe,
})
}
fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
state
.probe_in_flight
.as_ref()
.zip(token)
.is_some_and(|(active, token)| Arc::ptr_eq(active, token))
}
fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
if let Some(state) = self.lock().get_mut(module_id) {
if Self::owns_probe(state, probe_token) {
state.probe_in_flight = None;
}
}
}
pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
self.lock()
.remove(module_id)
.map(|state| state.consecutive_timeouts)
.filter(|discarded| *discarded > 0)
}
pub(super) fn open_snapshot(&self) -> Option<serde_json::Value> {
let now = Instant::now();
let modules = self.lock();
let open = modules
.iter()
.filter_map(|(module_id, state)| {
let cooldown_until = state.cooldown_until?;
Some((
module_id.clone(),
serde_json::json!({
"consecutive_timeouts": state.consecutive_timeouts,
"cooldown_remaining_ms":
cooldown_until.saturating_duration_since(now).as_millis() as u64,
"probe_in_flight": state.probe_in_flight.is_some(),
}),
))
})
.collect::<serde_json::Map<String, serde_json::Value>>();
(!open.is_empty()).then_some(serde_json::Value::Object(open))
}
}
impl ControlHandler {
fn deliver_route_open_fence_refusal(&self, ctx: &RouteCtx, refusal: Frame) -> Vec<Frame> {
match self
.forwarding
.upgrade_refusals
.track_fence_refusal(refusal)
{
Ok(tracked) => {
tracked.send(&ctx.egress);
Vec::new()
}
Err(refusal) => vec![refusal],
}
}
pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
self.route_bind_relay_timeout = timeout;
self
}
pub fn with_route_bind_relay_timeouts(
mut self,
timeouts: impl IntoIterator<Item = (String, Duration)>,
) -> Self {
self.route_bind_relay_timeouts = timeouts.into_iter().collect();
self
}
pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
self.route_bind_relay_timeouts
.get(module_id)
.copied()
.unwrap_or(self.route_bind_relay_timeout)
}
pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
self.route_bind_breaker_threshold = threshold.max(1);
self.route_bind_breaker_cooldown = cooldown;
self
}
}
impl ControlHandler {
#[cfg(test)]
pub(crate) fn with_route_bind_relay_sent_hold(
mut self,
hold: Arc<tokio::sync::Barrier>,
) -> Self {
self.route_bind_relay_sent_hold = Some(hold);
self
}
}
impl ControlHandler {
pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
return None;
}
let Ok(ClientControlRequest::RouteOpen { target, .. }) =
parse_client_control_request(&frame.body)
else {
return None;
};
Some(target_module_id(&target).to_string())
}
pub(crate) fn route_open_capacity_refusal(
&self,
ctx: &RouteCtx,
frame: &Frame,
target_module_id: &str,
in_flight: usize,
limit: usize,
) -> Result<Frame, RouterError> {
let caller = self.route_open_caller_from_frame(ctx, frame);
self.route_open_admission_refusal_frame(
ctx,
&caller,
frame,
target_module_id,
"open_admission_full",
(in_flight, limit),
format!(
"connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
),
)
}
pub(super) fn route_open_target_capacity_refusal(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
target_module_id: &str,
in_flight: usize,
) -> Result<Frame, RouterError> {
self.route_open_admission_refusal_frame(
ctx,
caller,
frame,
target_module_id,
"target_binds_full",
(in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
format!(
"module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
),
)
}
#[allow(clippy::too_many_arguments)]
fn route_open_admission_refusal_frame(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
target_module_id: &str,
reason: &'static str,
(in_flight, limit): (usize, usize),
message: impl Into<String>,
) -> Result<Frame, RouterError> {
let code = error_codes::TARGET_UNAVAILABLE;
self.counters.increment_route_open_refused(code);
info!(
target: "control",
code,
reason,
module_id = ?target_module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
in_flight,
limit,
"route.open refused"
);
control_error_frame(frame, code, message.into())
}
}
impl ControlHandler {
fn send_abandoned_route_bind_goodbye(
&self,
module_sink: &crate::FrameSink,
negotiated_ver: u8,
module_channel: u16,
module_epoch: u32,
) {
let frame = match Frame::build_with_version(
negotiated_ver,
FrameType::Goodbye,
control_flags(),
module_channel,
module_epoch,
0,
Vec::new(),
) {
Ok(frame) => frame,
Err(err) => {
warn!(
route_channel = module_channel,
error = %err,
"failed to build GOODBYE for abandoned route.bind"
);
return;
}
};
crate::forwarding::send_module_route_goodbye(
&self.counters,
module_sink,
frame,
None,
"abandoned route.bind",
);
}
}
impl ControlHandler {
fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
let Ok(ClientControlRequest::RouteOpen {
identity,
consumer_identity,
scope,
..
}) = parse_client_control_request(&frame.body)
else {
return RouteOpenCaller::unknown();
};
let principal = self
.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
.map(|attested| attested.principal);
RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
}
pub(super) fn route_open_principal(
&self,
connection_id: ConnectionId,
frame: &Frame,
consumer_identity: Option<ConsumerIdentity>,
) -> Result<Result<Principal, Frame>, RouterError> {
let attested = self
.attest_route_open_consumer(connection_id, consumer_identity.as_ref())
.map(|attested| attested.principal);
self.route_open_principal_attested(frame, consumer_identity, attested)
}
fn route_open_principal_attested(
&self,
frame: &Frame,
consumer_identity: Option<ConsumerIdentity>,
attested: Option<Principal>,
) -> Result<Result<Principal, Frame>, RouterError> {
if let Some(principal) = attested {
return Ok(Ok(principal));
}
Ok(Err(control_error_frame(
frame,
"bad_consumer_identity",
consumer_identity.map_or_else(
|| "connection claim is no longer authorized for routes".to_string(),
|identity| format!(
"consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
identity.module_id
),
),
)?))
}
#[allow(clippy::too_many_arguments)]
pub(super) fn route_open_refusal_frame(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
module_id: &str,
reason: &'static str,
code: &'static str,
message: impl Into<String>,
) -> Result<Frame, RouterError> {
self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
let detail = if reason == "daemon_upgrade" {
Some(serde_json::json!({"reason": "daemon_upgrade"}))
} else if matches!(
reason,
"registration_not_active"
| "supervisor_not_live"
| "no_forwarding_connection"
| "reloading"
) {
let expected_back = (reason == "reloading").then_some(true);
self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
} else {
None
};
control_error_body_frame(
frame,
ErrorBody {
code: code.to_string(),
message: message.into(),
detail,
},
)
}
fn route_open_recovery_detail(
&self,
module_id: &str,
corr: u64,
detail: Option<serde_json::Value>,
expected_back: Option<bool>,
) -> Result<Option<serde_json::Value>, RouterError> {
let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
return Ok(detail);
};
let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
detail["state"] = serde_json::json!(status.state.to_string());
if let Some(expected_back) = expected_back {
detail["expected_back"] = serde_json::json!(expected_back);
} else if let Some(module) = self.supervisor.get(module_id) {
match module.will_recover_after_connection_loss() {
Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
Err(err) => warn!(
%module_id,
error = %err,
"failed to read route.open recovery verdict; omitting expected_back"
),
}
}
Ok(Some(detail))
}
#[allow(clippy::too_many_arguments)]
fn route_bind_rejection(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
target_module_id: &str,
body: ErrorBody,
daemon_authored: bool,
) -> Result<Vec<Frame>, RouterError> {
if daemon_authored {
let scope_code = match body.code.as_str() {
error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
_ => None,
};
if let Some(code) = scope_code {
self.observe_route_open_refusal(
ctx,
caller,
target_module_id,
"scope_changed_before_commit",
code,
);
return Ok(vec![control_error_body_frame(frame, body)?]);
}
}
self.counters
.increment_route_open_refused("module_rejected");
info!(
target: "control",
code = "module_rejected",
module_code = ?body.code,
module_id = ?target_module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
"route.open refused"
);
let refusal = if daemon_authored {
control_error_body_frame(frame, body)?
} else {
control_relayed_error_body_frame(frame, body)?
};
Ok(vec![refusal])
}
#[allow(clippy::too_many_arguments)]
fn route_open_breaker_refusal_frame(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
module_id: &str,
consecutive_timeouts: u32,
retry_in: Duration,
probe_in_flight: bool,
) -> Result<Frame, RouterError> {
self.counters
.increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
debug!(
target: "control",
code = "module_timeout",
module_id = ?module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
consecutive_timeouts,
retry_in_ms = retry_in.as_millis() as u64,
probe_in_flight,
"route.open refused by open bind-relay breaker"
);
let detail = if probe_in_flight {
"one test route is already being tried; retry once it settles".to_string()
} else {
format!("retrying new routes in {}s", retry_in.as_secs().max(1))
};
control_error_frame(
frame,
"module_timeout",
format!(
"module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
timed out in a row); {detail}; its established routes are unaffected"
),
)
}
fn observe_route_open_refusal(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
module_id: &str,
reason: &'static str,
code: &'static str,
) {
self.counters.increment_route_open_refused(code);
self.route_refusal_log
.record(module_id, code, reason, caller, ctx.connection_id.get());
if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
self.route_outages.record_not_serving(module_id, reason);
}
}
fn observe_route_open_accept(
&self,
ctx: &RouteCtx,
module_id: &str,
principal: &str,
scope: &str,
) {
self.route_outages.record_accepted(module_id);
self.counters.increment_route_open_accepted(principal);
debug!(
target: "control",
principal,
module_id,
connection_id = ctx.connection_id.get(),
scope = %scope,
"route.open accepted"
);
}
fn supervised_absent_route_open_refusal_frame(
&self,
ctx: &RouteCtx,
caller: &RouteOpenCaller,
frame: &Frame,
module_id: &str,
code: &'static str,
status: &crate::supervise::ModuleStatus,
) -> Result<Frame, RouterError> {
self.counters.increment_route_open_refused(code);
info!(
target: "control",
code,
reason = "supervised_not_registered",
module_id = ?module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
state = %status.state,
enabled = status.enabled,
live = status.live,
"route.open refused"
);
self.route_outages
.record_not_serving(module_id, "supervised_not_registered");
let message = if let Some(pid) = status.waiting_for_previous_pid {
status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
})
} else {
format!(
"module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
status.state, status.enabled, status.live
)
};
let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
control_error_body_frame(
frame,
ErrorBody {
code: code.to_string(),
message,
detail: self.route_open_recovery_detail(
module_id,
frame.header.corr,
None,
expected_back,
)?,
},
)
}
pub(super) async fn handle_route_open(
&self,
ctx: &RouteCtx,
frame: Frame,
request: RouteOpenRequest,
timings: &mut RouteOpenTimings,
) -> Result<Vec<Frame>, RouterError> {
let RouteOpenRequest {
target,
mut identity,
consumer_identity,
consumer_capabilities,
role_versions,
busy_refusals,
admission_facts,
scope,
accepts_close_reasons,
} = request;
let target_module_id = target_module_id(&target).to_string();
timings.module_id.clone_from(&target_module_id);
if self
.registry
.get_module_by_connection(ctx.connection_id)
.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
.is_some()
{
return Ok(vec![control_error_frame(
&frame,
"invalid_request",
"module connections cannot open client routes",
)?]);
}
debug!(
connection_id = ctx.connection_id.get(),
corr = frame.header.corr,
module_id = %target_module_id,
"handling route.open"
);
let attested =
self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
let mut caller = RouteOpenCaller::new(
attested.as_ref().map(|attested| &attested.principal),
scope.as_ref(),
&identity,
);
let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
self.observe_route_open_refusal(
ctx,
&caller,
&target_module_id,
"invalid_role_versions",
error_codes::INVALID_REQUEST,
);
return Ok(vec![control_error_body_frame(
&frame,
ErrorBody {
code: error_codes::INVALID_REQUEST.to_string(),
message: error.to_string(),
detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
},
)?]);
}
if self.forwarding.upgrade_admission.phase().fenced()
|| self.supervisor.adoption_blocks(&target_module_id)
{
let refusal = self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"daemon_upgrade",
"module_reloading",
"module is awaiting daemon upgrade recovery",
)?;
return Ok(self.deliver_route_open_fence_refusal(ctx, refusal));
}
if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
if status.waiting_for_previous_pid.is_some() {
return Ok(vec![self.supervised_absent_route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"module_warming",
&status,
)?]);
}
}
let admission_registry = self
.registry
.route_admission_snapshot()
.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
let Some(registration) =
crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
else {
if let Some((status, warming)) =
self.supervisor_status(&target_module_id, frame.header.corr)?
{
if status.protocol == ModuleProtocol::None {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"protocol_none",
error_codes::MODULE_NO_PROTOCOL,
format!(
"module_id '{target_module_id}' is declared protocol: none; \
it speaks no subc wire and serves no routes"
),
)?]);
}
let code = if warming {
"module_warming"
} else {
"target_unavailable"
};
return Ok(vec![self.supervised_absent_route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
code,
&status,
)?]);
}
if let Some(removed_ago_ms) =
self.supervisor.removal_tombstone_age_ms(&target_module_id)
{
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"removed",
error_codes::MODULE_REMOVED,
format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
)?]);
}
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"not_registered",
error_codes::UNKNOWN_MODULE,
format!("module_id '{target_module_id}' is not registered"),
)?]);
};
if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
.is_err()
{
self.counters
.increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
info!(
target: "control",
code = error_codes::MODULE_WARMING,
module_id = ?target_module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
reason = "declared_not_ready",
"route.open refused"
);
self.route_outages
.record_not_serving(&target_module_id, "declared_not_ready");
return Ok(vec![control_error_body_frame(
&frame,
ErrorBody {
code: error_codes::MODULE_WARMING.to_string(),
message: format!(
"module_id '{target_module_id}' is registered and has declared itself not ready; retry"
),
detail: self.route_open_recovery_detail(
&target_module_id,
frame.header.corr,
Some(serde_json::json!({ "reason": "declared_not_ready" })),
Some(true),
)?,
},
)?]);
}
if let Some(capability) = self.first_unprovided_required_capability_for(
®istration.module_id,
registration.capabilities.as_ref(),
) {
self.counters
.increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
info!(
target: "control",
code = error_codes::MODULE_WARMING,
module_id = ?target_module_id,
connection_id = ctx.connection_id.get(),
principal = %caller.principal,
scope = %caller.scope,
harness = %caller.harness,
reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
capability = %capability,
"route.open refused"
);
return Ok(vec![control_error_body_frame(
&frame,
ErrorBody {
code: error_codes::MODULE_WARMING.to_string(),
message: format!(
"module_id '{target_module_id}' requires capability '{capability}', \
which no registered module provides; retry"
),
detail: Some(serde_json::json!({
"reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
"capability": capability,
})),
},
)?]);
}
if !target_has_required_role(&target, ®istration.roles) {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"role_not_provided",
"target_unavailable",
format!("module_id '{target_module_id}' does not provide the requested target"),
)?]);
}
if registration.state != ChannelState::Active {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"registration_not_active",
"target_unavailable",
format!("module_id '{target_module_id}' is not active"),
)?]);
}
if self
.forwarding
.module_is_draining(&target_module_id)
.map_err(RouterError::Forwarding)?
{
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"reloading",
"module_reloading",
format!("module_id '{target_module_id}' is reloading"),
)?]);
}
if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
process_liveness.process_live(&target_module_id) == Some(false)
}) {
if process_liveness.process_replacing(&target_module_id) {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"reloading",
"module_reloading",
format!("module_id '{target_module_id}' is reloading"),
)?]);
}
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"supervisor_not_live",
"target_unavailable",
format!("module_id '{target_module_id}' is not live"),
)?]);
}
if !self
.forwarding
.has_live_module_connection(&target_module_id)
.map_err(RouterError::Forwarding)?
{
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"no_forwarding_connection",
"target_unavailable",
format!("module_id '{target_module_id}' has no live forwarding connection"),
)?]);
}
if let Some(error) =
self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
{
self.observe_route_open_refusal(
ctx,
&caller,
&target_module_id,
"op_not_allowed",
"op_not_allowed",
);
return Ok(vec![error]);
}
let principal = match (&attested, consumer_identity.is_some()) {
(None, false) => {
self.observe_route_open_refusal(
ctx,
&caller,
&target_module_id,
"registration_channel_closed",
crate::supervise::REGISTRATION_CHANNEL_CLOSED,
);
return Ok(vec![control_error_frame(
&frame,
crate::supervise::REGISTRATION_CHANNEL_CLOSED,
"the claim binding's launch has ended",
)?]);
}
_ => match self.route_open_principal_attested(
&frame,
consumer_identity,
attested.as_ref().map(|attested| attested.principal.clone()),
)? {
Ok(principal) => principal,
Err(error) => {
self.observe_route_open_refusal(
ctx,
&caller,
&target_module_id,
"bad_consumer_identity",
"bad_consumer_identity",
);
return Ok(vec![error]);
}
},
};
let attested = attested.expect("an attested principal was resolved above");
timings.principal = principal_label(&principal);
let Ok(mut caller_capture) = attested.capture() else {
self.observe_route_open_refusal(
ctx,
&caller,
&target_module_id,
"registration_channel_closed",
crate::supervise::REGISTRATION_CHANNEL_CLOSED,
);
return Ok(vec![control_error_frame(
&frame,
crate::supervise::REGISTRATION_CHANNEL_CLOSED,
"the opener's launch has ended",
)?]);
};
let caller_module_id = match &attested.spawn {
Some((record, _)) => Some(record.module_id().to_owned()),
None => match &principal {
Principal::Reserved { module_id } => Some(module_id.clone()),
_ => None,
},
};
let build_class = identity.build_class.take().filter(|build_class| {
if caller_module_id.as_deref() == Some("callosum") {
build_class == subc_protocol::BUILD_CLASS_PRODUCTION
} else {
if self
.build_class_warned
.lock()
.unwrap_or_else(|p| p.into_inner())
.insert(ctx.connection_id)
{
warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
"ignoring build_class from a non-Callosum opener");
}
false
}
});
let opening_registration = self.caller_registration(&attested, &admission_registry);
if let Some(opening_registration) = &opening_registration {
let opening_module_id = opening_registration.module_id.as_str();
if let Some(capability) = denied_capability(
opening_registration.capabilities.as_ref(),
registration.capabilities.as_ref(),
) {
warn!(
opening_module_id,
target_module_id,
capability,
"refusing route.open because an attested capability deny edge matches"
);
return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
&frame,
&target_module_id,
"capability_deny_edge",
"capability_forbidden",
format!(
"module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
),
)?]);
}
}
if admission_facts.is_some() {
let carrier_matches = caller_module_id.is_some()
&& self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
if !carrier_matches {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"admission_facts_carrier_not_permitted",
"admission_facts_not_permitted",
"admission facts may only be carried by the configured reserved module",
)?]);
}
let target_allowed = self
.admission_facts_targets
.as_ref()
.is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
if !target_allowed {
return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
&frame,
&target_module_id,
"admission_facts_target_not_listed",
"admission_facts_target_not_allowed",
format!(
"admission facts are not permitted for target module_id '{target_module_id}'"
),
)?]);
}
}
let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
None => (None, None, false),
Some(selector) => {
let owner_configured = match &selector.owner {
Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
_ => false,
};
let mut scopes = self
.scopes
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let admitted = crate::scopes::admission::admit_route(
&scopes,
&admission_registry,
&principal,
&target_module_id,
Some(selector),
owner_configured,
crate::scopes::admission::AdmissionMode::Open,
)
.map(|route| {
let admission = route.scope.expect("scoped admission");
let bound = scopes.reserve_bind(
&admission,
&principal,
ctx.connection_id,
selector.hold_presence,
);
(admission, bound)
});
match admitted {
Ok((admission, bound)) => {
(Some(bound), Some(admission.stamp), admission.stamp_required)
}
Err(refusal) => {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
refusal.message,
)?]);
}
}
}
};
if let Some(stamp) = &scope_stamp {
caller.scope = route_open_scope_label(stamp);
}
if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
}
timings.enter(RouteOpenPhase::ProjectRoot);
let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
Ok(project) => project,
Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
};
timings.enter(RouteOpenPhase::Admission);
let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
Ok(root) => root,
Err(err) => {
return Ok(vec![control_error_frame(
&frame,
"invalid_project_root",
err.to_string(),
)?])
}
};
let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
let _concurrency_guard = match self
.route_bind_concurrency
.try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
{
Ok(guard) => guard,
Err(in_flight) => {
return Ok(vec![self.route_open_target_capacity_refusal(
ctx,
&caller,
&frame,
&target_module_id,
in_flight,
)?]);
}
};
let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
RouteBindAdmission::Admitted { guard, probe } => {
if probe {
info!(
module_id = %target_module_id,
connection_id = ctx.connection_id.get(),
"route.bind breaker half-open: admitting one probe"
);
}
guard
}
RouteBindAdmission::Refused {
consecutive_timeouts,
retry_in,
probe_in_flight,
} => {
return Ok(vec![self.route_open_breaker_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
consecutive_timeouts,
retry_in,
probe_in_flight,
)?]);
}
};
let operator_app = self
.route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
.await;
let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
let relay_deadline = Instant::now() + route_bind_relay_timeout;
let production_peer_build =
build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
timings.enter(RouteOpenPhase::EgressReservation);
let pending = match self
.forwarding
.begin_route_bind_relay_for(
ctx.connection_id,
ctx.egress.clone(),
response_version(&frame),
frame.header.corr,
&target_module_id,
principal.clone(),
bound_scope,
project_root,
identity.harness.clone(),
build_class,
operator_app.clone(),
crate::forwarding::RouteAuthority {
incarnation: self.supervisor.daemon_incarnation(),
caller: caller_capture
.as_ref()
.map(|caller| caller.authority.pair()),
capability_fence: route_bind_settlement::fence(
&opening_registration,
registration,
),
},
relay_deadline,
busy_refusals == Some(true),
accepts_close_reasons,
)
.await
{
Ok(pending) => pending,
Err(err) => {
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"relay_reservation_failed",
forwarding_error_code(&err),
err.to_string(),
)?])
}
};
timings.enter(RouteOpenPhase::Admission);
let crate::forwarding::PendingRouteBindRelay {
endpoint,
module_sink,
negotiated_ver,
client_channel,
client_epoch,
module_channel,
module_epoch,
corr: relay_corr,
receiver,
} = pending;
let mut reservation =
RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
let relay_registration = self
.registry
.route_registration_by_connection(endpoint.connection_id)
.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
let relay_capabilities = relay_registration
.as_ref()
.and_then(|registration| registration.capabilities.as_ref());
if let Some(selector) = &scope {
if let Err(refusal) = self
.scopes
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.check_bind_proof(&principal, selector)
{
reservation.release_and_disarm();
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
refusal.code,
refusal.code,
refusal.message,
)?]);
}
}
if let Some(stamp) = scope_stamp.as_ref() {
if let Err(refusal) = crate::scopes::check_target_required_stamp(
stamp_required,
&target_module_id,
relay_capabilities,
)
.and_then(|()| {
crate::scopes::check_target_flow_support(
stamp,
&target_module_id,
relay_capabilities,
)
})
.and_then(|()| {
crate::scopes::check_target_agent_run_support(
stamp,
&target_module_id,
relay_capabilities,
)
}) {
reservation.release_and_disarm();
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
refusal.code,
refusal.code,
refusal.message,
)?]);
}
}
let caller_attestation = self.caller_for_target(
caller_capture.as_ref(),
relay_capabilities,
&target_module_id,
&principal,
scope_stamp
.as_ref()
.and_then(|stamp| stamp.project_id.as_deref()),
);
if scope_stamp
.as_ref()
.is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
&& !crate::scopes::target_supports_federated(relay_capabilities)
{
scope_stamp = None;
}
if !relay_capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
}) {
if let Some(stamp) = scope_stamp.as_mut() {
stamp.workdir = None;
stamp.project_id = None;
}
}
let worker_run = scope_stamp
.as_ref()
.is_some_and(crate::scopes::is_worker_run)
&& relay_capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
});
if !worker_run
&& !relay_capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
})
{
if let Some(stamp) = scope_stamp.as_mut() {
stamp.attributes.on_behalf_of_agent = None;
}
}
if !relay_capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
}) {
if let Some(stamp) = scope_stamp.as_mut() {
stamp.attributes.flow_version = None;
stamp.attributes.flow_code_hash = None;
stamp.attributes.flow_install_id = None;
}
}
let call_mode = if worker_run
|| relay_capabilities
.is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
{
Some(derive_call_mode(scope_stamp.as_ref()))
} else {
if let Some(stamp) = scope_stamp.as_mut() {
stamp.expires_at_ms = None;
}
None
};
debug!(
connection_id = ctx.connection_id.get(),
client_channel,
client_epoch,
module_channel,
module_epoch,
"reserved route handle pair"
);
let route_principal_label = principal_label(&principal);
let relay = ModuleControlRequest::RouteBind {
route_channel: module_channel,
epoch: module_epoch,
target,
identity,
principal: Some(principal),
consumer_capabilities,
role_versions,
admission_facts,
scope: scope_stamp,
call_mode,
};
let peer = RouteBindPeer::new()
.with_observed_peer(
relay_capabilities
.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == OBSERVED_PEER_CAPABILITY)
})
.then(|| {
self.observed_peers
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&ctx.connection_id)
.cloned()
.unwrap_or_else(ObservedPeer::unobserved)
}),
)
.with_operator_app(
self.connection_operator_app(operator_app.as_ref())
.filter(|_| {
relay_capabilities.is_some_and(|caps| {
caps.provides
.iter()
.any(|cap| cap == OPERATOR_APP_CAPABILITY)
})
}),
)
.with_caller(caller_attestation)
.with_peer_build(
(production_peer_build
&& relay_capabilities.is_some_and(|caps| {
caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
}))
.then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
);
let relay_body = crate::bind_compat::encode_bind(
&relay,
&peer,
&legacy_bind_project,
relay_capabilities,
)
.map_err(|err| {
RouterError::backend(
0,
frame.header.corr,
format!("failed to encode route.bind request: {err}"),
)
})?;
let relay_frame = Frame::build_with_version(
negotiated_ver,
FrameType::Request,
control_flags(),
0,
0,
relay_corr,
relay_body,
)
.map_err(RouterError::FrameBuild)?;
timings.enter(RouteOpenPhase::BindSend);
let sent = timeout_at(
relay_deadline,
module_sink.send_upgrade_fenced(
relay_frame,
RouterError::DaemonUpgrade {
channel: 0,
epoch: 0,
corr: frame.header.corr,
},
),
)
.await;
timings.enter(RouteOpenPhase::Admission);
let Ok(sent) = sent else {
reservation.release_and_disarm();
breaker.record_inconclusive();
return Ok(vec![self.unsent_bind_timeout_refusal(
ctx,
&caller,
&frame,
&target_module_id,
)?]);
};
if let Err(err) = sent {
reservation.release_and_disarm();
if matches!(err, RouterError::DaemonUpgrade { .. }) {
breaker.record_inconclusive();
let refusal = self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"daemon_upgrade",
"module_reloading",
"daemon upgrade has fenced route admission",
)?;
return Ok(self.deliver_route_open_fence_refusal(ctx, refusal));
}
return Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"relay_send_failed",
"target_unavailable",
err.to_string(),
)?]);
}
#[cfg(test)]
if let Some(hold) = &self.route_bind_relay_sent_hold {
hold.wait().await;
hold.wait().await;
}
if self
.forwarding
.mark_route_bind_relay_enqueued(endpoint, relay_corr)
.map_err(RouterError::Forwarding)?
== crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
{
self.send_abandoned_route_bind_goodbye(
&module_sink,
negotiated_ver,
module_channel,
module_epoch,
);
}
timings.enter(RouteOpenPhase::BindAckWait);
let outcome = timeout_at(relay_deadline, receiver).await;
timings.enter(RouteOpenPhase::Admission);
match outcome {
Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
reservation.disarm();
if breaker.record_accepted() {
info!(
module_id = %target_module_id,
"route.bind breaker closed: the probe was accepted"
);
}
self.observe_route_open_accept(
ctx,
&target_module_id,
&route_principal_label,
&caller.scope,
);
Ok(Vec::new())
}
Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
reservation.release_and_disarm();
breaker.record_inconclusive();
self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
}
Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
reservation.release_and_disarm();
breaker.record_inconclusive();
self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
}
Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
reservation.release_and_disarm();
breaker.record_inconclusive();
tracing::warn!(
module_id = %target_module_id,
"route.bind relay abandoned: {message}"
);
Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"relay_abandoned",
"target_unavailable",
message,
)?])
}
Ok(Err(_)) => {
reservation.release_and_disarm();
breaker.record_inconclusive();
Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"relay_waiter_canceled",
"target_unavailable",
"route.bind relay waiter was canceled before the module responded",
)?])
}
Err(_) => {
reservation.release_and_disarm();
if let Some(opened) = breaker.record_timeout(
self.route_bind_breaker_threshold,
self.route_bind_breaker_cooldown,
) {
warn!(
module_id = %target_module_id,
consecutive_timeouts = opened.consecutive_timeouts,
cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
reopened_after_probe = opened.reopened_after_probe,
"route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
);
}
tracing::warn!(
module_id = %target_module_id,
timeout_ms = route_bind_relay_timeout.as_millis() as u64,
"route.bind relay timed out: module did not ack within budget"
);
Ok(vec![self.route_open_refusal_frame(
ctx,
&caller,
&frame,
&target_module_id,
"relay_timed_out",
"module_timeout",
format!(
"module_id '{target_module_id}' did not answer route.bind within {:?}",
route_bind_relay_timeout
),
)?])
}
}
}
}
fn target_module_id(target: &RouteTarget) -> &str {
match target {
RouteTarget::ToolProvider { module_id }
| RouteTarget::ManagementSurface { module_id }
| RouteTarget::InternalService { module_id, .. } => module_id,
}
}
fn target_has_required_role(
target: &RouteTarget,
roles: &[crate::registry::AdmissionRole],
) -> bool {
use crate::registry::AdmissionRole;
roles.iter().any(|role| match (target, role) {
(RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
(RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
(
RouteTarget::InternalService { service_id, .. },
AdmissionRole::InternalService(provided),
) => service_id == provided,
_ => false,
})
}
pub(super) fn is_routable_role(role: &ProviderRole) -> bool {
matches!(
role,
ProviderRole::ToolProvider { .. }
| ProviderRole::ManagementSurface { .. }
| ProviderRole::InternalService { .. }
)
}
pub(super) struct RouteOpenCaller {
pub(super) principal: String,
pub(super) scope: String,
pub(super) harness: String,
}
impl RouteOpenCaller {
fn new(
principal: Option<&Principal>,
scope: Option<&ScopeSelector>,
identity: &BindIdentity,
) -> Self {
Self {
principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
harness: bounded_log_text(&identity.harness),
}
}
pub(super) fn unknown() -> Self {
Self {
principal: "unknown".to_string(),
scope: "unknown".to_string(),
harness: "unknown".to_string(),
}
}
}
const MAX_LOGGED_TEXT_CHARS: usize = 64;
fn bounded_log_text(value: &str) -> String {
let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
bounded.push('…');
}
format!("{bounded:?}")
}
fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
use subc_protocol::scope::ScopeKind;
let kind = match stamp.kind {
ScopeKind::Head => "head",
ScopeKind::Worker => "worker",
ScopeKind::Ephemeral => "ephemeral",
ScopeKind::Federated => "federated",
_ => "unknown",
};
format!(
"{kind}/{}/{}@{}",
principal_label(&stamp.owner),
bounded_log_text(&stamp.scope_ref),
stamp.scope_epoch
)
}
fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
let epoch = selector
.scope_epoch
.map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
format!(
"requested/{}/{}@{epoch}",
bounded_log_text(&principal_label(&selector.owner)),
bounded_log_text(&selector.scope_ref),
)
}
pub(super) fn principal_label(principal: &Principal) -> String {
match principal {
Principal::Reserved { module_id } => format!("reserved:{module_id}"),
Principal::Direct => "direct".to_string(),
other => format!("{other:?}"),
}
}