|
| 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 | +} |
0 commit comments