Skip to main content

adk_code/vertex_sandbox/
client.rs

1//! REST client for the Agent Engine `sandboxEnvironments` surface.
2
3use 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
23/// Maximum sandboxes per list page (service cap).
24const LIST_PAGE_SIZE: usize = 100;
25/// Upper bound on list pagination rounds, so a server that keeps returning
26/// page tokens cannot spin this client forever.
27const LIST_MAX_PAGES: usize = 1_000;
28
29/// Client for Agent Engine sandbox environments.
30///
31/// Wraps the v1beta1 `sandboxEnvironments` REST surface: create and delete
32/// are long-running operations (polled to completion), get and list are
33/// plain reads, and `:execute` is synchronous. Resource names in every
34/// follow-up request (operation polls, re-GETs, executes, deletes) are
35/// validated against the configured project and location.
36///
37/// # Example
38///
39/// ```rust,no_run
40/// use adk_code::vertex_sandbox::{
41///     CreateSandboxRequest, VertexSandboxClient, VertexSandboxConfig,
42/// };
43///
44/// # async fn run() -> adk_core::Result<()> {
45/// let client = VertexSandboxClient::new_with_adc(VertexSandboxConfig::new(
46///     "my-project",
47///     "us-central1",
48/// ))?;
49/// let sandbox = client
50///     .create_sandbox("4242", CreateSandboxRequest::new("my-sandbox").with_ttl("3600s"))
51///     .await?;
52/// # let _ = sandbox;
53/// # Ok(())
54/// # }
55/// ```
56#[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    /// Creates a client using Application Default Credentials (ADC).
67    ///
68    /// # Errors
69    ///
70    /// Returns an error when ADC cannot be constructed, the endpoint is not
71    /// a valid secure origin, or the HTTP client cannot be built.
72    pub fn new_with_adc(config: VertexSandboxConfig) -> Result<Self> {
73        Self::build(config, None)
74    }
75
76    /// Creates a client with explicit credentials.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error when the endpoint is not a valid secure origin or
81    /// the HTTP client cannot be built.
82    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    /// Creates a sandbox under the given reasoning engine and waits for the
105    /// create operation to complete.
106    ///
107    /// `engine` is a full `projects/*/locations/*/reasoningEngines/*` name
108    /// or a bare numeric engine ID resolved against the configured project
109    /// and location. The operation response can be sparse, so the created
110    /// sandbox is re-fetched by name before returning.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error when the engine reference or display name is
115    /// invalid, the request fails, the operation completes with an error or
116    /// times out, or the created sandbox cannot be fetched.
117    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        // The operation response carries the created sandbox but may be
149        // sparse — read only the name, then re-GET the full resource.
150        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    /// Fetches a sandbox by resource name.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error when the name is outside the configured scope, the
165    /// request fails (a missing sandbox is a not-found error), or the
166    /// response is not a sandbox resource.
167    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    /// Lists every sandbox under the given reasoning engine, following
175    /// pagination (`pageSize` 100, the service cap).
176    ///
177    /// # Errors
178    ///
179    /// Returns an error when the engine reference is invalid, a page
180    /// request fails, or the server keeps returning page tokens past the
181    /// internal pagination bound.
182    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    /// Runs `:execute` on a sandbox with raw chunks. Synchronous — no LRO.
216    ///
217    /// Every `:execute` call resets the sandbox TTL server-side. The
218    /// request is rejected before sending when the decoded chunk payloads
219    /// exceed the 100 MB per-request file limit.
220    ///
221    /// # Errors
222    ///
223    /// Returns an error when the name is outside the configured scope, the
224    /// payload exceeds the request limit, the request fails, or the
225    /// response is not an `:execute` response.
226    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        // base64 decodes to at most 3 bytes per 4 encoded characters.
230        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    /// Runs source code in a sandbox using the code-execution chunk
252    /// conventions and decodes the outputs.
253    ///
254    /// # Example
255    ///
256    /// ```rust,no_run
257    /// use adk_code::vertex_sandbox::{InputFile, VertexSandboxClient, VertexSandboxConfig};
258    ///
259    /// # async fn run(client: VertexSandboxClient, sandbox: &str) -> adk_core::Result<()> {
260    /// let files = [InputFile::new("data.csv", "text/csv", b"a,b\n1,2\n".to_vec())];
261    /// let result = client
262    ///     .execute_code(sandbox, "print(open('data.csv').read())", &files)
263    ///     .await?;
264    /// println!("{}", result.stdout);
265    /// # Ok(())
266    /// # }
267    /// ```
268    ///
269    /// # Errors
270    ///
271    /// Returns an error when a filename is blank, the files exceed the
272    /// 100 MB per-request limit, the execution fails, or the outputs
273    /// cannot be decoded.
274    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    /// Deletes a sandbox and waits for the delete operation to complete.
302    ///
303    /// # Errors
304    ///
305    /// Returns an error when the name is outside the configured scope, the
306    /// request fails, or the operation completes with an error or times out.
307    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    /// Resolves a full engine resource name or bare numeric ID against the
325    /// configured project and location.
326    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    /// Rejects sandbox names outside the configured scope or with the wrong
349    /// shape, so a compromised or buggy server cannot redirect follow-up
350    /// requests elsewhere.
351    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}