Skip to content

Commit 316dd66

Browse files
committed
fix(discovery): share collection inputs and refresh accepted leases
Signed-off-by: Taylor Mutch <taylormutch@gmail.com>
1 parent 29a1edc commit 316dd66

8 files changed

Lines changed: 692 additions & 30 deletions

File tree

‎crates/openshell-server/README.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -315,15 +315,23 @@ snapshot revision includes lease renewals; `installation_version` remains stable
315315
across those renewals and changes when installation identity changes. These
316316
records establish neither application health nor ingress readiness.
317317

318-
Collection validates each installation once; lease renewals during a scan do not
319-
invalidate the view. This is not a cross-resource transaction. Reads are bounded
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
320327
to 1,000 records, 4,096 routes, 4 MiB, and ten seconds. A per-workspace cache shares
321328
one collection for a one-second refresh interval, retains at most 16 workspaces,
322329
and never returns expired routes. At most four collections and 16 unary snapshot
323330
requests run concurrently per gateway. Collections wait for a free slot within
324331
the ten-second timeout. Unary admission permits four requests per
325332
principal and eight per workspace. Overflow returns `RESOURCE_EXHAUSTED`; storage
326-
failure or timeout returns `UNAVAILABLE`; malformed records return `INTERNAL`.
333+
failure, configuration changes during collection or timeout return `UNAVAILABLE`;
334+
malformed records return `INTERNAL`.
327335
Watches recheck bearer authentication and workspace authorization each second,
328336
use a one-message buffer, and end after one minute or a five-second blocked send.
329337
Each gateway allows 32 watches, at most four per principal and 16 per workspace.

‎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() {
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Collection-local inputs. No validated configuration survives a collection.
5+
6+
use std::collections::HashMap;
7+
8+
use openshell_core::proto::{Sandbox, SandboxConfigSnapshot, ServiceEndpoint};
9+
use openshell_core::{ObjectId, ObjectName, ObjectWorkspace, SetResourceVersion};
10+
use prost::Message as _;
11+
use tonic::Status;
12+
13+
use super::super::StoredSettings;
14+
use super::super::provider::load_provider_environment_records;
15+
use super::{build_sandbox_config_snapshot_with_sources, load_global_settings};
16+
use crate::ServerState;
17+
use crate::persistence::{ObjectListQuery, ObjectType};
18+
use crate::policy_store::PolicyStoreExt as _;
19+
use crate::provider_profile_sources::EffectiveProviderProfileCatalog;
20+
21+
const MAX_DECLARATIONS: usize = 4096;
22+
const MAX_DECLARATION_BYTES: usize = 4 * 1024 * 1024;
23+
24+
#[derive(PartialEq)]
25+
struct Declarations {
26+
versions: Vec<(String, u64)>,
27+
by_sandbox: HashMap<String, Vec<ServiceEndpoint>>,
28+
}
29+
30+
impl Declarations {
31+
/// Bulk reads are an optimization, not an additional workspace limit.
32+
/// Legacy/unsuitable rows and large workspaces retain the original lookup.
33+
async fn load(state: &ServerState, workspace: &str) -> Result<Option<Self>, Status> {
34+
let mut result = Self {
35+
versions: Vec::new(),
36+
by_sandbox: HashMap::new(),
37+
};
38+
let mut cursor = None;
39+
let mut bytes = 0usize;
40+
loop {
41+
let page = state
42+
.store
43+
.list_object_page(
44+
ServiceEndpoint::object_type(),
45+
ObjectListQuery::Workspace(workspace),
46+
cursor.as_ref(),
47+
128,
48+
)
49+
.await
50+
.map_err(|_| Status::unavailable("service declarations unavailable"))?;
51+
for record in page.records {
52+
bytes = bytes
53+
.saturating_add(record.payload.len())
54+
.saturating_add(record.labels.as_ref().map_or(0, String::len));
55+
if bytes > MAX_DECLARATION_BYTES || result.versions.len() >= MAX_DECLARATIONS {
56+
return Ok(None);
57+
}
58+
let Ok(mut endpoint) = ServiceEndpoint::decode(record.payload.as_slice()) else {
59+
return Ok(None);
60+
};
61+
endpoint.set_resource_version(record.resource_version);
62+
let Ok(labels) = serde_json::from_str::<HashMap<String, String>>(
63+
record.labels.as_deref().unwrap_or("{}"),
64+
) else {
65+
return Ok(None);
66+
};
67+
let Some(meta) = &endpoint.metadata else {
68+
return Ok(None);
69+
};
70+
if endpoint.object_id() != record.id
71+
|| endpoint.object_workspace() != workspace
72+
|| meta.labels != labels
73+
{
74+
return Ok(None);
75+
}
76+
result.versions.push((record.id, record.resource_version));
77+
if let Some(name) = labels.get("sandbox") {
78+
result
79+
.by_sandbox
80+
.entry(name.clone())
81+
.or_default()
82+
.push(endpoint);
83+
}
84+
}
85+
let Some(next) = page.next_cursor else {
86+
break;
87+
};
88+
cursor = Some(next);
89+
}
90+
result.versions.sort();
91+
// Stable equality even if an update changes the store's listing order.
92+
for endpoints in result.by_sandbox.values_mut() {
93+
endpoints.sort_by(|a, b| a.object_id().cmp(b.object_id()));
94+
}
95+
Ok(Some(result))
96+
}
97+
}
98+
99+
pub struct DiscoveryConfigInputs {
100+
workspace: String,
101+
catalog: EffectiveProviderProfileCatalog,
102+
global_settings: StoredSettings,
103+
declarations: Option<Declarations>,
104+
}
105+
106+
impl DiscoveryConfigInputs {
107+
pub(crate) async fn load(state: &ServerState, workspace: &str) -> Result<Self, Status> {
108+
let (catalog, global_settings, declarations) = tokio::try_join!(
109+
state
110+
.provider_profile_sources
111+
.snapshot_catalog(&state.store, workspace),
112+
load_global_settings(&state.store),
113+
Declarations::load(state, workspace),
114+
)?;
115+
Ok(Self {
116+
workspace: workspace.into(),
117+
catalog,
118+
global_settings,
119+
declarations,
120+
})
121+
}
122+
123+
pub(crate) async fn ensure_current(&self, state: &ServerState) -> Result<(), Status> {
124+
let next = Self::load(state, &self.workspace).await?;
125+
if self.catalog.revision() != next.catalog.revision()
126+
// A source-owned revision cannot replace a content comparison,
127+
// including the platform fallback beneath workspace overrides.
128+
|| self.catalog.list_all_scoped_profiles() != next.catalog.list_all_scoped_profiles()
129+
|| self.global_settings.record_id != next.global_settings.record_id
130+
|| self.global_settings.resource_version != next.global_settings.resource_version
131+
|| self.global_settings.revision != next.global_settings.revision
132+
|| self.declarations != next.declarations
133+
{
134+
return Err(Status::unavailable(
135+
"discovery configuration changed during collection",
136+
));
137+
}
138+
Ok(())
139+
}
140+
141+
pub(crate) async fn build(
142+
&self,
143+
state: &ServerState,
144+
sandbox: &Sandbox,
145+
) -> Result<SandboxConfigSnapshot, Status> {
146+
if sandbox.object_workspace() != self.workspace {
147+
return Err(Status::internal("installation workspace mismatch"));
148+
}
149+
let providers = sandbox
150+
.spec
151+
.as_ref()
152+
.map_or(&[][..], |spec| spec.providers.as_slice());
153+
let (records, latest) = tokio::try_join!(
154+
load_provider_environment_records(
155+
&state.store,
156+
&state.refresh,
157+
&self.workspace,
158+
providers
159+
),
160+
async {
161+
state
162+
.store
163+
.get_latest_policy(sandbox.object_id())
164+
.await
165+
.map_err(|_| Status::unavailable("sandbox policy unavailable"))
166+
},
167+
)?;
168+
let routes = if let Some(declarations) = &self.declarations {
169+
let endpoints = declarations
170+
.by_sandbox
171+
.get(sandbox.object_name())
172+
.cloned()
173+
.unwrap_or_default();
174+
if endpoints.len()
175+
> usize::try_from(super::super::service::MAX_APP_SERVICE_ROUTES)
176+
.expect("bounded route limit")
177+
{
178+
return Err(Status::resource_exhausted(
179+
"too many application service declarations",
180+
));
181+
}
182+
Some(super::super::service::configured_app_routes_from_endpoints(
183+
state, sandbox, endpoints,
184+
))
185+
} else {
186+
None
187+
};
188+
build_sandbox_config_snapshot_with_sources(
189+
state,
190+
sandbox,
191+
&self.catalog,
192+
&records,
193+
&self.global_settings,
194+
latest.as_ref(),
195+
routes,
196+
)
197+
.await
198+
}
199+
}

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::persistence::{ObjectListQuery, ObjectType, WriteCondition};
2525
use crate::service_routing;
2626

2727
const MAX_SERVICE_NAME_LEN: usize = super::MAX_ROUTABLE_NAME_LEN;
28-
const MAX_APP_SERVICE_ROUTES: u32 = 1024;
28+
pub(super) const MAX_APP_SERVICE_ROUTES: u32 = 1024;
2929

3030
#[cfg(test)]
3131
#[derive(Default)]
@@ -421,8 +421,22 @@ pub(super) async fn configured_app_routes(
421421
if !state.config.supervisor_app_listener.enabled {
422422
return Ok(Vec::new());
423423
}
424-
let mut service_routes: Vec<_> = app_service_endpoints(state, sandbox)
425-
.await?
424+
Ok(configured_app_routes_from_endpoints(
425+
state,
426+
sandbox,
427+
app_service_endpoints(state, sandbox).await?,
428+
))
429+
}
430+
431+
pub(super) fn configured_app_routes_from_endpoints(
432+
state: &ServerState,
433+
sandbox: &Sandbox,
434+
endpoints: Vec<ServiceEndpoint>,
435+
) -> Vec<openshell_core::proto::SandboxServiceRoute> {
436+
if !state.config.supervisor_app_listener.enabled {
437+
return Vec::new();
438+
}
439+
let mut service_routes: Vec<_> = endpoints
426440
.into_iter()
427441
.filter(|ep| {
428442
ep.sandbox_id == sandbox.object_id()
@@ -441,7 +455,7 @@ pub(super) async fn configured_app_routes(
441455
})
442456
.collect();
443457
service_routes.sort_by(|a, b| a.name.cmp(&b.name));
444-
Ok(service_routes)
458+
service_routes
445459
}
446460

447461
async fn app_service_endpoints(

0 commit comments

Comments
 (0)