Skip to content

Commit bf9f55c

Browse files
authored
feat(gateway): expose workspace service route snapshots and watches (#4941)
* feat(gateway): expose workspace service route discovery Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(gateway): gate service discovery on the app listener Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * test(discovery): remove redundant request defaults before reader extension Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(discovery): separate and bound ingress discovery service Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(discovery): wait for collection capacity Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(discovery): share collection inputs and refresh accepted leases Signed-off-by: Taylor Mutch <taylormutch@gmail.com> --------- Signed-off-by: Taylor Mutch <taylormutch@gmail.com>
1 parent f0799e2 commit bf9f55c

21 files changed

Lines changed: 2546 additions & 120 deletions

File tree

‎crates/openshell-cli/tests/sandbox_exec_streaming_integration.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ macro_rules! mock_gateway {
163163
) => {
164164
#[tonic::async_trait]
165165
impl OpenShell for MockGateway {
166+
166167
$(async fn $method(&self, _: Request<$request>) -> Result<Response<$response>, Status> {
167168
Err(Status::unimplemented("unused test RPC"))
168169
})*

‎crates/openshell-sdk/src/client.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::auth::{BearerSlot, EdgeAuthInterceptor, bearer_metadata};
1212
use crate::config::{AuthConfig, ClientConfig};
1313
use crate::error::{Result, SdkError};
1414
use crate::pagination::{Page, Pager};
15-
use crate::raw::{AuthedGrpcClient, AuthedSandboxUpdatesClient};
15+
use crate::raw::{AuthedGrpcClient, AuthedSandboxUpdatesClient, AuthedServiceDiscoveryClient};
1616
use crate::refresh::{RefreshedToken, TokenSource};
1717
use crate::routing::OwnerCache;
1818
use crate::types::{
@@ -149,6 +149,23 @@ impl OpenShellClient {
149149
Ok(self.raw_sandbox_updates())
150150
}
151151

152+
/// Authenticated client for the separate ingress discovery service.
153+
/// Shares the channel and live auth slot; like [`Self::raw_grpc`], does not
154+
/// refresh or retry credentials by itself.
155+
pub fn raw_service_discovery(&self) -> AuthedServiceDiscoveryClient {
156+
proto::service_discovery_client::ServiceDiscoveryClient::with_interceptor(
157+
self.channel.clone(),
158+
self.interceptor.clone(),
159+
)
160+
}
161+
162+
/// Like [`Self::raw_service_discovery`], refreshing bearer credentials first.
163+
/// Reactive retry remains the raw caller's responsibility.
164+
pub async fn raw_service_discovery_fresh(&self) -> Result<AuthedServiceDiscoveryClient> {
165+
self.ensure_fresh().await?;
166+
Ok(self.raw_service_discovery())
167+
}
168+
152169
/// Force an OIDC refresh and write the new token into the live bearer
153170
/// slot, regardless of expiry. Returns `true` when a refresher is wired
154171
/// and a fresh token was minted, `false` for static auth. Use after a

‎crates/openshell-sdk/src/raw.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
pub use openshell_core::proto;
2222
pub use openshell_core::proto::open_shell_client::OpenShellClient as GrpcClient;
2323
pub use openshell_core::proto::sandbox_updates_client::SandboxUpdatesClient;
24+
pub use openshell_core::proto::service_discovery_client::ServiceDiscoveryClient;
2425
pub use openshell_core::proto::{
2526
CreateSandboxRequest, CreateSandboxTemplateRequest, CreateWorkspaceRequest,
2627
DeleteSandboxRequest, DeleteSandboxTemplateRequest, DeleteWorkspaceRequest, ExecSandboxRequest,
@@ -53,3 +54,11 @@ pub type AuthedSandboxUpdatesClient = SandboxUpdatesClient<
5354
crate::EdgeAuthInterceptor,
5455
>,
5556
>;
57+
58+
/// Application ingress discovery using the SDK transport and live auth slot.
59+
pub type AuthedServiceDiscoveryClient = ServiceDiscoveryClient<
60+
tonic::service::interceptor::InterceptedService<
61+
tonic::transport::Channel,
62+
crate::EdgeAuthInterceptor,
63+
>,
64+
>;

‎crates/openshell-sdk/tests/client_mock.rs‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1195,6 +1195,35 @@ impl SandboxUpdates for TestOpenShell {
11951195
}
11961196
}
11971197

1198+
#[tonic::async_trait]
1199+
impl proto::service_discovery_server::ServiceDiscovery for TestOpenShell {
1200+
async fn get_service_route_snapshot(
1201+
&self,
1202+
request: tonic::Request<proto::GetServiceRouteSnapshotRequest>,
1203+
) -> Result<Response<proto::GetServiceRouteSnapshotResponse>, Status> {
1204+
if let Some(expected) = &self.state.require_bearer
1205+
&& request
1206+
.metadata()
1207+
.get("authorization")
1208+
.and_then(|v| v.to_str().ok())
1209+
!= Some(expected.as_str())
1210+
{
1211+
return Err(Status::unauthenticated("invalid or missing bearer token"));
1212+
}
1213+
Ok(Response::new(proto::GetServiceRouteSnapshotResponse {
1214+
snapshot: Some(proto::ServiceRouteSnapshot::default()),
1215+
}))
1216+
}
1217+
type WatchServiceRoutesStream =
1218+
tokio_stream::wrappers::ReceiverStream<Result<proto::WatchServiceRoutesResponse, Status>>;
1219+
async fn watch_service_routes(
1220+
&self,
1221+
_: tonic::Request<proto::WatchServiceRoutesRequest>,
1222+
) -> Result<Response<Self::WatchServiceRoutesStream>, Status> {
1223+
Err(Status::unimplemented("unused"))
1224+
}
1225+
}
1226+
11981227
/// Spin up the mock gateway, return its endpoint URL.
11991228
async fn start_mock(state: Arc<MockState>) -> String {
12001229
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -1204,11 +1233,15 @@ async fn start_mock(state: Arc<MockState>) -> String {
12041233
let updates = SandboxUpdatesServer::new(TestOpenShell {
12051234
state: state.clone(),
12061235
});
1236+
let discovery = proto::service_discovery_server::ServiceDiscoveryServer::new(TestOpenShell {
1237+
state: state.clone(),
1238+
});
12071239
let svc = OpenShellServer::new(TestOpenShell { state });
12081240
tokio::spawn(async move {
12091241
let _ = tonic::transport::Server::builder()
12101242
.add_service(svc)
12111243
.add_service(updates)
1244+
.add_service(discovery)
12121245
.serve_with_incoming(stream)
12131246
.await;
12141247
});
@@ -2457,6 +2490,58 @@ async fn raw_sandbox_updates_shares_transport_and_live_auth_slot() {
24572490
assert_eq!(*state.last_update.lock().await, Some(request));
24582491
}
24592492

2493+
#[tokio::test]
2494+
async fn raw_discovery_shares_transport_and_refreshes_the_live_auth_slot() {
2495+
let state = Arc::new(MockState {
2496+
require_bearer: Some("Bearer fresh-token".into()),
2497+
..Default::default()
2498+
});
2499+
let endpoint = start_mock(state).await;
2500+
let calls = Arc::new(AtomicU32::new(0));
2501+
let mut config = ClientConfig::new(&endpoint);
2502+
config.auth = Some(AuthConfig::Oidc {
2503+
token: "stale-token".into(),
2504+
expires_at: Some(
2505+
std::time::SystemTime::now()
2506+
.duration_since(std::time::UNIX_EPOCH)
2507+
.unwrap()
2508+
.as_secs()
2509+
+ 5,
2510+
),
2511+
refresh: Some(Arc::new(OneShotRefresher {
2512+
calls: calls.clone(),
2513+
})),
2514+
});
2515+
let client = OpenShellClient::connect(config).await.unwrap();
2516+
let mut discovery = client.raw_service_discovery();
2517+
let request = proto::GetServiceRouteSnapshotRequest {
2518+
workspace_scope: Some(proto::workspace_selector("team")),
2519+
};
2520+
assert_eq!(
2521+
discovery
2522+
.get_service_route_snapshot(request.clone())
2523+
.await
2524+
.unwrap_err()
2525+
.code(),
2526+
tonic::Code::Unauthenticated
2527+
);
2528+
assert_eq!(calls.load(Ordering::SeqCst), 0);
2529+
client
2530+
.raw_service_discovery_fresh()
2531+
.await
2532+
.unwrap()
2533+
.get_service_route_snapshot(request.clone())
2534+
.await
2535+
.unwrap();
2536+
assert_eq!(calls.load(Ordering::SeqCst), 1);
2537+
discovery.get_service_route_snapshot(request).await.unwrap();
2538+
client
2539+
.raw_grpc()
2540+
.health(proto::HealthRequest {})
2541+
.await
2542+
.unwrap();
2543+
}
2544+
24602545
#[tokio::test]
24612546
async fn watch_logs_forwards_logs_and_warnings() {
24622547
let state = Arc::new(MockState {

‎crates/openshell-server/README.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,3 +295,47 @@ timeouts; bounded record attempts prevent a malformed or stalled record from
295295
starving later cleanup. Failed attempts are revisited on the next scan.
296296
Discovery consumers must not treat these
297297
records as application health or external ingress readiness.
298+
299+
## Workspace service discovery
300+
301+
Both discovery RPCs require `supervisor_app_listener.enabled = true`. When the
302+
listener is disabled, they return `FAILED_PRECONDITION` without collecting routes
303+
or starting a watch.
304+
305+
`openshell.v1.ServiceDiscovery.GetServiceRouteSnapshot` and `WatchServiceRoutes` expose accepted installations
306+
for one explicit active workspace. They require `sandbox:read` and workspace
307+
user access; omitted/all-workspaces selectors and sandbox principals are rejected.
308+
Dedicated discovery machine grants are separate work.
309+
310+
Each successful response replaces the complete view. Consumers preserve the
311+
returned hostname as TLS SNI and HTTP authority when dialing the supervisor
312+
endpoint, remove absent routes, and expire cached entries at `expires_at` even
313+
when discovery is unavailable. An error is not an empty replacement. The opaque
314+
snapshot revision includes lease renewals; `installation_version` remains stable
315+
across those renewals and changes when installation identity changes. These
316+
records establish neither application health nor ingress readiness.
317+
318+
Collection shares the provider catalog, global settings and bounded service
319+
declarations within one scan, and checks their versions before publication.
320+
Large or unsuitable declaration batches retain the per-sandbox lookup. Sandbox
321+
policy, provider records, settings and live ownership remain individually checked.
322+
Before publication, discovery reads the latest accepted receipts: unchanged
323+
serving identities can use renewed deadlines after configuration revalidation;
324+
replacement or withdrawn installations are omitted. Lease renewals do not
325+
invalidate the whole view, and reads never manufacture or extend a lease.
326+
This is not a cross-resource transaction. Reads are bounded
327+
to 1,000 records, 4,096 routes, 4 MiB, and ten seconds. A per-workspace cache shares
328+
one collection for a one-second refresh interval, retains at most 16 workspaces,
329+
and never returns expired routes. At most four collections and 16 unary snapshot
330+
requests run concurrently per gateway. Collections wait for a free slot within
331+
the ten-second timeout. Unary admission permits four requests per
332+
principal and eight per workspace. Overflow returns `RESOURCE_EXHAUSTED`; storage
333+
failure, configuration changes during collection or timeout return `UNAVAILABLE`;
334+
malformed records return `INTERNAL`.
335+
Watches recheck bearer authentication and workspace authorization each second,
336+
use a one-message buffer, and end after one minute or a five-second blocked send.
337+
Each gateway allows 32 watches, at most four per principal and 16 per workspace.
338+
Cache reuse adds at most one refresh interval to collection freshness; consumers
339+
must independently honor the advertised lease expiry.
340+
Reconnect and relist on stream termination; revisions are opaque
341+
equality tokens, not resumable cursors or an ordering across gateway replicas.

‎crates/openshell-server/src/grpc/mod.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub mod supervisor_host;
1414
pub use sandbox::mint_persisted_authentication;
1515
mod service;
1616
pub mod service_advertisement;
17+
pub mod service_discovery;
1718
mod validation;
1819
pub mod workspace;
1920

@@ -1435,3 +1436,22 @@ mod tests {
14351436
assert_eq!(public.protocol_minor, 2);
14361437
}
14371438
}
1439+
1440+
#[tonic::async_trait]
1441+
impl openshell_core::proto::service_discovery_server::ServiceDiscovery for OpenShellService {
1442+
async fn get_service_route_snapshot(
1443+
&self,
1444+
request: Request<openshell_core::proto::GetServiceRouteSnapshotRequest>,
1445+
) -> Result<Response<openshell_core::proto::GetServiceRouteSnapshotResponse>, Status> {
1446+
service_discovery::get_snapshot(&self.state, request).await
1447+
}
1448+
1449+
type WatchServiceRoutesStream = service_discovery::RouteWatchStream;
1450+
1451+
async fn watch_service_routes(
1452+
&self,
1453+
request: Request<openshell_core::proto::WatchServiceRoutesRequest>,
1454+
) -> Result<Response<Self::WatchServiceRoutesStream>, Status> {
1455+
service_discovery::watch(&self.state, request).await
1456+
}
1457+
}

‎crates/openshell-server/src/grpc/policy.rs‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@
1111
#![allow(clippy::items_after_statements)] // DB_PORTS const inside function
1212

1313
mod config_inputs;
14+
mod discovery_inputs;
1415
mod endpoint_status;
1516
mod provisioning_clock;
1617
#[cfg(test)]
1718
mod token_grant_owners_tests;
1819
pub use config_inputs::{SandboxConfigInputs, load_sandbox_config_inputs};
20+
pub(super) use discovery_inputs::DiscoveryConfigInputs;
1921
pub use provisioning_clock::configuration_change;
2022

2123
pub(super) use endpoint_status::{
@@ -2924,19 +2926,35 @@ pub async fn build_sandbox_config_snapshot_from_inputs(
29242926
state: &ServerState,
29252927
inputs: &SandboxConfigInputs,
29262928
) -> Result<SandboxConfigSnapshot, Status> {
2927-
let sandbox = &inputs.sandbox;
2929+
build_sandbox_config_snapshot_with_sources(
2930+
state,
2931+
&inputs.sandbox,
2932+
&inputs.catalog,
2933+
&inputs.provider_records,
2934+
&inputs.global_settings,
2935+
inputs.latest_policy.as_ref(),
2936+
None,
2937+
)
2938+
.await
2939+
}
2940+
2941+
async fn build_sandbox_config_snapshot_with_sources(
2942+
state: &ServerState,
2943+
sandbox: &Sandbox,
2944+
provider_profile_catalog: &EffectiveProviderProfileCatalog,
2945+
provider_records: &[super::provider::ProviderEnvironmentRecord],
2946+
global_settings: &StoredSettings,
2947+
latest: Option<&PolicyRecord>,
2948+
service_routes: Option<Vec<openshell_core::proto::SandboxServiceRoute>>,
2949+
) -> Result<SandboxConfigSnapshot, Status> {
29282950
let sandbox_id = sandbox.object_id().to_string();
29292951
let workspace = sandbox.object_workspace().to_string();
2930-
let provider_profile_catalog = &inputs.catalog;
2931-
let provider_records = &inputs.provider_records;
2932-
let global_settings = &inputs.global_settings;
29332952

29342953
let global_policy = decode_policy_from_global_settings(global_settings)?;
29352954
let mut global_policy_version: u32 = 0;
29362955

29372956
// Under a global override, only the sandbox version metadata is observed;
29382957
// the dormant payload is neither decoded nor validated.
2939-
let latest = inputs.latest_policy.as_ref();
29402958

29412959
let (mut policy, version, mut policy_hash, policy_source) =
29422960
if let Some(global_policy) = global_policy {
@@ -3084,7 +3102,10 @@ pub async fn build_sandbox_config_snapshot_from_inputs(
30843102
.filter(|_| matches!(policy_source, PolicySource::Global)),
30853103
)?;
30863104

3087-
let service_routes = super::service::configured_app_routes(state, sandbox).await?;
3105+
let service_routes = match service_routes {
3106+
Some(routes) => routes,
3107+
None => super::service::configured_app_routes(state, sandbox).await?,
3108+
};
30883109
// Include the allowlist in delivery identity so a service edit is not
30893110
// coalesced away as a duplicate policy/settings snapshot.
30903111
if !service_routes.is_empty() {

0 commit comments

Comments
 (0)