1use super::types::{
4 Chunk, CreateSandboxRequest, ExecuteRequest, ExecuteResponse, InputFile, ListSandboxesResponse,
5 SandboxEnvironment, SandboxExecutionResult, decode_output_chunks, encode_code_chunk,
6 encode_file_chunk,
7};
8use super::{
9 CREATE_POLL_TIMEOUT, HTTP_REQUEST_TIMEOUT, MAX_REQUEST_FILE_BYTES, MAX_RESPONSE_BYTES,
10 VertexSandboxConfig, errors,
11};
12use adk_core::Result;
13use adk_gcp::{
14 GcpHttpClient, LroPoller, VertexResourceName, is_canonical_reasoning_engine_id,
15 is_scoped_resource_name, truncate_for_error,
16};
17use google_cloud_auth::credentials::Credentials;
18use reqwest::Method;
19use serde_json::Value;
20use std::time::Duration;
21use tracing::debug;
22
23const LIST_PAGE_SIZE: usize = 100;
25const LIST_MAX_PAGES: usize = 1_000;
28
29#[derive(Debug)]
57pub struct VertexSandboxClient {
58 http: GcpHttpClient,
59 project_id: String,
60 location: String,
61 create_poller: LroPoller,
62 delete_poller: LroPoller,
63}
64
65impl VertexSandboxClient {
66 pub fn new_with_adc(config: VertexSandboxConfig) -> Result<Self> {
73 Self::build(config, None)
74 }
75
76 pub fn with_credentials(config: VertexSandboxConfig, credentials: Credentials) -> Result<Self> {
83 Self::build(config, Some(credentials))
84 }
85
86 fn build(config: VertexSandboxConfig, credentials: Option<Credentials>) -> Result<Self> {
87 let mut builder = GcpHttpClient::builder(errors(), config.endpoint())
88 .request_timeout(HTTP_REQUEST_TIMEOUT)
89 .max_response_bytes(MAX_RESPONSE_BYTES);
90 if let Some(credentials) = credentials {
91 builder = builder.credentials(credentials);
92 }
93 Ok(Self {
94 http: builder.build()?,
95 project_id: config.project_id,
96 location: config.location,
97 create_poller: LroPoller::new()
98 .with_poll_timeout(CREATE_POLL_TIMEOUT)
99 .with_max_delay(Duration::from_secs(5)),
100 delete_poller: LroPoller::new(),
101 })
102 }
103
104 pub async fn create_sandbox(
118 &self,
119 engine: &str,
120 request: CreateSandboxRequest,
121 ) -> Result<SandboxEnvironment> {
122 let errors = self.http.errors();
123 let engine = self.resolve_engine(engine)?;
124 if request.display_name.trim().is_empty() {
125 return Err(errors.invalid_input(
126 "vertex sandbox display name must not be blank; pass a non-empty display name to CreateSandboxRequest::new",
127 ));
128 }
129 let body = request.into_body();
130 let http_request = self
131 .http
132 .request(Method::POST, &format!("{engine}/sandboxEnvironments"))
133 .await?
134 .json(&body);
135 let operation = self.http.send_value(http_request).await?;
136 let response = self
137 .create_poller
138 .wait_for_operation(
139 &self.http,
140 operation,
141 "sandbox create",
142 true,
143 &self.project_id,
144 &self.location,
145 )
146 .await?
147 .unwrap_or(Value::Null);
148 let name = response.get("name").and_then(Value::as_str).ok_or_else(|| {
151 errors.invalid_response(
152 "vertex sandbox create operation response did not contain a sandbox name; inspect the operation in Google Cloud",
153 )
154 })?;
155 self.validate_sandbox_name(name)?;
156 debug!(sandbox.name = name, "sandbox created, fetching full resource");
157 self.get_sandbox(name).await
158 }
159
160 pub async fn get_sandbox(&self, name: &str) -> Result<SandboxEnvironment> {
168 self.validate_sandbox_name(name)?;
169 let request = self.http.request(Method::GET, name).await?;
170 let value = self.http.send_value(request).await?;
171 self.parse_sandbox(value)
172 }
173
174 pub async fn list_sandboxes(&self, engine: &str) -> Result<Vec<SandboxEnvironment>> {
183 let errors = self.http.errors();
184 let engine = self.resolve_engine(engine)?;
185 let path = format!("{engine}/sandboxEnvironments");
186 let mut sandboxes = Vec::new();
187 let mut page_token: Option<String> = None;
188 for _ in 0..LIST_MAX_PAGES {
189 let mut request = self
190 .http
191 .request(Method::GET, &path)
192 .await?
193 .query(&[("pageSize", LIST_PAGE_SIZE.to_string())]);
194 if let Some(token) = &page_token {
195 request = request.query(&[("pageToken", token)]);
196 }
197 let value = self.http.send_value(request).await?;
198 let page: ListSandboxesResponse = serde_json::from_value(value).map_err(|error| {
199 errors.invalid_response(format!(
200 "failed to parse vertex sandbox list response: {}",
201 truncate_for_error(&error.to_string()),
202 ))
203 })?;
204 sandboxes.extend(page.sandbox_environments);
205 match page.next_page_token.filter(|token| !token.is_empty()) {
206 Some(token) => page_token = Some(token),
207 None => return Ok(sandboxes),
208 }
209 }
210 Err(errors.invalid_response(format!(
211 "vertex sandbox list returned page tokens for more than {LIST_MAX_PAGES} pages; refusing to paginate further",
212 )))
213 }
214
215 pub async fn execute(&self, name: &str, inputs: Vec<Chunk>) -> Result<Vec<Chunk>> {
227 let errors = self.http.errors();
228 self.validate_sandbox_name(name)?;
229 let decoded_bytes: usize = inputs.iter().map(|chunk| chunk.data.len() / 4 * 3).sum();
231 if decoded_bytes > MAX_REQUEST_FILE_BYTES {
232 return Err(errors.invalid_input(format!(
233 "vertex sandbox :execute payload of ~{decoded_bytes} bytes exceeds the {MAX_REQUEST_FILE_BYTES}-byte (100 MB) per-request limit; split the input files across executions",
234 )));
235 }
236 let request = self
237 .http
238 .request(Method::POST, &format!("{name}:execute"))
239 .await?
240 .json(&ExecuteRequest { inputs });
241 let value = self.http.send_value(request).await?;
242 let response: ExecuteResponse = serde_json::from_value(value).map_err(|error| {
243 errors.invalid_response(format!(
244 "failed to parse vertex sandbox :execute response: {}",
245 truncate_for_error(&error.to_string()),
246 ))
247 })?;
248 Ok(response.outputs)
249 }
250
251 pub async fn execute_code(
275 &self,
276 name: &str,
277 code: &str,
278 input_files: &[InputFile],
279 ) -> Result<SandboxExecutionResult> {
280 let errors = self.http.errors();
281 let file_bytes: usize = input_files.iter().map(|file| file.data.len()).sum();
282 if file_bytes > MAX_REQUEST_FILE_BYTES {
283 return Err(errors.invalid_input(format!(
284 "vertex sandbox input files total {file_bytes} bytes, exceeding the {MAX_REQUEST_FILE_BYTES}-byte (100 MB) per-request limit; split the files across executions",
285 )));
286 }
287 let mut inputs = Vec::with_capacity(input_files.len() + 1);
288 inputs.push(encode_code_chunk(code));
289 for file in input_files {
290 if file.name.trim().is_empty() {
291 return Err(errors.invalid_input(
292 "vertex sandbox input file names must not be blank; set InputFile::name to the filename the code should see",
293 ));
294 }
295 inputs.push(encode_file_chunk(file));
296 }
297 let outputs = self.execute(name, inputs).await?;
298 decode_output_chunks(&outputs)
299 }
300
301 pub async fn delete_sandbox(&self, name: &str) -> Result<()> {
308 self.validate_sandbox_name(name)?;
309 let request = self.http.request(Method::DELETE, name).await?;
310 let operation = self.http.send_value(request).await?;
311 self.delete_poller
312 .wait_for_operation(
313 &self.http,
314 operation,
315 "sandbox delete",
316 false,
317 &self.project_id,
318 &self.location,
319 )
320 .await?;
321 Ok(())
322 }
323
324 fn resolve_engine(&self, engine: &str) -> Result<VertexResourceName> {
327 let errors = self.http.errors();
328 if let Some(name) = VertexResourceName::parse(engine) {
329 if name.project_id() != self.project_id || name.location() != self.location {
330 return Err(errors.invalid_input(format!(
331 "reasoning engine '{}' does not belong to projects/{}/locations/{}; construct the client with a matching VertexSandboxConfig",
332 truncate_for_error(engine),
333 self.project_id,
334 self.location,
335 )));
336 }
337 return Ok(name);
338 }
339 if is_canonical_reasoning_engine_id(engine) {
340 return Ok(VertexResourceName::new(&self.project_id, &self.location, engine));
341 }
342 Err(errors.invalid_input(format!(
343 "reasoning engine '{}' is neither a full projects/*/locations/*/reasoningEngines/* name nor a canonical numeric engine ID",
344 truncate_for_error(engine),
345 )))
346 }
347
348 fn validate_sandbox_name(&self, name: &str) -> Result<()> {
352 let errors = self.http.errors();
353 if !is_scoped_resource_name(name, &self.project_id, &self.location) {
354 return Err(errors.invalid_input(format!(
355 "sandbox name '{}' does not belong to projects/{}/locations/{}",
356 truncate_for_error(name),
357 self.project_id,
358 self.location,
359 )));
360 }
361 let segments: Vec<&str> = name.split('/').collect();
362 let well_formed = matches!(
363 segments.as_slice(),
364 ["projects", _, "locations", _, "reasoningEngines", engine, "sandboxEnvironments", sandbox]
365 if !engine.is_empty() && !sandbox.is_empty()
366 );
367 if !well_formed {
368 return Err(errors.invalid_input(format!(
369 "sandbox name '{}' is not a projects/*/locations/*/reasoningEngines/*/sandboxEnvironments/* resource name",
370 truncate_for_error(name),
371 )));
372 }
373 Ok(())
374 }
375
376 fn parse_sandbox(&self, value: Value) -> Result<SandboxEnvironment> {
377 serde_json::from_value(value).map_err(|error| {
378 self.http.errors().invalid_response(format!(
379 "failed to parse vertex sandbox resource: {}",
380 truncate_for_error(&error.to_string()),
381 ))
382 })
383 }
384}