From e0e8c2f7c46ed1644a7b00647fd85818fad8a8da Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 2 Dec 2026 14:31:44 -0800 Subject: [PATCH 1/2] fix(ingress): keep application routes stable as shared fleets grow Replace per-renewal Sandbox LISTs with a metadata-watch locator and fresh point reads, bound parallel discovery collection, and expose configurable supervisor connection budgets. Fixes #6181 Signed-off-by: Taylor Mutch --- crates/openshell-core/src/app_listener.rs | 36 +++ crates/openshell-driver-kubernetes/README.md | 8 + .../src/app_endpoint_index.rs | 179 ++++++++++++++ .../src/app_endpoint_index/tests.rs | 96 ++++++++ .../src/app_endpoint_lookup_tests.rs | 93 +++++++ .../src/app_listener.rs | 15 ++ .../openshell-driver-kubernetes/src/config.rs | 1 + .../openshell-driver-kubernetes/src/driver.rs | 80 +++++- .../src/image_update_tests.rs | 1 + crates/openshell-driver-kubernetes/src/lib.rs | 1 + .../src/lifecycle_tests.rs | 1 + .../src/grpc/mutation_replay/tests.rs | 2 + crates/openshell-server/src/grpc/service.rs | 5 + .../src/grpc/service_advertisement.rs | 23 +- .../src/grpc/service_discovery.rs | 231 ++++++++++-------- .../openshell-server/src/service_routing.rs | 1 + .../src/supervisor_session.rs | 30 ++- crates/openshell-supervisor/README.md | 7 + .../openshell-supervisor/src/app_listener.rs | 68 +++++- .../helm/openshell/templates/supervisor.yaml | 4 + docs/how-it-works/gateways/configuration.mdx | 9 + skills/debug-openshell-cluster/SKILL.md | 15 ++ 22 files changed, 774 insertions(+), 132 deletions(-) create mode 100644 crates/openshell-driver-kubernetes/src/app_endpoint_index.rs create mode 100644 crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs create mode 100644 crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs diff --git a/crates/openshell-core/src/app_listener.rs b/crates/openshell-core/src/app_listener.rs index 5db86c3cd7..7ab9492a4f 100644 --- a/crates/openshell-core/src/app_listener.rs +++ b/crates/openshell-core/src/app_listener.rs @@ -6,6 +6,9 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +pub const DEFAULT_APP_MAX_CONNECTIONS: usize = 1024; +pub const DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX: usize = 64; + /// Gateway browser credentials are reserved on both application access paths. pub fn is_gateway_service_auth_cookie(name: &[u8]) -> bool { name.eq_ignore_ascii_case(b"__Host-openshell-service-session") @@ -21,6 +24,10 @@ pub struct AppListenerConfig { pub port: u16, /// Public HTTPS origin used to derive service hostnames and URLs. pub base_url: Option, + /// Concurrent accepted TLS connections per supervisor listener. + pub max_connections: usize, + /// Concurrent connections and backend relays for each sandbox. + pub max_connections_per_sandbox: usize, } impl Default for AppListenerConfig { @@ -29,6 +36,8 @@ impl Default for AppListenerConfig { enabled: false, port: 8443, base_url: None, + max_connections: DEFAULT_APP_MAX_CONNECTIONS, + max_connections_per_sandbox: DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX, } } } @@ -59,6 +68,13 @@ impl AppListenerConfig { if !self.enabled { return Ok(()); } + if self.max_connections == 0 + || self.max_connections > tokio::sync::Semaphore::MAX_PERMITS + || self.max_connections_per_sandbox == 0 + || self.max_connections_per_sandbox > self.max_connections + { + return Err("app listener requires 1 <= max_connections_per_sandbox <= max_connections <= Semaphore::MAX_PERMITS".into()); + } let origin = self.parsed_base_url()?; validate_listener_endpoint(self.port, origin.host_str().unwrap_or_default()) } @@ -286,6 +302,26 @@ mod tests { assert!(config.service_url("default", "demo", "web", None).is_none()); } + #[test] + fn listener_connection_budgets_preserve_defaults_and_reject_invalid_bounds() { + let mut config = AppListenerConfig { + enabled: true, + base_url: Some("https://services.example.com".into()), + ..Default::default() + }; + assert_eq!(config.max_connections, 1024); + assert_eq!(config.max_connections_per_sandbox, 64); + assert!(config.validate().is_ok()); + for (total, per_sandbox) in [(0, 1), (64, 0), (64, 65), (usize::MAX, 1)] { + config.max_connections = total; + config.max_connections_per_sandbox = per_sandbox; + assert!(config.validate().is_err()); + } + config.max_connections = 16384; + config.max_connections_per_sandbox = 256; + assert!(config.validate().is_ok()); + } + #[test] fn base_url_is_the_only_authored_service_domain() { let config: AppListenerConfig = serde_json::from_str( diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index bb2c4e49fb..46dcc4366a 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -2,6 +2,14 @@ Kubernetes-backed compute driver for OpenShell cluster deployments. +Application endpoint resolution uses a metadata-only Sandbox watch to map each +sandbox ID to its Kubernetes resource. Every resolution still fetches that +resource by name and checks its UID, gateway labels, and deletion state before +validating supervisor placement. The watch must finish its initial list; +ambiguous IDs and watch errors make resolution unavailable until a fresh list +completes. Renewals use point reads to avoid repeated label-selected Sandbox +LISTs exhausting Kubernetes API flow-control capacity. + Caller driver config is disabled by default. External resource references need administrator-controlled approval labels in every workspace mode, including before restart and scheduling-gate release. GPU devices are temporarily exempt. diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs new file mode 100644 index 0000000000..5e51598fcb --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_index.rs @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Watch-maintained resource locators, never cached endpoint authority. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use futures::StreamExt as _; +use kube::Api; +use kube::core::{DynamicObject, ObjectMeta, PartialObjectMeta}; +use kube::runtime::watcher::{self, Event}; +use openshell_core::driver_utils::{ + LABEL_GATEWAY_ID, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Locator { + pub namespace: String, + pub name: String, + uid: String, +} + +impl Locator { + pub fn matches(&self, metadata: &ObjectMeta, sandbox_id: &str, gateway_id: &str) -> bool { + let label = |key| metadata.labels.as_ref().and_then(|labels| labels.get(key)); + metadata.namespace.as_ref() == Some(&self.namespace) + && metadata.name.as_ref() == Some(&self.name) + && metadata.uid.as_ref() == Some(&self.uid) + && metadata.deletion_timestamp.is_none() + && label(LABEL_SANDBOX_ID).is_some_and(|id| id == sandbox_id) + && label(LABEL_GATEWAY_ID).is_some_and(|id| id == gateway_id) + && label(LABEL_MANAGED_BY).is_some_and(|value| value == LABEL_MANAGED_BY_VALUE) + } +} + +#[derive(Default)] +struct State { + ready: bool, + // Key by resource name so label changes replace the previous association. + objects: BTreeMap<(String, String), (String, Locator)>, + by_id: BTreeMap>, +} + +impl State { + fn remove(&mut self, key: &(String, String)) { + if let Some((id, _)) = self.objects.remove(key) + && let Some(locators) = self.by_id.get_mut(&id) + { + locators.remove(key); + if locators.is_empty() { + self.by_id.remove(&id); + } + } + } + + fn apply(&mut self, metadata: ObjectMeta) { + let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { + return; + }; + let key = (namespace.clone(), name.clone()); + self.remove(&key); + let Some(uid) = metadata.uid.clone() else { + return; + }; + let Some(id) = metadata + .labels + .as_ref() + .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) + .cloned() + else { + return; + }; + if metadata.deletion_timestamp.is_some() { + return; + } + let locator = Locator { + namespace: namespace.clone(), + name: name.clone(), + uid, + }; + self.by_id + .entry(id.clone()) + .or_default() + .insert(key.clone(), locator.clone()); + self.objects.insert(key, (id, locator)); + } + + fn delete(&mut self, metadata: &ObjectMeta) { + let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { + return; + }; + let key = (namespace.clone(), name.clone()); + if self + .objects + .get(&key) + .is_some_and(|(_, locator)| metadata.uid.as_ref() == Some(&locator.uid)) + { + self.remove(&key); + } + } +} + +#[derive(Clone, Default)] +pub struct AppEndpointIndex(Arc>); + +impl AppEndpointIndex { + pub fn lookup(&self, sandbox_id: &str) -> Option { + let state = self.0.lock().ok()?; + if !state.ready { + return None; + } + let locators = state.by_id.get(sandbox_id)?; + if locators.len() != 1 { + return None; + } + locators.values().next().cloned() + } + + pub fn observe(&self, event: Event) { + let Ok(mut state) = self.0.lock() else { return }; + match event { + Event::Init => *state = State::default(), + Event::InitApply(metadata) | Event::Apply(metadata) => state.apply(metadata), + Event::InitDone => state.ready = true, + Event::Delete(metadata) => state.delete(&metadata), + } + } + + pub fn start( + &self, + api: Api>, + selector: String, + mut shutdown: tokio::sync::watch::Receiver, + ) { + let index = self.clone(); + tokio::spawn(async move { + loop { + if *shutdown.borrow() { + break; + } + let stream = + watcher::watcher(api.clone(), watcher::Config::default().labels(&selector)); + tokio::pin!(stream); + loop { + tokio::select! { + _ = shutdown.changed() => { index.observe(Event::Init); return; } + event = stream.next() => match event { + Some(Ok(event)) => index.observe(match event { + Event::Init => Event::Init, + Event::InitDone => Event::InitDone, + Event::Apply(object) => Event::Apply(object.metadata), + Event::InitApply(object) => Event::InitApply(object.metadata), + Event::Delete(object) => Event::Delete(object.metadata), + }), + Some(Err(error)) => { + tracing::warn!(%error, "application endpoint locator watch failed; relisting"); + break; + } + None => break, + } + } + } + // Recreate the watcher after errors so recovery must complete + // a fresh list; incremental events cannot revive a partial index. + index.observe(Event::Init); + tokio::select! { + _ = shutdown.changed() => return, + () = tokio::time::sleep(Duration::from_secs(1)) => {} + } + } + index.observe(Event::Init); + }); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs new file mode 100644 index 0000000000..e1f248363b --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_index/tests.rs @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; + +fn metadata(namespace: &str, name: &str, uid: &str, id: &str) -> ObjectMeta { + ObjectMeta { + namespace: Some(namespace.into()), + name: Some(name.into()), + uid: Some(uid.into()), + labels: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.into(), id.into()), + (LABEL_GATEWAY_ID.into(), "gateway".into()), + (LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()), + ])), + ..Default::default() + } +} + +#[test] +fn partial_initialization_and_watch_reset_do_not_publish_locators() { + let index = AppEndpointIndex::default(); + let object = metadata("ns", "sandbox", "uid", "id"); + index.observe(Event::InitApply(object.clone())); + assert!(index.lookup("id").is_none()); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_some()); + index.observe(Event::Init); + index.observe(Event::InitApply(object)); + assert!(index.lookup("id").is_none()); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_some()); + index.observe(Event::Init); + index.observe(Event::InitDone); + assert!( + index.lookup("id").is_none(), + "relisting removes absent resources" + ); +} + +#[test] +fn duplicate_ids_across_namespaces_are_ambiguous() { + let index = AppEndpointIndex::default(); + let first = metadata("ns-a", "same-name", "uid-a", "id"); + let second = metadata("ns-b", "same-name", "uid-b", "id"); + index.observe(Event::InitApply(first)); + index.observe(Event::InitApply(second.clone())); + index.observe(Event::InitDone); + assert!(index.lookup("id").is_none()); + index.observe(Event::Delete(second)); + assert_eq!(index.lookup("id").unwrap().namespace, "ns-a"); +} + +#[test] +fn delayed_deletion_cannot_remove_recreated_resource() { + let index = AppEndpointIndex::default(); + let original = metadata("ns", "sandbox", "old", "id"); + let replacement = metadata("ns", "sandbox", "new", "id"); + index.observe(Event::InitApply(original.clone())); + index.observe(Event::InitDone); + let old = index.lookup("id").unwrap(); + index.observe(Event::Apply(replacement.clone())); + index.observe(Event::Delete(original)); + assert!(!old.matches(&replacement, "id", "gateway")); + assert!( + index + .lookup("id") + .unwrap() + .matches(&replacement, "id", "gateway") + ); +} + +#[test] +fn label_reassignment_replaces_old_id_and_get_must_match_all_identity_fields() { + let index = AppEndpointIndex::default(); + let mut object = metadata("ns", "sandbox", "uid", "old"); + index.observe(Event::InitApply(object.clone())); + index.observe(Event::InitDone); + object + .labels + .as_mut() + .unwrap() + .insert(LABEL_SANDBOX_ID.into(), "new".into()); + index.observe(Event::Apply(object.clone())); + assert!(index.lookup("old").is_none()); + let locator = index.lookup("new").unwrap(); + assert!(locator.matches(&object, "new", "gateway")); + assert!(!locator.matches(&object, "old", "gateway")); + assert!(!locator.matches(&object, "new", "other-gateway")); + object + .labels + .as_mut() + .unwrap() + .insert(LABEL_MANAGED_BY.into(), "foreign".into()); + assert!(!locator.matches(&object, "new", "gateway")); +} diff --git a/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs b/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs new file mode 100644 index 0000000000..1f98e05930 --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/app_endpoint_lookup_tests.rs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[tokio::test] +async fn indexed_resolution_uses_point_reads_and_rejects_recreated_resources() { + let config = KubernetesComputeConfig::default(); + let metadata = ObjectMeta { + namespace: Some("openshell".into()), + name: Some("team-a--sandbox".into()), + uid: Some("original".into()), + labels: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.into(), "sandbox-id".into()), + (LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()), + (LABEL_GATEWAY_ID.into(), config.gateway_id.clone()), + ])), + ..Default::default() + }; + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let response_metadata = metadata.clone(); + let service = tower::service_fn(move |request: http::Request| { + let count = observed.fetch_add(1, Ordering::SeqCst); + assert_eq!(request.method(), http::Method::GET); + assert_eq!( + request.uri().path(), + "/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes/team-a--sandbox" + ); + assert!( + request.uri().query().is_none(), + "renewals must not submit label-selected LISTs" + ); + let mut metadata = response_metadata.clone(); + if count == 2 { + metadata.uid = Some("recreated".into()); + } + async move { + Ok::<_, std::convert::Infallible>(http::Response::new(http_body_util::Full::new(bytes::Bytes::from( + serde_json::to_vec(&serde_json::json!({ + "apiVersion":"agents.x-k8s.io/v1beta1", "kind":"Sandbox", "metadata":metadata + })).unwrap() + )))) + } + }); + let client = Client::new(service, "openshell"); + let mut driver = KubernetesComputeDriver::new_for_test(config); + driver.client = client; + driver + .sandbox_api_version + .set(SANDBOX_VERSION_V1BETA1) + .unwrap(); + driver + .app_endpoint_index + .observe(Event::InitApply(metadata)); + driver.app_endpoint_index.observe(Event::InitDone); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_some() + ); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_some() + ); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_none() + ); + assert_eq!(requests.load(Ordering::SeqCst), 3); + driver.app_endpoint_index.observe(Event::Init); + assert!( + driver + .app_endpoint_sandbox("sandbox-id") + .await + .unwrap() + .is_none() + ); + assert_eq!( + requests.load(Ordering::SeqCst), + 3, + "unavailable index must fail closed without a fallback LIST" + ); +} diff --git a/crates/openshell-driver-kubernetes/src/app_listener.rs b/crates/openshell-driver-kubernetes/src/app_listener.rs index 95e5bfe356..acfcb3e202 100644 --- a/crates/openshell-driver-kubernetes/src/app_listener.rs +++ b/crates/openshell-driver-kubernetes/src/app_listener.rs @@ -24,6 +24,14 @@ pub fn configure_supervisor_pod(mut pod: Pod, config: &KubernetesAppListenerConf let env = container.env.get_or_insert_default(); for (name, value) in [ ("OPENSHELL_APP_LISTENER_ENABLED", "true".to_string()), + ( + "OPENSHELL_APP_MAX_CONNECTIONS", + config.common.max_connections.to_string(), + ), + ( + "OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", + config.common.max_connections_per_sandbox.to_string(), + ), ( "OPENSHELL_APP_LISTEN_ADDRESS", format!("0.0.0.0:{}", config.common.port), @@ -107,6 +115,8 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + max_connections: 16384, + max_connections_per_sandbox: 256, }, tls_secret_name: "app-tls".into(), }; @@ -125,5 +135,10 @@ mod tests { Some("https://services.example.com:10443") ); assert_eq!(value("OPENSHELL_APP_LISTEN_ADDRESS"), Some("0.0.0.0:9443")); + assert_eq!(value("OPENSHELL_APP_MAX_CONNECTIONS"), Some("16384")); + assert_eq!( + value("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX"), + Some("256") + ); } } diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 82f98cdb54..e8fe9d5714 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -1196,6 +1196,7 @@ mod tests { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; assert!(config.validate().is_ok()); config.app_listener.common.port = config.boundary_port; diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..7b985780c1 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1081,6 +1081,7 @@ pub struct KubernetesComputeDriver { watch_client: Client, sandbox_api_version: Arc>, lifecycle_gates: Arc, + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex, config: KubernetesComputeConfig, /// Gateway-normalized destination trust available only to this in-process /// driver. The external driver protocol deliberately has no transport for @@ -1130,6 +1131,7 @@ impl KubernetesComputeDriver { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle: None, operator_allowlist: None, @@ -1278,6 +1280,7 @@ impl KubernetesComputeDriver { watch_client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle, operator_allowlist, @@ -1288,6 +1291,30 @@ impl KubernetesComputeDriver { driver.backfill_gateway_id_labels().await?; } + if driver.config.sandbox_runtime.app_listener.common.enabled { + let api = driver + .supported_sandbox_api_for_lookup(driver.watch_client.clone()) + .await + .map_err(KubernetesDriverError::Message)?; + let metadata_api = if driver.config.is_multi_namespace() { + Api::>::all_with( + driver.watch_client.clone(), + &api.resource, + ) + } else { + Api::>::namespaced_with( + driver.watch_client.clone(), + &driver.config.namespace, + &api.resource, + ) + }; + driver.app_endpoint_index.start( + metadata_api, + driver.openshell_sandbox_selector(), + shutdown_rx.clone(), + ); + } + Ok(driver) } @@ -2219,6 +2246,35 @@ impl KubernetesComputeDriver { Ok(()) } + async fn app_endpoint_sandbox( + &self, + sandbox_id: &str, + ) -> Result, KubernetesDriverError> { + let Some(locator) = self.app_endpoint_index.lookup(sandbox_id) else { + return Ok(None); + }; + let api = self + .supported_agent_sandbox_api(self.client.clone(), &locator.namespace) + .await + .map_err(KubernetesDriverError::Message)?; + let Some(object) = api + .api + .get_opt(&locator.name) + .await + .map_err(KubernetesDriverError::from_kube)? + else { + return Ok(None); + }; + // The watch provides a locator only. A fresh GET and the original UID + // pin are required on every resolution; never cache serving authority. + if !locator.matches(&object.metadata, sandbox_id, &self.config.gateway_id) + || self.app_endpoint_index.lookup(sandbox_id).as_ref() != Some(&locator) + { + return Ok(None); + } + Ok(Some(object)) + } + /// Resolve only a unique, live driver-owned supervisor. Multi-member pool /// resolution must use the HA assignment/member API rather than guess. pub async fn supervisor_app_endpoint( @@ -2231,19 +2287,8 @@ impl KubernetesComputeDriver { if !self.config.sandbox_runtime.app_listener.common.enabled { return Ok(None); } - let api = self - .supported_sandbox_api_for_lookup(self.client.clone()) - .await - .map_err(KubernetesDriverError::Message)?; - let objects = api - .api - .list(&ListParams::default().labels(&self.sandbox_lookup_selector(sandbox_id))) - .await - .map_err(KubernetesDriverError::from_kube)? - .items; - let [object]: [DynamicObject; 1] = match objects.try_into() { - Ok(objects) => objects, - Err(_) => return Ok(None), + let Some(object) = self.app_endpoint_sandbox(sandbox_id).await? else { + return Ok(None); }; let namespace = object.metadata.namespace.as_deref().ok_or_else(|| { KubernetesDriverError::Precondition("sandbox namespace missing".into()) @@ -9468,6 +9513,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), network_trust_bundle: None, operator_allowlist: None, @@ -10718,6 +10764,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), operator_allowlist: None, shared_supervisor: None, @@ -10811,6 +10858,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), operator_allowlist: None, shared_supervisor: None, @@ -13588,6 +13636,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config, network_trust_bundle: None, operator_allowlist: None, @@ -13894,6 +13943,7 @@ mod tests { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: managed_config(&[]), network_trust_bundle: None, operator_allowlist: None, @@ -14811,3 +14861,7 @@ mod tests { include!("lifecycle_tests.rs"); } + +#[cfg(test)] +#[path = "app_endpoint_lookup_tests.rs"] +mod app_endpoint_lookup_tests; diff --git a/crates/openshell-driver-kubernetes/src/image_update_tests.rs b/crates/openshell-driver-kubernetes/src/image_update_tests.rs index 6a079d9575..8795e78abd 100644 --- a/crates/openshell-driver-kubernetes/src/image_update_tests.rs +++ b/crates/openshell-driver-kubernetes/src/image_update_tests.rs @@ -230,6 +230,7 @@ fn fixture( watch_client: client, sandbox_api_version: Arc::new(api_version), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), shared_supervisor: None, network_trust_bundle: None, config: KubernetesComputeConfig { diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index f3a1e419ec..e0033179f4 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +mod app_endpoint_index; pub mod app_listener; pub mod config; pub mod driver; diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index afe894fd39..57822910aa 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -135,6 +135,7 @@ mod lifecycle_reconciliation { watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), lifecycle_gates: Arc::default(), + app_endpoint_index: crate::app_endpoint_index::AppEndpointIndex::default(), config: KubernetesComputeConfig::default(), network_trust_bundle: None, operator_allowlist: None, diff --git a/crates/openshell-server/src/grpc/mutation_replay/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/tests.rs index 0a7648c484..98d6484f83 100644 --- a/crates/openshell-server/src/grpc/mutation_replay/tests.rs +++ b/crates/openshell-server/src/grpc/mutation_replay/tests.rs @@ -212,6 +212,7 @@ async fn create_replay_preserves_all_recorded_urls_when_origins_change() { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let replay = run(&state, authed_request(request)).await.unwrap(); assert_eq!(replay.metadata().get("openshell-replayed").unwrap(), "true"); @@ -240,6 +241,7 @@ async fn expose_replay_preserves_recorded_url_when_origins_change_or_are_disable enabled: true, port: 9443, base_url: Some("https://old.example.com:10443".into()), + ..Default::default() }; run( &state, diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 5c95fef3b0..a7557d2319 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -666,6 +666,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com".into()), + ..Default::default() }; seed_sandbox(&state, "limited").await; state @@ -794,6 +795,7 @@ mod tests { port: 9443, base_url: application_enabled .then(|| "https://services.example.com:10443".into()), + ..Default::default() }; seed_sandbox(&state, "demo").await; for name in ["", "web"] { @@ -875,6 +877,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let response = handle_expose_service(&state, authed_request(request.clone())) @@ -926,6 +929,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://services.example.com:10443".into()), + ..Default::default() }; let response = service_endpoint_response( &state, @@ -968,6 +972,7 @@ mod tests { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; seed_sandbox(&state, "first").await; seed_sandbox(&state, "second").await; diff --git a/crates/openshell-server/src/grpc/service_advertisement.rs b/crates/openshell-server/src/grpc/service_advertisement.rs index 77dd8895a9..23a0439252 100644 --- a/crates/openshell-server/src/grpc/service_advertisement.rs +++ b/crates/openshell-server/src/grpc/service_advertisement.rs @@ -230,6 +230,7 @@ pub async fn prepare_lease( state: &ServerState, owner: &OwnerGuard, ) -> Result, Status> { + let started = std::time::Instant::now(); let Some(sandbox) = state .store .get_message::(&owner.sandbox_id) @@ -261,16 +262,17 @@ pub async fn prepare_lease( if !state.config.supervisor_app_listener.enabled { return Ok(None); } - Ok(current_endpoint(state, &sandbox, owner) - .await? - .map(|endpoint| LeaseAuthority { - sandbox_id: owner.sandbox_id.clone(), - session_id: owner.session_id.clone(), - supervisor_instance_id: owner.supervisor_instance_id.clone(), - connection_epoch: owner.connection_epoch, - auth_epoch: owner.auth_epoch, - endpoint, - })) + tracing::debug!(sandbox_id = %owner.sandbox_id, elapsed_ms = started.elapsed().as_millis(), "service installation lease resolving endpoint"); + let endpoint = current_endpoint(state, &sandbox, owner).await?; + tracing::debug!(sandbox_id = %owner.sandbox_id, elapsed_ms = started.elapsed().as_millis(), available = endpoint.is_some(), "service installation lease endpoint resolved"); + Ok(endpoint.map(|endpoint| LeaseAuthority { + sandbox_id: owner.sandbox_id.clone(), + session_id: owner.session_id.clone(), + supervisor_instance_id: owner.supervisor_instance_id.clone(), + connection_epoch: owner.connection_epoch, + auth_epoch: owner.auth_epoch, + endpoint, + })) } pub async fn accept_lease( @@ -1240,6 +1242,7 @@ pub(super) mod test_support { base_url: Some("https://services.example.com".into()), enabled: true, port: 9443, + ..Default::default() }; let inner = Arc::get_mut(&mut state).unwrap(); inner.config.name = gateway.into(); diff --git a/crates/openshell-server/src/grpc/service_discovery.rs b/crates/openshell-server/src/grpc/service_discovery.rs index 12b9f8f805..662875c9d7 100644 --- a/crates/openshell-server/src/grpc/service_discovery.rs +++ b/crates/openshell-server/src/grpc/service_discovery.rs @@ -41,6 +41,7 @@ pub type RouteWatchStream = ReceiverStream Result { + use futures::{StreamExt as _, TryStreamExt as _}; + tokio::time::timeout(SNAPSHOT_TIMEOUT, async { authorize_selection(state, principal, selection).await?; let before = selection_workspaces(state, selection).await?; @@ -447,8 +450,10 @@ async fn selected_snapshot( let names = before.clone(); let mut result = ServiceRouteSnapshot::default(); let mut bytes = 0usize; - for name in names { - let part = cached_snapshot(state, &name).await?; + let mut parts = futures::stream::iter(names) + .map(|name| async move { cached_snapshot(state, &name).await }) + .buffered(MAX_COLLECTIONS); + while let Some(part) = parts.try_next().await? { bytes = bytes.saturating_add(part.encoded_len()); if bytes > MAX_BYTES - 128 || result.routes.len() + part.routes.len() > MAX_ROUTES { return Err(Status::resource_exhausted( @@ -685,25 +690,31 @@ async fn validate_installations( inputs: &DiscoveryConfigInputs, before: Vec, ) -> Result, Status> { - let mut validated = Vec::new(); - for object in before { - let installation: Installation = serde_json::from_slice(&object.payload) - .map_err(|_| Status::internal("invalid service installation record"))?; - let Some((sandbox, routes)) = validated_routes(state, &installation, Some(inputs)).await? - else { - continue; - }; - if sandbox.object_workspace() != workspace { - return Err(Status::internal("installation workspace mismatch")); - } - validated.push(ValidatedInstallation { - id: object.id, - installation, - sandbox, - routes, - }); - } - Ok(validated) + use futures::{StreamExt as _, TryStreamExt as _}; + + futures::stream::iter(before) + .map(|object| async move { + let installation: Installation = serde_json::from_slice(&object.payload) + .map_err(|_| Status::internal("invalid service installation record"))?; + let Some((sandbox, routes)) = + validated_routes(state, &installation, Some(inputs)).await? + else { + return Ok(None); + }; + if sandbox.object_workspace() != workspace { + return Err(Status::internal("installation workspace mismatch")); + } + Ok(Some(ValidatedInstallation { + id: object.id, + installation, + sandbox, + routes, + })) + }) + .buffer_unordered(RECORD_CONCURRENCY) + .try_filter_map(|item| async move { Ok(item) }) + .try_collect() + .await } async fn publish_installations( @@ -712,6 +723,8 @@ async fn publish_installations( inputs: &DiscoveryConfigInputs, validated: Vec, ) -> Result { + use futures::{StreamExt as _, TryStreamExt as _}; + // Refresh receipts after expensive validation. Lease resource-version churn // is expected: compare serving identity, not a transaction-wide row version. let mut latest: std::collections::HashMap<_, _> = records(state, workspace) @@ -719,85 +732,20 @@ async fn publish_installations( .into_iter() .map(|r| (r.id.clone(), r)) .collect(); + let mut parts = futures::stream::iter(validated) + .map(|previous| { + let record = latest.remove(&previous.id); + publish_installation(state, workspace, inputs, previous, record) + }) + .buffer_unordered(RECORD_CONCURRENCY); let mut routes = Vec::new(); - for previous in validated { - let Some(record) = latest.remove(&previous.id) else { - continue; - }; - let installation: Installation = serde_json::from_slice(&record.payload) - .map_err(|_| Status::internal("invalid service installation record"))?; - if !previous.installation.same_identity(&installation) - || installation.sequence < previous.installation.sequence - || (installation.sequence == previous.installation.sequence - && installation.expires_at_ms != previous.installation.expires_at_ms) - { - continue; - } - let Some(sandbox) = current_sandbox(state, &installation).await? else { - continue; - }; - let installed_routes = if installation.sequence != previous.installation.sequence - || sandbox.metadata != previous.sandbox.metadata - { - // A renewed lease is reused only after checking its configuration - // and live authority too. Never manufacture a new expiry at read time. - let Some((_, routes)) = validated_routes(state, &installation, Some(inputs)).await? - else { - continue; - }; - routes - } else { - previous.routes - }; - for (bytes, route) in installation.routes.iter().zip(installed_routes) { - let hostname = if route.application_hostname.is_empty() { - // Legacy reports can only be current against legacy configuration. - state - .config - .supervisor_app_listener - .service_hostname( - workspace, - sandbox.object_name(), - &route.name, - state.config.service_routing_discriminator(), - ) - .ok_or_else(|| { - Status::failed_precondition("application listener hostname unavailable") - })? - } else { - route.application_hostname.clone() - }; - let label = hostname - .strip_suffix(&format!(".{}", installation.service_domain)) - .ok_or_else(|| Status::internal("installed hostname domain mismatch"))?; - if !openshell_core::app_listener::valid_dns_label(label) { - return Err(Status::failed_precondition( - "service hostname exceeds DNS label limit", - )); - } - let version = installation_version(&installation, bytes)?; - routes.push(DiscoveredServiceRoute { - workspace: workspace.to_string(), - sandbox: sandbox.object_name().to_string(), - name: route.name, - hostname, - endpoint: Some(ServiceRouteEndpoint { - host: installation.host.clone(), - port: installation.port, - }), - installation_version: version, - declaration_revision: route.resource_version, - expires_at: Some( - openshell_core::time::timestamp_from_millis(installation.expires_at_ms) - .map_err(|_| Status::internal("invalid installation expiry"))?, - ), - }); - if routes.len() > MAX_ROUTES { - return Err(Status::resource_exhausted( - "too many discovered service routes", - )); - } + while let Some(part) = parts.try_next().await? { + if routes.len() + part.len() > MAX_ROUTES { + return Err(Status::resource_exhausted( + "too many discovered service routes", + )); } + routes.extend(part); } // Shared catalog, global settings and bulk declarations are collection-local. // Changes invalidate the view; normal serving-lease renewal does not. @@ -805,6 +753,93 @@ async fn publish_installations( finish_snapshot(routes) } +async fn publish_installation( + state: &ServerState, + workspace: &str, + inputs: &DiscoveryConfigInputs, + previous: ValidatedInstallation, + record: Option, +) -> Result, Status> { + let Some(record) = record else { + return Ok(Vec::new()); + }; + let installation: Installation = serde_json::from_slice(&record.payload) + .map_err(|_| Status::internal("invalid service installation record"))?; + if !previous.installation.same_identity(&installation) + || installation.sequence < previous.installation.sequence + || (installation.sequence == previous.installation.sequence + && installation.expires_at_ms != previous.installation.expires_at_ms) + { + return Ok(Vec::new()); + } + let Some(sandbox) = current_sandbox(state, &installation).await? else { + return Ok(Vec::new()); + }; + let installed_routes = if installation.sequence != previous.installation.sequence + || sandbox.metadata != previous.sandbox.metadata + { + // A renewed lease is reused only after checking its configuration + // and live authority too. Never manufacture a new expiry at read time. + let Some((_, routes)) = validated_routes(state, &installation, Some(inputs)).await? else { + return Ok(Vec::new()); + }; + routes + } else { + previous.routes + }; + let mut routes = Vec::new(); + for (bytes, route) in installation.routes.iter().zip(installed_routes) { + let hostname = if route.application_hostname.is_empty() { + // Legacy reports can only be current against legacy configuration. + state + .config + .supervisor_app_listener + .service_hostname( + workspace, + sandbox.object_name(), + &route.name, + state.config.service_routing_discriminator(), + ) + .ok_or_else(|| { + Status::failed_precondition("application listener hostname unavailable") + })? + } else { + route.application_hostname.clone() + }; + let label = hostname + .strip_suffix(&format!(".{}", installation.service_domain)) + .ok_or_else(|| Status::internal("installed hostname domain mismatch"))?; + if !openshell_core::app_listener::valid_dns_label(label) { + return Err(Status::failed_precondition( + "service hostname exceeds DNS label limit", + )); + } + let version = installation_version(&installation, bytes)?; + routes.push(DiscoveredServiceRoute { + workspace: workspace.to_string(), + sandbox: sandbox.object_name().to_string(), + name: route.name, + hostname, + endpoint: Some(ServiceRouteEndpoint { + host: installation.host.clone(), + port: installation.port, + }), + installation_version: version, + declaration_revision: route.resource_version, + expires_at: Some( + openshell_core::time::timestamp_from_millis(installation.expires_at_ms) + .map_err(|_| Status::internal("invalid installation expiry"))?, + ), + }); + if routes.len() > MAX_ROUTES { + return Err(Status::resource_exhausted( + "too many discovered service routes", + )); + } + } + Ok(routes) +} + fn route_is_live(route: &DiscoveredServiceRoute) -> bool { route .expires_at diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index ac3e51390c..fdc2e8fde8 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -2326,6 +2326,7 @@ mod tests { enabled: true, port: 9443, base_url: Some("https://apps.example.com".into()), + ..Default::default() }; for workspace in ["default", "team-a"] { for service in ["", "web"] { diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 0c39fdbf9f..8694a9640b 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -3004,9 +3004,14 @@ async fn run_session_loop( bootstrap_complete = true; } if let Some(supervisor_message::Payload::ServiceAdvertisement(report)) = &msg.payload { - if let Some(lease) = app_lease.claim(report.lease_sequence) - && !matches!(tokio::time::timeout(Duration::from_secs(2), crate::grpc::service_advertisement::accept_lease(state, owner_guard, report, lease)).await, Ok(Ok(()))) { - debug!(sandbox_id, "service installation report rejected or unavailable"); + if let Some(lease) = app_lease.claim(report.lease_sequence) { + match tokio::time::timeout(Duration::from_secs(2), crate::grpc::service_advertisement::accept_lease(state, owner_guard, report, lease)).await { + Ok(Ok(())) => {} + Ok(Err(error)) => debug!(sandbox_id, sequence = report.lease_sequence, %error, "service installation report rejected"), + Err(_) => debug!(sandbox_id, sequence = report.lease_sequence, "service installation report acceptance timed out"), + } + } else { + debug!(sandbox_id, sequence = report.lease_sequence, "service installation report lease is stale or already claimed"); } continue; } @@ -3041,9 +3046,22 @@ async fn run_session_loop( } } _ = app_timer.tick(), if session.advertises_services => { - let Ok(Ok(Some(authority))) = tokio::time::timeout(Duration::from_secs(2), - crate::grpc::service_advertisement::prepare_lease(state, owner_guard)).await - else { continue; }; + let authority = match tokio::time::timeout(Duration::from_secs(2), + crate::grpc::service_advertisement::prepare_lease(state, owner_guard)).await { + Ok(Ok(Some(authority))) => authority, + Ok(Ok(None)) => { + debug!(sandbox_id, "service installation lease authority unavailable"); + continue; + } + Ok(Err(error)) => { + debug!(sandbox_id, %error, "service installation lease preparation failed"); + continue; + } + Err(_) => { + debug!(sandbox_id, "service installation lease preparation timed out"); + continue; + } + }; let Some(lease) = app_lease.issue(authority) else { break; }; let message = GatewayMessage { payload: Some(gateway_message::Payload::ServiceRouteLease(lease)) }; if tx.try_send(message).is_err() { break; } diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index 790487a32c..1a1ef3e6ce 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -310,6 +310,13 @@ instance's configuration from process environment. TLS configuration uses `openshell-crypto`; certificates are read at process startup. Restart the supervisor to reload application certificates. +`OPENSHELL_APP_MAX_CONNECTIONS` bounds accepted connections for the process +listener (default 1024). `OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX` bounds each +sandbox's connections and backend relays (default 64). Both must be positive, +and the per-sandbox limit cannot exceed the process limit. The gateway's +`supervisor.app_listener` configuration and Kubernetes Helm templates propagate +these budgets; increase supervisor resources before raising them. + This path uses application or trusted-edge authentication independently from gateway authentication. It validates Host against SNI, preserves public Host/Origin and application cookies, strips gateway/edge identity material, and diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 009edaa8a3..075b31e9b7 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -35,7 +35,9 @@ use tokio_rustls::TlsAcceptor; const FRESHNESS: Duration = Duration::from_secs(30); const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -const MAX_INSTANCE_CONNECTIONS: usize = 64; +#[cfg(test)] +const MAX_INSTANCE_CONNECTIONS: usize = + openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX; const MAX_HTTP2_STREAMS: u32 = 16; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -81,6 +83,22 @@ pub struct Config { domain: String, certificate: PathBuf, key: PathBuf, + limits: ConnectionLimits, +} + +#[derive(Clone, Copy)] +struct ConnectionLimits { + total: usize, + per_sandbox: usize, +} + +impl Default for ConnectionLimits { + fn default() -> Self { + Self { + total: openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS, + per_sandbox: openshell_core::app_listener::DEFAULT_APP_MAX_CONNECTIONS_PER_SANDBOX, + } + } } impl Config { @@ -110,10 +128,25 @@ impl Config { )); }; let address: SocketAddr = address.parse().into_diagnostic()?; + let limit = |name: &str, default: usize| -> Result { + read(name).map_or(Ok(default), |value| { + value + .parse() + .map_err(|_| miette::miette!("{name} must be a positive integer")) + }) + }; let listener = openshell_core::app_listener::AppListenerConfig { enabled: true, port: address.port(), base_url: Some(base_url), + max_connections: limit( + "OPENSHELL_APP_MAX_CONNECTIONS", + ConnectionLimits::default().total, + )?, + max_connections_per_sandbox: limit( + "OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", + ConnectionLimits::default().per_sandbox, + )?, }; listener .validate() @@ -124,6 +157,10 @@ impl Config { domain, certificate: certificate.into(), key: key.into(), + limits: ConnectionLimits { + total: listener.max_connections, + per_sandbox: listener.max_connections_per_sandbox, + }, })) } @@ -146,6 +183,7 @@ impl Config { listener, acceptor: TlsAcceptor::from(Arc::new(tls)), domain: self.domain, + limits: self.limits, }) } } @@ -504,6 +542,7 @@ pub struct BoundListener { listener: tokio::net::TcpListener, acceptor: TlsAcceptor, domain: String, + limits: ConnectionLimits, } /// Host-level dispatcher. It never shares a sandbox connector or policy @@ -512,6 +551,7 @@ pub struct BoundListener { pub struct Router { domain: String, requires_authority: bool, + limits: ConnectionLimits, registrations: Arc>>>, } @@ -660,6 +700,7 @@ pub struct InstanceListener { pub(crate) routes: Routes, receiver: mpsc::Receiver, domain: String, + limits: ConnectionLimits, } pub struct Handle { @@ -685,7 +726,7 @@ impl Router { "app listener requires a canonical sandbox name" )); } - let (sender, receiver) = mpsc::channel(16); + let (sender, receiver) = mpsc::channel(self.limits.per_sandbox); let registration = Arc::new(Registration { router: self.clone(), sandbox: sandbox.to_string(), @@ -701,6 +742,7 @@ impl Router { }, receiver, domain: self.domain.clone(), + limits: self.limits, }) } } @@ -710,11 +752,12 @@ impl BoundListener { pub fn start(self) -> HostHandle { let router = Router { domain: self.domain.clone(), + limits: self.limits, ..Default::default() }; let dispatch = router.clone(); let task = tokio::spawn(async move { - let permits = Arc::new(Semaphore::new(1024)); + let permits = Arc::new(Semaphore::new(self.limits.total)); let mut connections = JoinSet::new(); loop { tokio::select! { @@ -763,9 +806,9 @@ impl InstanceListener { let retained_routes = self.routes.clone(); let task = tokio::spawn(async move { let routes = self.routes.clone(); - let permits = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); + let permits = Arc::new(Semaphore::new(self.limits.per_sandbox)); // Multiplexed requests share the previous per-instance relay budget. - let relays = Arc::new(Semaphore::new(MAX_INSTANCE_CONNECTIONS)); + let relays = Arc::new(Semaphore::new(self.limits.per_sandbox)); let mut connections = JoinSet::new(); ocsf_emit!( AppLifecycleBuilder::new(crate::ocsf_ctx()) @@ -1392,6 +1435,20 @@ mod tests { .unwrap(); assert_eq!(configured.address.port(), 9443); assert_eq!(configured.domain, "services.example.com"); + assert_eq!(configured.limits.total, 1024); + assert_eq!(configured.limits.per_sandbox, 64); + values.insert("OPENSHELL_APP_MAX_CONNECTIONS", "16384"); + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", "256"); + let configured = Config::from_values(|name| values.get(name).map(ToString::to_string)) + .unwrap() + .unwrap(); + assert_eq!(configured.limits.total, 16384); + assert_eq!(configured.limits.per_sandbox, 256); + for invalid in ["0", "-1", "invalid", "20000"] { + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", invalid); + assert!(Config::from_values(|name| values.get(name).map(ToString::to_string)).is_err()); + } + values.insert("OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX", "256"); values.remove("OPENSHELL_APP_TLS_KEY"); assert!(Config::from_values(|name| values.get(name).map(ToString::to_string)).is_err()); assert!( @@ -1703,6 +1760,7 @@ mod tests { domain: "svc.openshell.internal".into(), certificate: cert_path, key: key_path, + limits: ConnectionLimits::default(), }; let bound = config.bind().unwrap(); let address = bound.listener.local_addr().unwrap(); diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index 96d4a1e687..05d6da6beb 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -108,6 +108,10 @@ spec: {{- if get $app "enabled" }} - name: OPENSHELL_APP_LISTENER_ENABLED value: "true" + - name: OPENSHELL_APP_MAX_CONNECTIONS + value: {{ get $app "max_connections" | default 1024 | quote }} + - name: OPENSHELL_APP_MAX_CONNECTIONS_PER_SANDBOX + value: {{ get $app "max_connections_per_sandbox" | default 64 | quote }} - name: OPENSHELL_APP_LISTEN_ADDRESS value: {{ printf "%s:%v" $listenHost $appPort | quote }} - name: OPENSHELL_APP_BASE_URL diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 71d9882742..3e34651a5b 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -2361,11 +2361,20 @@ sandbox connection. [Expose long-running services](/how-it-works/sandboxes/overv enabled = true port = 9443 base_url = "https://services.example.com" +max_connections = 1024 +max_connections_per_sandbox = 64 [openshell.drivers.kubernetes.sandbox_runtime.app_listener] tls_secret_name = "openshell-app-tls" ``` +`max_connections` bounds concurrent accepted TLS connections per supervisor +listener and defaults to 1024. `max_connections_per_sandbox` bounds connections +and concurrent backend relays for each sandbox and defaults to 64. Both must be +positive, and the per-sandbox budget cannot exceed the listener budget. Size +these budgets with CPU, memory, and socket capacity when increasing shared +supervisor load. The Helm chart and Kubernetes driver pass them to supervisors. + `base_url = "https://"` replaces `domain`. Remove the old key when updating an existing app-listener configuration. diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index ade2038992..ee67689e48 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1975,3 +1975,18 @@ fails or stalls. Check Entra egress, the federated credential, and PostgreSQL role mapping; do not suggest CLI login, node identity, or a password fallback. Sandbox ServiceAccounts must not carry gateway database federation. See the published gateway configuration documentation for setup. + + +For application route renewal failures, `service installation lease preparation timed out` +means no renewal challenge was issued. Check Kubernetes API flow-control queues +as well as database latency. Endpoint resolution uses a metadata watch for a +Sandbox locator, then a fresh GET with UID, labels, and deletion checks. Watch +errors and incomplete relists make lookup unavailable. Do not extend expiry at +read time to repair an overloaded lookup path. + +Size supervisor app-listener connection budgets using +`supervisor.app_listener.max_connections` (default 1024) and +`max_connections_per_sandbox` (default 64). The Kubernetes driver and Helm chart +pass both budgets to supervisors. Keep the per-sandbox budget positive and at +most the listener-wide budget, and provide CPU, memory, and socket capacity for +higher budgets. From 9c5347d21923bd9602ccefbdf89622c00f5df03f Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Wed, 2 Dec 2026 14:45:47 -0800 Subject: [PATCH 2/2] docs(ingress): tidy renewal diagnostic guidance Signed-off-by: Taylor Mutch --- skills/debug-openshell-cluster/SKILL.md | 1 - 1 file changed, 1 deletion(-) diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index ee67689e48..8396be8ae3 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1976,7 +1976,6 @@ credential, and PostgreSQL role mapping; do not suggest CLI login, node identity or a password fallback. Sandbox ServiceAccounts must not carry gateway database federation. See the published gateway configuration documentation for setup. - For application route renewal failures, `service installation lease preparation timed out` means no renewal challenge was issued. Check Kubernetes API flow-control queues as well as database latency. Endpoint resolution uses a metadata watch for a