Skip to main content

gadk_cli/deploy/
cloudrun.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `gadk deploy cloudrun`.
17//!
18//! The flag structs keep ADK's shape (the nested flag groups, field for field in ADK's order) so
19//! [`CloudRunFlags::go_v`] can print the one-line flags dump ADK's tool prints; gadk's
20//! additions (`bin`, `target`) sit after those fields and are never printed.
21//!
22//! gadk builds the image remotely from the staged Cargo workspace (the `"Staging source"` step
23//! takes the slot of ADK's `"Compiling server"`) with the two-stage Dockerfile of
24//! [`crate::stage::dockerfile`]; the checks, the `CMD` array, the gcloud invocations and the
25//! console output follow ADK's.
26
27use std::fmt::Write as _;
28use std::fs::{self, OpenOptions};
29use std::io::{self, Write as _};
30use std::os::unix::fs::OpenOptionsExt;
31use std::path::{Path, PathBuf};
32
33use clap::{ArgMatches, Command};
34use gadk_platform::{GoDuration, go_path_join, go_quote};
35
36use crate::Env;
37use crate::flags::{
38    bool_flag, bool_value, duration_flag, duration_value, int_flag, int_value, passed,
39    pflag_command, stray_args, string_flag, string_value,
40};
41use crate::stage::{BuilderStage, SourceTree, dockerfile, make_temp};
42use crate::target::{
43    COMPILED_RUSTC_VERSION, CargoTarget, builder_image, builder_rust_version,
44    check_path_dependencies, resolve,
45};
46use crate::util::{
47    Printer, center_string, log_command, log_start_stop, validate_dockerfile_safe,
48    validate_shell_arg_safe,
49};
50
51/// The command's short description.
52pub const SHORT: &str = "Deploys the application to cloudrun.";
53/// The command's long description (tabs and trailing spaces preserved).
54// The first sentence says the image is built from the staged Cargo workspace.
55pub const LONG: &str = "Deployment prepares a Dockerfile which builds the server executable from the staged Cargo workspace.\n\tService on Cloudrun is created using this information. \n\tLocal proxy adding authentication is started. \n\t";
56
57/// The four OIDC flags whose passed state is recorded.
58pub const TRIGGER_OIDC_FLAG_NAMES: [&str; 4] = [
59    "pubsub_oidc_audience",
60    "pubsub_oidc_service_accounts",
61    "eventarc_oidc_audience",
62    "eventarc_oidc_service_accounts",
63];
64
65/// The gcloud flags.
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct GCloudFlags {
68    /// `--region` (`-r`): the GCP region.
69    pub region: String,
70    /// `--project_name` (`-p`): the GCP project.
71    pub project_name: String,
72}
73
74/// The trigger configuration flags.
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
76pub struct TriggerConfigFlags {
77    /// `--<trigger>_max_retries`: the retries for HTTP 429 errors (default 3).
78    pub max_retries: i64,
79    /// `--<trigger>_base_delay`: the base delay of the retry backoff (default 1s).
80    pub base_delay: GoDuration,
81    /// `--<trigger>_max_delay`: the maximum delay of the retry backoff (default 10s).
82    pub max_delay: GoDuration,
83    /// `--<trigger>_max_concurrent_runs`: the most trigger runs at once (default 100).
84    pub max_runs: i64,
85    /// `--<trigger>_oidc_audience`: the audience of the OIDC token the trigger attaches.
86    pub oidc_audience: String,
87    /// `--<trigger>_oidc_service_accounts`: the comma-separated service account emails allowed
88    /// to call the trigger endpoint.
89    pub oidc_service_accounts: String,
90    /// Whether each OIDC flag was on the command line, which an empty value
91    /// alone cannot tell from it being omitted.
92    pub oidc_audience_passed: bool,
93    /// Whether `--<trigger>_oidc_service_accounts` was on the command line.
94    pub oidc_service_accounts_passed: bool,
95}
96
97/// The Cloud Run service flags.
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub struct CloudRunServiceFlags {
100    /// `--service_name` (`-s`): the Cloud Run service name.
101    pub service_name: String,
102    /// `--server_port`: the server port (default 8080).
103    pub server_port: i64,
104    /// `--a2a_agent_url` (`-a`): the A2A agent card URL advertised in the public agent card
105    /// (default `http://127.0.0.1:8081`).
106    pub a2a_agent_card_url: String,
107    /// `--a2a`: enable A2A (default true).
108    pub a2a: bool,
109    /// `--api`: enable the API (default true).
110    pub api: bool,
111    /// `--debug_api`: enable the Debug API (default false; requires `--api`).
112    pub debug_api: bool,
113    /// `--webui`: enable the web UI (default true).
114    pub webui: bool,
115    /// `--pubsub`: enable the Pub/Sub subrouter (default false).
116    pub pubsub: bool,
117    /// The `--pubsub_*` trigger flags.
118    pub pubsub_trigger: TriggerConfigFlags,
119    /// `--eventarc`: enable the Eventarc subrouter (default false).
120    pub eventarc: bool,
121    /// The `--eventarc_*` trigger flags.
122    pub eventarc_trigger: TriggerConfigFlags,
123}
124
125/// The local proxy flags.
126#[derive(Debug, Clone, Default, PartialEq, Eq)]
127pub struct LocalProxyFlags {
128    /// `--proxy_port`: the local proxy's port (default 8081).
129    pub port: i64,
130}
131
132/// The build flags.
133#[derive(Debug, Clone, Default, PartialEq, Eq)]
134pub struct BuildFlags {
135    /// `--temp_dir` (`-t`); after [`CloudRunFlags::compute_flags`], the `cloudrun_*` directory
136    /// it created there (in the system temp dir when the flag is empty).
137    pub temp_dir: String,
138    /// The path of the built executable: `<temp_dir>/<exec_file>` unless already set.
139    pub exec_path: String,
140    /// The executable name: the resolved Cargo binary target.
141    pub exec_file: String,
142    /// The path of the generated Dockerfile: `<temp_dir>/Dockerfile`.
143    pub dockerfile_build_path: String,
144}
145
146/// The source flags.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub struct SourceFlags {
149    /// The Cargo workspace root of the resolved package, set by
150    /// [`CloudRunFlags::compute_flags`].
151    pub src_base_path: String,
152    /// `--entry_point_path` (`-e`); after [`CloudRunFlags::compute_flags`], the resolved
153    /// package's directory.
154    pub entry_point_path: String,
155}
156
157/// The flags of `gadk deploy cloudrun`, plus gadk's `--bin` and the resolved Cargo target.
158#[derive(Debug, Clone, Default, PartialEq, Eq)]
159pub struct CloudRunFlags {
160    /// The gcloud flags.
161    pub gcloud: GCloudFlags,
162    /// The Cloud Run service flags.
163    pub cloud_run: CloudRunServiceFlags,
164    /// The local proxy flags.
165    pub proxy: LocalProxyFlags,
166    /// The build paths.
167    pub build: BuildFlags,
168    /// The source paths.
169    pub source: SourceFlags,
170    /// gadk's `--bin` (not printed).
171    pub bin: String,
172    /// The Cargo target `compute_flags` resolved (not printed).
173    pub target: Option<CargoTarget>,
174}
175
176/// The `cloudrun` command with its flags, in ADK's order, plus gadk's `--bin`.
177pub fn command() -> Command {
178    pflag_command("cloudrun")
179        .about(SHORT)
180        .long_about(LONG)
181        .arg(string_flag("region", Some('r'), "", "GCP Region"))
182        .arg(string_flag("project_name", Some('p'), "", "GCP Project Name"))
183        .arg(string_flag("service_name", Some('s'), "", "Cloud Run Service name"))
184        .arg(string_flag(
185            "temp_dir",
186            Some('t'),
187            "",
188            "Temp dir for build, defaults to os.TempDir() if not specified",
189        ))
190        .arg(int_flag("proxy_port", None, "8081", "Local proxy port"))
191        .arg(int_flag("server_port", None, "8080", "Cloudrun server port"))
192        // `-e` names a Cargo package.
193        .arg(string_flag(
194            "entry_point_path",
195            Some('e'),
196            "",
197            "Path to the Cargo package of the entry point (its directory or Cargo.toml), defaults to the current directory",
198        ))
199        .arg(bool_flag("a2a", true, "Enable A2A"))
200        .arg(string_flag(
201            "a2a_agent_url",
202            Some('a'),
203            "http://127.0.0.1:8081",
204            "A2A agent card URL as advertised in the public agent card",
205        ))
206        .arg(bool_flag("api", true, "Enable API"))
207        .arg(bool_flag(
208            "debug_api",
209            false,
210            "Enable the Debug API - requires '--api'. Exposes tool-call arguments, responses and tool names. The web UI's Traces and agent structure panels need it.",
211        ))
212        .arg(bool_flag("webui", true, "Enable Web UI"))
213        .arg(bool_flag("pubsub", false, "Enable PubSub subrouter"))
214        .arg(int_flag(
215            "pubsub_max_retries",
216            None,
217            "3",
218            "Maximum retries for HTTP 429 errors from PubSub triggers",
219        ))
220        .arg(duration_flag(
221            "pubsub_base_delay",
222            None,
223            "1s",
224            "Base delay for PubSub trigger retry exponential backoff",
225        ))
226        .arg(duration_flag(
227            "pubsub_max_delay",
228            None,
229            "10s",
230            "Maximum delay for PubSub trigger retry exponential backoff",
231        ))
232        .arg(int_flag(
233            "pubsub_max_concurrent_runs",
234            None,
235            "100",
236            "Maximum concurrent PubSub trigger runs",
237        ))
238        .arg(string_flag(
239            "pubsub_oidc_audience",
240            None,
241            "",
242            "Audience of the Google-signed OIDC token the PubSub push subscription attaches. Requires --pubsub and --pubsub_oidc_service_accounts. When neither OIDC flag is given, the PubSub endpoint is unauthenticated. An empty value is refused",
243        ))
244        .arg(string_flag(
245            "pubsub_oidc_service_accounts",
246            None,
247            "",
248            "Comma-separated service account emails allowed to call the PubSub endpoint. Requires --pubsub and --pubsub_oidc_audience. An empty value is refused",
249        ))
250        .arg(bool_flag("eventarc", false, "Enable Eventarc subrouter"))
251        .arg(int_flag(
252            "eventarc_max_retries",
253            None,
254            "3",
255            "Maximum retries for HTTP 429 errors from Eventarc triggers",
256        ))
257        .arg(duration_flag(
258            "eventarc_base_delay",
259            None,
260            "1s",
261            "Base delay for Eventarc trigger retry exponential backoff",
262        ))
263        .arg(duration_flag(
264            "eventarc_max_delay",
265            None,
266            "10s",
267            "Maximum delay for Eventarc trigger retry exponential backoff",
268        ))
269        .arg(int_flag(
270            "eventarc_max_concurrent_runs",
271            None,
272            "100",
273            "Maximum concurrent Eventarc trigger runs",
274        ))
275        .arg(string_flag(
276            "eventarc_oidc_audience",
277            None,
278            "",
279            "Audience of the Google-signed OIDC token the Eventarc trigger attaches. Requires --eventarc and --eventarc_oidc_service_accounts. When neither OIDC flag is given, the Eventarc endpoint is unauthenticated. An empty value is refused",
280        ))
281        .arg(string_flag(
282            "eventarc_oidc_service_accounts",
283            None,
284            "",
285            "Comma-separated service account emails allowed to call the Eventarc endpoint. Requires --eventarc and --eventarc_oidc_audience. An empty value is refused",
286        ))
287        // A gadk-only flag selecting the Cargo binary target.
288        .arg(string_flag(
289            "bin",
290            None,
291            "",
292            "Binary target of the package to deploy, required when the package has more than one",
293        ))
294        .arg(stray_args())
295}
296
297/// The flags of a parsed `cloudrun` command, with the passed OIDC flags recorded
298/// (`note_passed_oidc_flags` from [`crate::flags::passed`]).
299pub fn from_matches(m: &ArgMatches) -> CloudRunFlags {
300    let trigger = |name: &str| TriggerConfigFlags {
301        max_retries: int_value(m, &format!("{name}_max_retries")),
302        base_delay: duration_value(m, &format!("{name}_base_delay")),
303        max_delay: duration_value(m, &format!("{name}_max_delay")),
304        max_runs: int_value(m, &format!("{name}_max_concurrent_runs")),
305        oidc_audience: string_value(m, &format!("{name}_oidc_audience")),
306        oidc_service_accounts: string_value(m, &format!("{name}_oidc_service_accounts")),
307        oidc_audience_passed: false,
308        oidc_service_accounts_passed: false,
309    };
310    let mut f = CloudRunFlags {
311        gcloud: GCloudFlags {
312            region: string_value(m, "region"),
313            project_name: string_value(m, "project_name"),
314        },
315        cloud_run: CloudRunServiceFlags {
316            service_name: string_value(m, "service_name"),
317            server_port: int_value(m, "server_port"),
318            a2a_agent_card_url: string_value(m, "a2a_agent_url"),
319            a2a: bool_value(m, "a2a"),
320            api: bool_value(m, "api"),
321            debug_api: bool_value(m, "debug_api"),
322            webui: bool_value(m, "webui"),
323            pubsub: bool_value(m, "pubsub"),
324            pubsub_trigger: trigger("pubsub"),
325            eventarc: bool_value(m, "eventarc"),
326            eventarc_trigger: trigger("eventarc"),
327        },
328        proxy: LocalProxyFlags {
329            port: int_value(m, "proxy_port"),
330        },
331        build: BuildFlags {
332            temp_dir: string_value(m, "temp_dir"),
333            ..BuildFlags::default()
334        },
335        source: SourceFlags {
336            entry_point_path: string_value(m, "entry_point_path"),
337            ..SourceFlags::default()
338        },
339        bin: string_value(m, "bin"),
340        target: None,
341    };
342    // Record which OIDC flags were passed.
343    f.note_passed_oidc_flags(&|id| passed(m, id));
344    f
345}
346
347/// The trigger flags' one-line form: durations as their nanosecond count.
348fn trigger_go_v(t: &TriggerConfigFlags) -> String {
349    format!(
350        "{{{} {} {} {} {} {} {} {}}}",
351        t.max_retries,
352        t.base_delay.0,
353        t.max_delay.0,
354        t.max_runs,
355        t.oidc_audience,
356        t.oidc_service_accounts,
357        t.oidc_audience_passed,
358        t.oidc_service_accounts_passed
359    )
360}
361
362impl CloudRunFlags {
363    /// The one-line form of the flags (without the newline), printed before deploying:
364    /// every flag group in braces in field order, values space-separated (durations as
365    /// nanoseconds, derived fields as they are now), byte-identical to the line ADK's tool
366    /// prints; `bin` and `target` are not printed.
367    pub fn go_v(&self) -> String {
368        let (g, c, b, s) = (&self.gcloud, &self.cloud_run, &self.build, &self.source);
369        format!(
370            "{{{{{} {}}} {{{} {} {} {} {} {} {} {} {} {} {}}} {{{}}} {{{} {} {} {}}} {{{} {}}}}}",
371            g.region,
372            g.project_name,
373            c.service_name,
374            c.server_port,
375            c.a2a_agent_card_url,
376            c.a2a,
377            c.api,
378            c.debug_api,
379            c.webui,
380            c.pubsub,
381            trigger_go_v(&c.pubsub_trigger),
382            c.eventarc,
383            trigger_go_v(&c.eventarc_trigger),
384            self.proxy.port,
385            b.temp_dir,
386            b.exec_path,
387            b.exec_file,
388            b.dockerfile_build_path,
389            s.src_base_path,
390            s.entry_point_path
391        )
392    }
393
394    /// Records which OIDC flags were passed on the command line.
395    pub fn note_passed_oidc_flags(&mut self, passed: &dyn Fn(&str) -> bool) {
396        self.cloud_run.pubsub_trigger.oidc_audience_passed = passed("pubsub_oidc_audience");
397        self.cloud_run.pubsub_trigger.oidc_service_accounts_passed =
398            passed("pubsub_oidc_service_accounts");
399        self.cloud_run.eventarc_trigger.oidc_audience_passed = passed("eventarc_oidc_audience");
400        self.cloud_run.eventarc_trigger.oidc_service_accounts_passed =
401            passed("eventarc_oidc_service_accounts");
402    }
403
404    /// Computes the derived flags: the checks in order, target resolution, the shell-safe
405    /// checks, then the `cloudrun_<local time>__*` temp dir and the derived paths.
406    pub async fn compute_flags(&mut self, env: &Env) -> Result<(), String> {
407        log_start_stop(
408            &env.out,
409            "Computing flags & preparing temp",
410            async |p: Printer| {
411                if self.cloud_run.debug_api && !self.cloud_run.api {
412                    return Err("cannot enable Debug API without having enabled API".to_string());
413                }
414
415                validate_service_name(&self.cloud_run.service_name)?;
416
417                // Checked before the temp dir is created so a rejected value does not leave
418                // one behind. It is checked whether or not --a2a is set.
419                validate_dockerfile_safe(&self.cloud_run.a2a_agent_card_url, "--a2a_agent_url")?;
420                validate_trigger_oidc("pubsub", &self.cloud_run.pubsub_trigger)?;
421                validate_trigger_oidc("eventarc", &self.cloud_run.eventarc_trigger)?;
422                check_trigger_oidc_emitted(
423                    "pubsub",
424                    self.cloud_run.pubsub,
425                    &self.cloud_run.pubsub_trigger,
426                )?;
427                check_trigger_oidc_emitted(
428                    "eventarc",
429                    self.cloud_run.eventarc,
430                    &self.cloud_run.eventarc_trigger,
431                )?;
432
433                // The raw flag value, kept for the rejection messages below: what the checks
434                // see is derived from it.
435                let orig_entry_point_path = self.source.entry_point_path.clone();
436
437                // Resolves the Cargo target (package, binary, workspace root; its errors are
438                // gadk's) and rejects a `path` dependency outside the staged workspace root,
439                // all before the temp dir is created.
440                let target = resolve(env, &orig_entry_point_path, &self.bin).await?;
441                check_path_dependencies(&target, &target.workspace_root)?;
442                self.source.src_base_path = target.workspace_root.to_string_lossy().into_owned();
443                self.source.entry_point_path = target.manifest_dir.to_string_lossy().into_owned();
444                if self.build.exec_path.is_empty() {
445                    self.build.exec_file = target.bin.clone();
446                }
447
448                // execFile becomes both COPY operands and the CMD argv[0], and COPY splits
449                // its operands on whitespace: it takes the allowlist.
450                validate_shell_arg_safe(
451                    &self.build.exec_file,
452                    &format!(
453                        "executable name derived from --entry_point_path {}:",
454                        go_quote(&orig_entry_point_path)
455                    ),
456                )?;
457                // The package name reaches the builder's `RUN cargo build -p <package>` line,
458                // so it takes the same allowlist.
459                validate_shell_arg_safe(
460                    &target.package,
461                    &format!(
462                        "package name derived from --entry_point_path {}:",
463                        go_quote(&orig_entry_point_path)
464                    ),
465                )?;
466                self.target = Some(target);
467
468                if self.build.temp_dir.is_empty() {
469                    self.build.temp_dir = env.temp_dir().to_string_lossy().into_owned();
470                }
471                let absp = env.abs(&self.build.temp_dir);
472                // The wrapped error is Rust's `io::Error` text.
473                let dir = make_temp(&absp, "cloudrun_", env.time.now()).map_err(|e| {
474                    format!(
475                        "cannot create a temporary sub directory in '{}': {e}",
476                        absp.display()
477                    )
478                })?;
479                self.build.temp_dir = dir.to_string_lossy().into_owned();
480                p.print(&[&"Using temp dir:", &self.build.temp_dir]);
481
482                if self.build.exec_path.is_empty() {
483                    self.build.exec_path =
484                        go_path_join(&[self.build.temp_dir.as_str(), &self.build.exec_file]);
485                }
486                self.build.dockerfile_build_path =
487                    go_path_join(&[self.build.temp_dir.as_str(), "Dockerfile"]);
488
489                Ok(())
490            },
491        )
492        .await
493    }
494
495    /// `"Staging source"`: copies the workspace into
496    /// the temp dir and writes a `.gcloudignore` when the copy has none.
497    // The Cargo workspace root is copied (without `.git`, `target` and a nested temp dir)
498    // into the temp dir for a remote build, and a one-comment `.gcloudignore` is written when
499    // the workspace has none, so `gcloud` does not fall back to `.gitignore` (which may exclude
500    // `Cargo.lock`). Its error texts are gadk's.
501    pub async fn stage_source(&mut self, env: &Env) -> Result<(), String> {
502        log_start_stop(&env.out, "Staging source", async |p: Printer| {
503            let Some(target) = &self.target else {
504                return Err(NO_TARGET.to_string());
505            };
506            let root = &target.workspace_root;
507            let temp = PathBuf::from(&self.build.temp_dir);
508            p.print(&[&"Using", &self.source.entry_point_path, &"as entry point"]);
509            p.print(&[&"Copying", &root.display(), &"to", &self.build.temp_dir]);
510            let staged = SourceTree::walk(root, &nested_exclude(root, &temp))
511                .and_then(|tree| tree.copy_into(&temp))
512                .map_err(|e| {
513                    format!(
514                        "cannot copy '{}' to '{}': {e}",
515                        root.display(),
516                        temp.display()
517                    )
518                });
519            staged?;
520            let ignore = temp.join(".gcloudignore");
521            if fs::symlink_metadata(&ignore).is_err() {
522                p.print(&[&"Writing:", &ignore.display()]);
523                fs::write(&ignore, GCLOUDIGNORE)
524                    .map_err(|e| format!("cannot write '{}': {e}", ignore.display()))?;
525            }
526            Ok(())
527        })
528        .await
529    }
530
531    /// Prepares the Dockerfile: reads only the receiver; the generated `Dockerfile`
532    /// replaces any copied root `Dockerfile` (removed first, so a symbolic link is never
533    /// followed out of the temp dir).
534    pub async fn prepare_dockerfile(&self, env: &Env) -> Result<(), String> {
535        log_start_stop(&env.out, "Preparing Dockerfile", async |p: Printer| {
536            p.print(&[&"Writing:", &self.build.dockerfile_build_path]);
537            let Some(target) = &self.target else {
538                return Err(NO_TARGET.to_string());
539            };
540
541            // Every value below is read off the receiver.
542            let c = &self.cloud_run;
543            let mut b = String::new();
544            if c.api {
545                let _ = write!(
546                    b,
547                    r#", "api", "-webui_address", "127.0.0.1:{}""#,
548                    self.proxy.port
549                );
550                if c.debug_api {
551                    b.push_str(r#", "-include_debug_api""#);
552                }
553            }
554            if c.a2a {
555                let _ = write!(
556                    b,
557                    r#", "a2a", "--a2a_agent_url", "{}""#,
558                    c.a2a_agent_card_url
559                );
560            }
561            if c.webui {
562                let _ = write!(
563                    b,
564                    r#", "webui", "--api_server_address", "http://127.0.0.1:{}/api""#,
565                    self.proxy.port
566                );
567            }
568            if c.pubsub {
569                b.push_str(r#", "pubsub""#);
570                write_trigger_flags(&mut b, &c.pubsub_trigger);
571                write_oidc_flags(&mut b, &c.pubsub_trigger);
572            }
573            if c.eventarc {
574                b.push_str(r#", "eventarc""#);
575                write_trigger_flags(&mut b, &c.eventarc_trigger);
576                write_oidc_flags(&mut b, &c.eventarc_trigger);
577            }
578            let builder = BuilderStage {
579                image: builder_image(&builder_rust_version(target, COMPILED_RUSTC_VERSION)),
580                workdir: String::new(),
581                package: target.package.clone(),
582                bin: self.build.exec_file.clone(),
583            };
584            let content = dockerfile(&builder, c.server_port, &b);
585            // The error is Rust's `io::Error` text after an `open <path>: ` prefix.
586            write_file_0600(Path::new(&self.build.dockerfile_build_path), &content)
587                .map_err(|e| format!("open {}: {e}", self.build.dockerfile_build_path))
588        })
589        .await
590    }
591
592    /// Deploys to Cloud Run with `gcloud run deploy`.
593    pub async fn gcloud_deploy_to_cloud_run(&self, env: &Env) -> Result<(), String> {
594        log_start_stop(&env.out, "Deploying to Cloud Run", async |p: Printer| {
595            let params = [
596                "run",
597                "deploy",
598                self.cloud_run.service_name.as_str(),
599                "--source",
600                ".",
601                "--set-secrets=GOOGLE_API_KEY=GOOGLE_API_KEY:latest",
602                "--region",
603                self.gcloud.region.as_str(),
604                "--project",
605                self.gcloud.project_name.as_str(),
606                "--ingress",
607                "all",
608                "--no-allow-unauthenticated",
609            ];
610            let cmd = env
611                .command("gcloud", &params)
612                .with_dir(self.build.temp_dir.clone());
613            log_command(env.runner.as_ref(), &cmd, &p).await
614        })
615        .await
616    }
617
618    /// Removes the temp dir.
619    pub async fn clean_temp(&self, env: &Env) -> Result<(), String> {
620        log_start_stop(&env.out, "Cleaning temp", async |p: Printer| {
621            p.print(&[&"Clean temp starting with", &self.build.temp_dir]);
622            // A missing directory is not an error.
623            // The wrapped error is Rust's `io::Error` text.
624            match fs::remove_dir_all(&self.build.temp_dir) {
625                Err(e) if e.kind() != io::ErrorKind::NotFound => Err(format!(
626                    "failed to clean temp directory {}: {e}",
627                    self.build.temp_dir
628                )),
629                _ => Ok(()),
630            }
631        })
632        .await
633    }
634
635    /// Runs the local proxy (banner and `gcloud run services proxy`).
636    pub async fn run_gcloud_proxy(&self, env: &Env) -> Result<(), String> {
637        log_start_stop(
638            &env.out,
639            "Running local gcloud authenticating proxy",
640            async |p: Printer| {
641                let target_width = 80;
642                let port = self.proxy.port.to_string();
643
644                p.print(&[&"-".repeat(target_width)]);
645                p.print(&[&center_string("", target_width)]);
646                p.print(&[&center_string(
647                    &format!("Running ADK Web UI on http://127.0.0.1:{port}/ui/    <-- open this"),
648                    target_width,
649                )]);
650                p.print(&[&center_string(
651                    &format!("ADK REST API on http://127.0.0.1:{port}/api/         "),
652                    target_width,
653                )]);
654                p.print(&[&center_string("", target_width)]);
655                p.print(&[&center_string("Press Ctrl-C to stop", target_width)]);
656                p.print(&[&center_string("", target_width)]);
657                p.print(&[&"-".repeat(target_width)]);
658
659                let cmd = env.command(
660                    "gcloud",
661                    &[
662                        "run",
663                        "services",
664                        "proxy",
665                        &self.cloud_run.service_name,
666                        "--project",
667                        &self.gcloud.project_name,
668                        "--port",
669                        &port,
670                        "--region",
671                        &self.gcloud.region,
672                    ],
673                );
674                log_command(env.runner.as_ref(), &cmd, &p).await
675            },
676        )
677        .await
678    }
679
680    /// Deploys: prints [`CloudRunFlags::go_v`], then compute → stage →
681    /// Dockerfile → deploy → clean → proxy, stopping at the first error (the temp dir is kept).
682    pub async fn deploy_on_cloud_run(&mut self, env: &Env) -> Result<(), String> {
683        // Prints the receiver's flags.
684        env.out.write_str(&format!("{}\n", self.go_v()));
685
686        self.compute_flags(env).await?;
687        self.stage_source(env).await?;
688        self.prepare_dockerfile(env).await?;
689        self.gcloud_deploy_to_cloud_run(env).await?;
690        self.clean_temp(env).await?;
691        self.run_gcloud_proxy(env).await?;
692
693        Ok(())
694    }
695}
696
697/// The error of a step that needs the Cargo target before `compute_flags` resolved it (no
698/// command-line path reaches it).
699const NO_TARGET: &str = "no Cargo target: computeFlags has not run";
700
701/// The `.gcloudignore` written when the staged workspace has none.
702const GCLOUDIGNORE: &str =
703    "# Written by gadk deploy cloudrun: without a .gcloudignore, gcloud would apply .gitignore.\n";
704
705/// The paths the staging walk of `root` skips: the temp dir when it lies inside `root`, in
706/// the same form as `root` (the walk compares `root`-joined paths as given), also when one of
707/// the two is reached through a symbolic link.
708fn nested_exclude(root: &Path, temp: &Path) -> Vec<PathBuf> {
709    let mut exclude = vec![temp.to_path_buf()];
710    if let (Ok(r), Ok(t)) = (fs::canonicalize(root), fs::canonicalize(temp))
711        && let Ok(rel) = t.strip_prefix(&r)
712    {
713        exclude.push(root.join(rel));
714    }
715    exclude
716}
717
718/// Writes `data` to `path` with mode 0600 after removing any existing entry at `path`.
719fn write_file_0600(path: &Path, data: &str) -> io::Result<()> {
720    match fs::symlink_metadata(path) {
721        Ok(_) => fs::remove_file(path)?,
722        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
723        Err(e) => return Err(e),
724    }
725    let mut file = OpenOptions::new()
726        .write(true)
727        .create(true)
728        .truncate(true)
729        .mode(0o600)
730        .open(path)?;
731    file.write_all(data.as_bytes())
732}
733
734/// The four trigger lines of the generated Dockerfile `CMD`.
735fn write_trigger_flags(b: &mut String, t: &TriggerConfigFlags) {
736    let _ = write!(b, r#", "--trigger_max_retries", "{}""#, t.max_retries);
737    let _ = write!(b, r#", "--trigger_base_delay", "{}""#, t.base_delay);
738    let _ = write!(b, r#", "--trigger_max_delay", "{}""#, t.max_delay);
739    let _ = write!(b, r#", "--trigger_max_concurrent_runs", "{}""#, t.max_runs);
740}
741
742/// Rejects a `--service_name` gcloud would parse as a flag.
743pub fn validate_service_name(name: &str) -> Result<(), String> {
744    if name.starts_with('-') {
745        return Err(format!(
746            "invalid --service_name {}: a Cloud Run service name must not begin with '-'",
747            go_quote(name)
748        ));
749    }
750    Ok(())
751}
752
753/// Rejects the trigger's OIDC values the Dockerfile cannot
754/// carry or the trigger's sublauncher would refuse at startup.
755pub fn validate_trigger_oidc(name: &str, t: &TriggerConfigFlags) -> Result<(), String> {
756    let aud_flag = format!("--{name}_oidc_audience");
757    let sa_flag = format!("--{name}_oidc_service_accounts");
758    validate_dockerfile_safe(&t.oidc_audience, &aud_flag)?;
759    validate_dockerfile_safe(&t.oidc_service_accounts, &sa_flag)?;
760    // Before the pair check, so a deploy script with one variable unset is told which value
761    // is empty rather than to pass both flags.
762    if t.oidc_audience_passed && t.oidc_audience.is_empty() {
763        return Err(format!(
764            "{aud_flag} is empty: give it a value or leave it out"
765        ));
766    }
767    if t.oidc_service_accounts_passed && t.oidc_service_accounts.is_empty() {
768        return Err(format!(
769            "{sa_flag} is empty: give it a value or leave it out"
770        ));
771    }
772    check_oidc_values_are_not_flags(
773        &aud_flag,
774        &sa_flag,
775        &t.oidc_audience,
776        &t.oidc_service_accounts,
777    )?;
778    if t.oidc_audience.is_empty() != t.oidc_service_accounts.is_empty() {
779        return Err(format!("{aud_flag} and {sa_flag} must be set together"));
780    }
781    if t.oidc_audience != t.oidc_audience.trim() {
782        return Err(format!(
783            "{aud_flag} {} has surrounding whitespace",
784            go_quote(&t.oidc_audience)
785        ));
786    }
787    if !t.oidc_service_accounts.is_empty()
788        && t.oidc_service_accounts
789            .split(',')
790            .any(|account| account.trim().is_empty())
791    {
792        return Err(format!(
793            "{sa_flag} {} has an empty entry",
794            go_quote(&t.oidc_service_accounts)
795        ));
796    }
797    Ok(())
798}
799
800/// Rejects an audience or service account starting with
801/// `-`, as when an unset variable makes a flag take the next flag as its value.
802pub fn check_oidc_values_are_not_flags(
803    aud_flag: &str,
804    sa_flag: &str,
805    audience: &str,
806    accounts: &str,
807) -> Result<(), String> {
808    if audience.starts_with('-') {
809        return Err(format!(
810            "{aud_flag} {} starts with \"-\", as when an unset variable makes a flag take the next flag as its value",
811            go_quote(audience)
812        ));
813    }
814    if accounts.trim().starts_with('-') {
815        return Err(format!(
816            "{sa_flag} {} starts with \"-\", as when an unset variable makes a flag take the next flag as its value",
817            go_quote(accounts)
818        ));
819    }
820    if accounts
821        .split(',')
822        .any(|account| account.trim().starts_with('-'))
823    {
824        return Err(format!(
825            "{sa_flag} {} has an entry starting with \"-\"",
826            go_quote(accounts)
827        ));
828    }
829    Ok(())
830}
831
832/// Rejects OIDC values for a trigger that is not enabled (they
833/// are written only after that trigger's keyword).
834pub fn check_trigger_oidc_emitted(
835    name: &str,
836    enabled: bool,
837    t: &TriggerConfigFlags,
838) -> Result<(), String> {
839    if !enabled && (!t.oidc_audience.is_empty() || !t.oidc_service_accounts.is_empty()) {
840        return Err(format!(
841            "--{name}_oidc_audience and --{name}_oidc_service_accounts require --{name}"
842        ));
843    }
844    Ok(())
845}
846
847/// Writes the trigger's OIDC flags when set (`compute_flags` has checked that
848/// both or neither are).
849pub fn write_oidc_flags(b: &mut String, t: &TriggerConfigFlags) {
850    if !t.oidc_audience.is_empty() {
851        let _ = write!(b, r#", "-oidc_audience", "{}""#, t.oidc_audience);
852    }
853    if !t.oidc_service_accounts.is_empty() {
854        let _ = write!(
855            b,
856            r#", "-oidc_service_accounts", "{}""#,
857            t.oidc_service_accounts
858        );
859    }
860}
861
862/// Test fixtures shared by this module's tests: a Cargo
863/// workspace on disk with a [`TestEnv`](crate::testutil::TestEnv) whose runner answers
864/// `cargo metadata` for it.
865#[cfg(test)]
866pub(crate) mod fixture {
867    use std::fs;
868    use std::path::{Path, PathBuf};
869
870    use super::{CloudRunFlags, CloudRunServiceFlags};
871    use crate::runner::Cmd;
872    use crate::target::CargoTarget;
873    use crate::testutil::{
874        Canned, TestEnv, cargo_metadata_json, cargo_metadata_runner, write_cargo_workspace,
875    };
876
877    /// The `rust-toolchain.toml` channel every fixture workspace pins.
878    pub(crate) const CHANNEL: &str = "1.90.0";
879
880    /// `<dir>/ws`: a Cargo workspace ([`write_cargo_workspace`] plus `rust-toolchain.toml`)
881    /// whose package `package` lives at `<dir>/ws/<member>` with the binary targets `bins`;
882    /// `<dir>/tmp` is the temp parent (Go `t.TempDir()`).
883    pub(crate) struct Workspace {
884        pub dir: tempfile::TempDir,
885        pub member: String,
886        pub package: String,
887        pub bins: Vec<String>,
888        /// `path` dependencies `cargo metadata` reports for the package.
889        pub path_dependencies: Vec<PathBuf>,
890    }
891
892    impl Workspace {
893        pub(crate) fn new(member: &str, package: &str, bins: &[&str]) -> Workspace {
894            let dir = tempfile::tempdir().unwrap();
895            let root = dir.path().join("ws");
896            fs::create_dir_all(dir.path().join("tmp")).unwrap();
897            write_cargo_workspace(&root, member, package);
898            fs::write(
899                root.join("rust-toolchain.toml"),
900                format!("[toolchain]\nchannel = \"{CHANNEL}\"\n"),
901            )
902            .unwrap();
903            Workspace {
904                dir,
905                member: member.to_string(),
906                package: package.to_string(),
907                bins: bins.iter().map(|b| b.to_string()).collect(),
908                path_dependencies: Vec::new(),
909            }
910        }
911
912        /// The workspace root `<dir>/ws`.
913        pub(crate) fn root(&self) -> PathBuf {
914            self.dir.path().join("ws")
915        }
916
917        /// The temp parent `<dir>/tmp`.
918        pub(crate) fn temp_parent(&self) -> PathBuf {
919            self.dir.path().join("tmp")
920        }
921
922        /// The package's manifest directory.
923        pub(crate) fn manifest_dir(&self) -> PathBuf {
924            if self.member.is_empty() {
925                self.root()
926            } else {
927                self.root().join(&self.member)
928            }
929        }
930
931        /// What `cargo metadata --format-version 1 --no-deps` prints for the workspace.
932        pub(crate) fn metadata(&self) -> String {
933            let bins: Vec<&str> = self.bins.iter().map(String::as_str).collect();
934            cargo_metadata_json(
935                &self.root(),
936                &self.manifest_dir().join("Cargo.toml"),
937                &self.package,
938                &bins,
939                &self.path_dependencies,
940            )
941        }
942
943        /// A [`TestEnv`] in the workspace root whose runner answers `cargo metadata` with
944        /// [`Workspace::metadata`] and every other command with exit 0.
945        pub(crate) fn env(&self) -> TestEnv {
946            self.env_with(|_| Canned::success(Vec::new()))
947        }
948
949        /// As [`Workspace::env`], with every command other than `cargo metadata` answered by
950        /// `other`.
951        pub(crate) fn env_with(
952            &self,
953            other: impl Fn(&Cmd) -> Canned + Send + Sync + 'static,
954        ) -> TestEnv {
955            let metadata = self.metadata();
956            let runner = cargo_metadata_runner(move |_| metadata.clone(), other);
957            TestEnv::builder(self.root()).runner(runner).build()
958        }
959
960        /// Go `resetFlags(t, entryPointPath, a2aAgentCardURL)`: the zero value plus the
961        /// entry point, the temp parent as `--temp_dir` and the A2A agent card URL.
962        pub(crate) fn flags(&self, entry_point: &str, a2a_agent_card_url: &str) -> CloudRunFlags {
963            let mut f = CloudRunFlags {
964                cloud_run: CloudRunServiceFlags {
965                    a2a_agent_card_url: a2a_agent_card_url.to_string(),
966                    ..CloudRunServiceFlags::default()
967                },
968                ..CloudRunFlags::default()
969            };
970            f.source.entry_point_path = entry_point.to_string();
971            f.build.temp_dir = self.temp_parent().to_string_lossy().into_owned();
972            f
973        }
974    }
975
976    /// A receiver `prepare_dockerfile` can run on directly (Go builds `&deployCloudRunFlags{}`
977    /// by hand): `exec_file`, the Dockerfile at `<dir>/Dockerfile` and a resolved target
978    /// (package `agent`) whose workspace root is `dir` (no `rust-toolchain.toml` unless the
979    /// test writes one).
980    pub(crate) fn receiver(dir: &Path, exec_file: &str) -> CloudRunFlags {
981        let mut f = CloudRunFlags::default();
982        f.build.exec_file = exec_file.to_string();
983        f.build.dockerfile_build_path = dir.join("Dockerfile").to_string_lossy().into_owned();
984        f.target = Some(CargoTarget {
985            package: "agent".to_string(),
986            bin: exec_file.to_string(),
987            workspace_root: dir.to_path_buf(),
988            manifest_dir: dir.to_path_buf(),
989            rust_version: None,
990            path_dependencies: Vec::new(),
991        });
992        f
993    }
994
995    /// The `CMD` line's JSON array of a generated Dockerfile (Go: the line after `CMD `,
996    /// `json.Unmarshal` into `[]string`).
997    pub(crate) fn cmd_args(content: &str) -> Vec<String> {
998        let line = content
999            .lines()
1000            .filter_map(|l| l.strip_prefix("CMD "))
1001            .next_back()
1002            .unwrap_or_else(|| {
1003                panic!("no CMD instruction in the generated Dockerfile:\n{content}")
1004            });
1005        serde_json::from_str(line)
1006            .unwrap_or_else(|e| panic!("CMD {line} does not parse as a JSON array: {e}"))
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use std::fs;
1013    use std::os::unix::fs::PermissionsExt;
1014    use std::path::Path;
1015    use std::sync::{Arc, Mutex};
1016
1017    use chrono::Local;
1018    use pretty_assertions::assert_eq;
1019
1020    use super::fixture::{CHANNEL, Workspace, receiver};
1021    use super::*;
1022    use crate::testutil::{Canned, TestEnv, default_now};
1023
1024    fn parse(args: &[&str]) -> CloudRunFlags {
1025        let m = command()
1026            .try_get_matches_from(std::iter::once("cloudrun").chain(args.iter().copied()))
1027            .unwrap();
1028        from_matches(&m)
1029    }
1030
1031    #[test]
1032    fn go_v_golden_line_with_defaults() {
1033        assert_eq!(
1034            parse(&["-e", "x"]).go_v(),
1035            "{{ } { 8080 http://127.0.0.1:8081 true true false true false {3 1000000000 10000000000 100   false false} false {3 1000000000 10000000000 100   false false}} {8081} {   } { x}}"
1036        );
1037    }
1038
1039    #[test]
1040    fn from_matches_reads_every_flag_and_go_v_prints_it() {
1041        let f = parse(&[
1042            "-r",
1043            "us-east1",
1044            "-p",
1045            "proj",
1046            "-s",
1047            "svc",
1048            "-t",
1049            "/t",
1050            "--proxy_port",
1051            "9001",
1052            "--server_port=0x10",
1053            "-e",
1054            "agent",
1055            "--a2a=false",
1056            "-a",
1057            "https://a.example",
1058            "--api=f",
1059            "--debug_api",
1060            "--webui=0",
1061            "--pubsub",
1062            "--pubsub_max_retries",
1063            "5",
1064            "--pubsub_base_delay",
1065            "1.5s",
1066            "--pubsub_max_delay=1m",
1067            "--pubsub_max_concurrent_runs",
1068            "7",
1069            "--pubsub_oidc_audience",
1070            "aud",
1071            "--pubsub_oidc_service_accounts=sa@x",
1072            "--eventarc=true",
1073            "--eventarc_max_retries=6",
1074            "--eventarc_base_delay=2ms",
1075            "--eventarc_max_delay",
1076            "3h",
1077            "--eventarc_max_concurrent_runs=8",
1078            "--eventarc_oidc_audience=",
1079            "--bin",
1080            "tool",
1081            "stray",
1082        ]);
1083        let want = CloudRunFlags {
1084            gcloud: GCloudFlags {
1085                region: "us-east1".into(),
1086                project_name: "proj".into(),
1087            },
1088            cloud_run: CloudRunServiceFlags {
1089                service_name: "svc".into(),
1090                server_port: 16,
1091                a2a_agent_card_url: "https://a.example".into(),
1092                a2a: false,
1093                api: false,
1094                debug_api: true,
1095                webui: false,
1096                pubsub: true,
1097                pubsub_trigger: TriggerConfigFlags {
1098                    max_retries: 5,
1099                    base_delay: GoDuration(1_500_000_000),
1100                    max_delay: GoDuration::MINUTE,
1101                    max_runs: 7,
1102                    oidc_audience: "aud".into(),
1103                    oidc_service_accounts: "sa@x".into(),
1104                    oidc_audience_passed: true,
1105                    oidc_service_accounts_passed: true,
1106                },
1107                eventarc: true,
1108                eventarc_trigger: TriggerConfigFlags {
1109                    max_retries: 6,
1110                    base_delay: GoDuration(2 * GoDuration::MILLISECOND.0),
1111                    max_delay: GoDuration(3 * GoDuration::HOUR.0),
1112                    max_runs: 8,
1113                    oidc_audience: String::new(),
1114                    oidc_service_accounts: String::new(),
1115                    oidc_audience_passed: true,
1116                    oidc_service_accounts_passed: false,
1117                },
1118            },
1119            proxy: LocalProxyFlags { port: 9001 },
1120            build: BuildFlags {
1121                temp_dir: "/t".into(),
1122                ..BuildFlags::default()
1123            },
1124            source: SourceFlags {
1125                src_base_path: String::new(),
1126                entry_point_path: "agent".into(),
1127            },
1128            bin: "tool".into(),
1129            target: None,
1130        };
1131        assert_eq!(f, want);
1132        assert_eq!(
1133            f.go_v(),
1134            "{{us-east1 proj} {svc 16 https://a.example false false true false true {5 1500000000 60000000000 7 aud sa@x true true} true {6 2000000 10800000000000 8   true false}} {9001} {/t   } { agent}}"
1135        );
1136    }
1137
1138    #[test]
1139    fn note_passed_oidc_flags_names_each_flag() {
1140        for (i, name) in TRIGGER_OIDC_FLAG_NAMES.iter().enumerate() {
1141            let mut f = CloudRunFlags::default();
1142            f.note_passed_oidc_flags(&|id| id == *name);
1143            let got = [
1144                f.cloud_run.pubsub_trigger.oidc_audience_passed,
1145                f.cloud_run.pubsub_trigger.oidc_service_accounts_passed,
1146                f.cloud_run.eventarc_trigger.oidc_audience_passed,
1147                f.cloud_run.eventarc_trigger.oidc_service_accounts_passed,
1148            ];
1149            let mut want = [false; 4];
1150            want[i] = true;
1151            assert_eq!(got, want, "{name}");
1152        }
1153    }
1154
1155    #[tokio::test]
1156    async fn prepare_dockerfile_golden_with_every_optional_segment() {
1157        let dir = tempfile::tempdir().unwrap();
1158        fs::write(
1159            dir.path().join("rust-toolchain.toml"),
1160            "[toolchain]\nchannel = \"1.92\"\n",
1161        )
1162        .unwrap();
1163        let mut f = receiver(dir.path(), "agent-bin");
1164        f.target.as_mut().unwrap().package = "my-agent".into();
1165        f.cloud_run.server_port = 8080;
1166        f.proxy.port = 8081;
1167        f.cloud_run.api = true;
1168        f.cloud_run.debug_api = true;
1169        f.cloud_run.a2a = true;
1170        f.cloud_run.a2a_agent_card_url = "https://agent.example/a2a".into();
1171        f.cloud_run.webui = true;
1172        f.cloud_run.pubsub = true;
1173        f.cloud_run.pubsub_trigger = TriggerConfigFlags {
1174            max_retries: 3,
1175            base_delay: GoDuration::SECOND,
1176            max_delay: GoDuration(10 * GoDuration::SECOND.0),
1177            max_runs: 100,
1178            oidc_audience: "https://svc.run.app/pubsub".into(),
1179            oidc_service_accounts: "push@p.iam.gserviceaccount.com".into(),
1180            ..TriggerConfigFlags::default()
1181        };
1182        f.cloud_run.eventarc = true;
1183        f.cloud_run.eventarc_trigger = TriggerConfigFlags {
1184            max_retries: 4,
1185            base_delay: GoDuration(1_500 * GoDuration::MILLISECOND.0),
1186            max_delay: GoDuration(90 * GoDuration::SECOND.0),
1187            max_runs: 9,
1188            oidc_audience: "https://svc.run.app".into(),
1189            oidc_service_accounts: "a@p.iam.gserviceaccount.com,b@p.iam.gserviceaccount.com".into(),
1190            ..TriggerConfigFlags::default()
1191        };
1192        let t = TestEnv::builder(dir.path()).build();
1193
1194        f.prepare_dockerfile(&t.env).await.unwrap();
1195
1196        let content = fs::read_to_string(&f.build.dockerfile_build_path).unwrap();
1197        assert_eq!(
1198            content,
1199            r#"
1200FROM rust:1.92-bookworm AS builder
1201WORKDIR /app/
1202COPY . /app/
1203RUN cargo build --release --locked --target-dir /gadk-target -p my-agent --bin agent-bin
1204
1205FROM gcr.io/distroless/cc-debian12
1206
1207COPY --from=builder /gadk-target/release/agent-bin  /app/agent-bin
1208EXPOSE 8080
1209# Command to run the executable when the container starts
1210CMD ["/app/agent-bin", "web", "-host", "0.0.0.0", "-port", "8080", "api", "-webui_address", "127.0.0.1:8081", "-include_debug_api", "a2a", "--a2a_agent_url", "https://agent.example/a2a", "webui", "--api_server_address", "http://127.0.0.1:8081/api", "pubsub", "--trigger_max_retries", "3", "--trigger_base_delay", "1s", "--trigger_max_delay", "10s", "--trigger_max_concurrent_runs", "100", "-oidc_audience", "https://svc.run.app/pubsub", "-oidc_service_accounts", "push@p.iam.gserviceaccount.com", "eventarc", "--trigger_max_retries", "4", "--trigger_base_delay", "1.5s", "--trigger_max_delay", "1m30s", "--trigger_max_concurrent_runs", "9", "-oidc_audience", "https://svc.run.app", "-oidc_service_accounts", "a@p.iam.gserviceaccount.com,b@p.iam.gserviceaccount.com"]"#
1211        );
1212        let mode = fs::metadata(&f.build.dockerfile_build_path)
1213            .unwrap()
1214            .permissions()
1215            .mode();
1216        assert_eq!(mode & 0o777, 0o600);
1217        assert_eq!(
1218            t.out.text(),
1219            format!(
1220                "Preparing Dockerfile : \x1b[32mStarting\x1b[0m\n    \x1b[32m> \x1b[0m [Writing: {}]\n\nPreparing Dockerfile : \x1b[32mFinished successfully\x1b[0m\n",
1221                f.build.dockerfile_build_path
1222            )
1223        );
1224    }
1225
1226    #[tokio::test]
1227    async fn prepare_dockerfile_replaces_a_copied_dockerfile_link_without_following_it() {
1228        let dir = tempfile::tempdir().unwrap();
1229        let outside = dir.path().join("outside");
1230        fs::write(&outside, "FROM user\n").unwrap();
1231        let temp = dir.path().join("temp");
1232        fs::create_dir(&temp).unwrap();
1233        std::os::unix::fs::symlink(&outside, temp.join("Dockerfile")).unwrap();
1234        let f = receiver(&temp, "main");
1235        let t = TestEnv::builder(dir.path()).build();
1236
1237        f.prepare_dockerfile(&t.env).await.unwrap();
1238
1239        assert_eq!(fs::read_to_string(&outside).unwrap(), "FROM user\n");
1240        let written = temp.join("Dockerfile");
1241        assert!(!fs::symlink_metadata(&written).unwrap().is_symlink());
1242        assert!(
1243            fs::read_to_string(&written)
1244                .unwrap()
1245                .contains("COPY . /app/\n")
1246        );
1247    }
1248
1249    #[tokio::test]
1250    async fn compute_flags_resolves_the_target_and_creates_the_temp_dir() {
1251        let ws = Workspace::new("agent", "my-agent", &["agent", "tool"]);
1252        let mut f = ws.flags("agent", "http://127.0.0.1:8081");
1253        f.bin = "tool".into();
1254        // An empty --temp_dir is Go's os.TempDir(): TMPDIR.
1255        f.build.temp_dir = String::new();
1256        let metadata = ws.metadata();
1257        let runner = crate::testutil::RecordingRunner::with_responder(move |_| {
1258            Canned::success(metadata.clone())
1259        });
1260        let t = TestEnv::builder(ws.root())
1261            .var("TMPDIR", &ws.temp_parent().to_string_lossy())
1262            .runner(runner)
1263            .build();
1264
1265        f.compute_flags(&t.env).await.unwrap();
1266
1267        let temp = Path::new(&f.build.temp_dir);
1268        assert_eq!(temp.parent(), Some(ws.temp_parent().as_path()));
1269        let name = temp.file_name().unwrap().to_string_lossy().into_owned();
1270        let stamp = default_now()
1271            .with_timezone(&Local)
1272            .format("cloudrun_%Y%m%d_%H%M%S__")
1273            .to_string();
1274        let suffix = name
1275            .strip_prefix(&stamp)
1276            .unwrap_or_else(|| panic!("{name}"));
1277        assert!(suffix.parse::<u32>().is_ok(), "{name}");
1278        assert!(temp.is_dir());
1279        assert_eq!(f.build.exec_file, "tool");
1280        assert_eq!(f.build.exec_path, format!("{}/tool", f.build.temp_dir));
1281        assert_eq!(
1282            f.build.dockerfile_build_path,
1283            format!("{}/Dockerfile", f.build.temp_dir)
1284        );
1285        assert_eq!(f.source.src_base_path, ws.root().to_string_lossy());
1286        assert_eq!(
1287            f.source.entry_point_path,
1288            ws.manifest_dir().to_string_lossy()
1289        );
1290        let target = f.target.as_ref().unwrap();
1291        assert_eq!(
1292            (target.package.as_str(), target.bin.as_str()),
1293            ("my-agent", "tool")
1294        );
1295        let manifest = ws.manifest_dir().join("Cargo.toml");
1296        let calls = t.runner.calls();
1297        assert_eq!(calls.len(), 1);
1298        assert_eq!(
1299            calls[0].args,
1300            [
1301                "cargo",
1302                "metadata",
1303                "--format-version",
1304                "1",
1305                "--no-deps",
1306                "--manifest-path",
1307                &manifest.to_string_lossy(),
1308            ]
1309        );
1310        assert_eq!(
1311            t.out.text(),
1312            format!(
1313                "Computing flags & preparing temp : \x1b[32mStarting\x1b[0m\n    \x1b[32m> \x1b[0m [Using temp dir: {}]\n\nComputing flags & preparing temp : \x1b[32mFinished successfully\x1b[0m\n",
1314                f.build.temp_dir
1315            )
1316        );
1317    }
1318
1319    #[tokio::test]
1320    async fn compute_flags_rejects_target_problems_before_the_temp_dir() {
1321        type Setup = fn(&mut Workspace, &mut CloudRunFlags);
1322        let cases: [(&str, &[&str], Setup, &str); 5] = [
1323            (
1324                "unsafe package name",
1325                &["agent"],
1326                |ws, _| ws.package = "my agent".into(),
1327                r#"package name derived from --entry_point_path "agent": "my agent" contains a character not allowed"#,
1328            ),
1329            (
1330                "path dependency outside the workspace",
1331                &["agent"],
1332                |ws, _| {
1333                    let dep = ws.dir.path().join("elsewhere");
1334                    ws.path_dependencies.push(dep);
1335                },
1336                "is outside",
1337            ),
1338            (
1339                "no binary",
1340                &[],
1341                |_, _| {},
1342                r#"package "my-agent" has no binary target"#,
1343            ),
1344            (
1345                "several binaries without --bin",
1346                &["a", "b"],
1347                |_, _| {},
1348                r#"package "my-agent" has several binary targets (a, b); select one with --bin"#,
1349            ),
1350            (
1351                "unknown --bin",
1352                &["a", "b"],
1353                |_, f| f.bin = "c".into(),
1354                r#"package "my-agent" has no binary target "c" (binaries: a, b)"#,
1355            ),
1356        ];
1357        for (name, bins, setup, want) in cases {
1358            let mut ws = Workspace::new("agent", "my-agent", bins);
1359            let mut f = ws.flags("agent", "http://127.0.0.1:8081");
1360            setup(&mut ws, &mut f);
1361            let t = ws.env();
1362
1363            let err = f.compute_flags(&t.env).await.unwrap_err();
1364
1365            assert!(err.contains(want), "{name}: {err}");
1366            assert_eq!(
1367                fs::read_dir(ws.temp_parent()).unwrap().count(),
1368                0,
1369                "{name}: a temp dir was left behind"
1370            );
1371        }
1372    }
1373
1374    #[tokio::test]
1375    async fn clean_temp_removes_the_dir_and_ignores_a_missing_one() {
1376        let dir = tempfile::tempdir().unwrap();
1377        let temp = dir.path().join("cloudrun_x");
1378        fs::create_dir_all(temp.join("a/b")).unwrap();
1379        fs::write(temp.join("a/b/c"), "x").unwrap();
1380        let mut f = CloudRunFlags::default();
1381        f.build.temp_dir = temp.to_string_lossy().into_owned();
1382        let t = TestEnv::builder(dir.path()).build();
1383
1384        f.clean_temp(&t.env).await.unwrap();
1385        assert!(!temp.exists());
1386        f.clean_temp(&t.env).await.unwrap();
1387        assert_eq!(
1388            t.out.text().lines().nth(1).unwrap(),
1389            format!(
1390                "    \x1b[32m> \x1b[0m [Clean temp starting with {}]",
1391                f.build.temp_dir
1392            )
1393        );
1394    }
1395
1396    /// What the gcloud responder saw in the temp dir at `gcloud run deploy` time.
1397    #[derive(Default, Debug)]
1398    struct Staged {
1399        dockerfile: String,
1400        dockerfile_mode: u32,
1401        gcloudignore: String,
1402        files: Vec<String>,
1403    }
1404
1405    fn list(root: &Path, rel: &Path, out: &mut Vec<String>) {
1406        let mut names: Vec<_> = fs::read_dir(root.join(rel))
1407            .unwrap()
1408            .map(|e| e.unwrap().file_name())
1409            .collect();
1410        names.sort();
1411        for name in names {
1412            let path = rel.join(&name);
1413            out.push(path.to_string_lossy().into_owned());
1414            if root.join(&path).is_dir() {
1415                list(root, &path, out);
1416            }
1417        }
1418    }
1419
1420    /// A workspace with source, a root `Dockerfile`, `.git` and `target` dirs; the gcloud
1421    /// responder records the staged temp dir and answers `run deploy` with `deploy_exit`.
1422    fn run_fixture(deploy_exit: i32) -> (Workspace, TestEnv, Arc<Mutex<Staged>>) {
1423        let ws = Workspace::new("", "agent", &["agent"]);
1424        let root = ws.root();
1425        fs::write(root.join("Dockerfile"), "FROM user-image\n").unwrap();
1426        fs::create_dir_all(root.join(".git")).unwrap();
1427        fs::write(root.join(".git/HEAD"), "ref\n").unwrap();
1428        fs::create_dir_all(root.join("target/release")).unwrap();
1429        fs::write(root.join("target/release/agent"), "bin").unwrap();
1430        let staged = Arc::new(Mutex::new(Staged::default()));
1431        let seen = staged.clone();
1432        let t = ws.env_with(move |c| {
1433            if c.args.get(2).map(String::as_str) == Some("deploy") {
1434                let temp = Path::new(&c.dir);
1435                let mut s = seen.lock().unwrap();
1436                s.dockerfile = fs::read_to_string(temp.join("Dockerfile")).unwrap();
1437                s.dockerfile_mode = fs::metadata(temp.join("Dockerfile"))
1438                    .unwrap()
1439                    .permissions()
1440                    .mode()
1441                    & 0o777;
1442                s.gcloudignore = fs::read_to_string(temp.join(".gcloudignore")).unwrap_or_default();
1443                list(temp, Path::new(""), &mut s.files);
1444                return Canned::exit(deploy_exit);
1445            }
1446            Canned::success(Vec::new())
1447        });
1448        (ws, t, staged)
1449    }
1450
1451    fn cloud_run_args(ws: &Workspace, temp_dir: &Path) -> Vec<String> {
1452        [
1453            "-r",
1454            "us-central1",
1455            "-p",
1456            "my-proj",
1457            "-s",
1458            "my-svc",
1459            "-t",
1460            &temp_dir.to_string_lossy(),
1461        ]
1462        .iter()
1463        .map(|s| s.to_string())
1464        .chain(std::iter::once(format!(
1465            "--entry_point_path={}",
1466            ws.root().display()
1467        )))
1468        .collect()
1469    }
1470
1471    #[tokio::test]
1472    async fn deploy_on_cloud_run_runs_go_steps_in_order() {
1473        let (ws, t, staged) = run_fixture(0);
1474        let root = ws.root();
1475        // A temp parent inside the workspace: the staging walk must skip the temp dir.
1476        let parent = root.join("build-tmp");
1477        fs::create_dir(&parent).unwrap();
1478        let args = cloud_run_args(&ws, &parent);
1479        let args: Vec<&str> = args.iter().map(String::as_str).collect();
1480        let mut f = parse(&args);
1481        let flags_line = f.go_v();
1482
1483        f.deploy_on_cloud_run(&t.env).await.unwrap();
1484
1485        let temp = f.build.temp_dir.clone();
1486        assert!(!Path::new(&temp).exists(), "temp dir kept after success");
1487        let calls = t.runner.calls();
1488        let got: Vec<(Vec<String>, String)> = calls
1489            .iter()
1490            .map(|c| (c.args.clone(), c.dir.clone()))
1491            .collect();
1492        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
1493        let manifest = root.join("Cargo.toml");
1494        assert_eq!(
1495            got,
1496            vec![
1497                (
1498                    s(&[
1499                        "cargo",
1500                        "metadata",
1501                        "--format-version",
1502                        "1",
1503                        "--no-deps",
1504                        "--manifest-path",
1505                        &manifest.to_string_lossy(),
1506                    ]),
1507                    root.to_string_lossy().into_owned(),
1508                ),
1509                (
1510                    s(&[
1511                        "gcloud",
1512                        "run",
1513                        "deploy",
1514                        "my-svc",
1515                        "--source",
1516                        ".",
1517                        "--set-secrets=GOOGLE_API_KEY=GOOGLE_API_KEY:latest",
1518                        "--region",
1519                        "us-central1",
1520                        "--project",
1521                        "my-proj",
1522                        "--ingress",
1523                        "all",
1524                        "--no-allow-unauthenticated",
1525                    ]),
1526                    temp.clone(),
1527                ),
1528                (
1529                    s(&[
1530                        "gcloud",
1531                        "run",
1532                        "services",
1533                        "proxy",
1534                        "my-svc",
1535                        "--project",
1536                        "my-proj",
1537                        "--port",
1538                        "8081",
1539                        "--region",
1540                        "us-central1",
1541                    ]),
1542                    String::new(),
1543                ),
1544            ]
1545        );
1546
1547        let staged = staged.lock().unwrap();
1548        assert!(staged.dockerfile.starts_with(&format!(
1549            "\nFROM rust:{CHANNEL}-bookworm AS builder\nWORKDIR /app/\nCOPY . /app/\nRUN cargo build --release --locked --target-dir /gadk-target -p agent --bin agent\n"
1550        )));
1551        assert!(staged.dockerfile.ends_with(
1552            r#"CMD ["/app/agent", "web", "-host", "0.0.0.0", "-port", "8080", "api", "-webui_address", "127.0.0.1:8081", "a2a", "--a2a_agent_url", "http://127.0.0.1:8081", "webui", "--api_server_address", "http://127.0.0.1:8081/api"]"#
1553        ));
1554        assert_eq!(staged.dockerfile_mode, 0o600);
1555        assert_eq!(staged.gcloudignore, GCLOUDIGNORE);
1556        assert_eq!(
1557            staged.files,
1558            [
1559                ".gcloudignore",
1560                "Cargo.lock",
1561                "Cargo.toml",
1562                "Dockerfile",
1563                "build-tmp",
1564                "rust-toolchain.toml",
1565                "src",
1566                "src/main.rs",
1567            ]
1568        );
1569
1570        let out = t.out.text();
1571        let banners: Vec<&str> = out
1572            .lines()
1573            .filter(|l| l.ends_with("Starting\x1b[0m"))
1574            .collect();
1575        assert_eq!(
1576            banners,
1577            [
1578                "Computing flags & preparing temp : \x1b[32mStarting\x1b[0m",
1579                "Staging source : \x1b[32mStarting\x1b[0m",
1580                "Preparing Dockerfile : \x1b[32mStarting\x1b[0m",
1581                "Deploying to Cloud Run : \x1b[32mStarting\x1b[0m",
1582                "Cleaning temp : \x1b[32mStarting\x1b[0m",
1583                "Running local gcloud authenticating proxy : \x1b[32mStarting\x1b[0m",
1584            ]
1585        );
1586        let p = |s: &str| format!("    \x1b[32m> \x1b[0m [{s}]\n");
1587        let banner_line = |s: &str| p(&center_string(s, 80));
1588        let proxy_step = [
1589            "Running local gcloud authenticating proxy : \x1b[32mStarting\x1b[0m\n".to_string(),
1590            p(&"-".repeat(80)),
1591            banner_line(""),
1592            banner_line("Running ADK Web UI on http://127.0.0.1:8081/ui/    <-- open this"),
1593            banner_line("ADK REST API on http://127.0.0.1:8081/api/         "),
1594            banner_line(""),
1595            banner_line("Press Ctrl-C to stop"),
1596            banner_line(""),
1597            p(&"-".repeat(80)),
1598            p("Running :  \x1b[33m  \x1b[0m   gcloud run services proxy my-svc --project my-proj --port 8081 --region us-central1"),
1599            "\n".to_string(),
1600            "Running local gcloud authenticating proxy : \x1b[32mFinished successfully\x1b[0m\n".to_string(),
1601        ]
1602        .concat();
1603        assert!(out.starts_with(&format!("{flags_line}\n")), "{out}");
1604        assert!(out.ends_with(&proxy_step), "{out}");
1605        assert!(out.contains(&p(&format!("Copying {} to {temp}", root.display()))));
1606        assert!(out.contains(&p(&format!(
1607            "Running :  \x1b[33m {temp} \x1b[0m   gcloud run deploy my-svc --source . --set-secrets=GOOGLE_API_KEY=GOOGLE_API_KEY:latest --region us-central1 --project my-proj --ingress all --no-allow-unauthenticated"
1608        ))));
1609    }
1610
1611    #[tokio::test]
1612    async fn deploy_on_cloud_run_keeps_a_user_gcloudignore() {
1613        let (ws, t, staged) = run_fixture(0);
1614        fs::write(ws.root().join(".gcloudignore"), "custom\n").unwrap();
1615        let args = cloud_run_args(&ws, &ws.temp_parent());
1616        let args: Vec<&str> = args.iter().map(String::as_str).collect();
1617        let mut f = parse(&args);
1618
1619        f.deploy_on_cloud_run(&t.env).await.unwrap();
1620
1621        assert_eq!(staged.lock().unwrap().gcloudignore, "custom\n");
1622        assert!(!t.out.text().contains(".gcloudignore]"));
1623    }
1624
1625    #[tokio::test]
1626    async fn deploy_on_cloud_run_keeps_the_temp_dir_when_gcloud_fails() {
1627        let (ws, t, _) = run_fixture(1);
1628        let args = cloud_run_args(&ws, &ws.temp_parent());
1629        let args: Vec<&str> = args.iter().map(String::as_str).collect();
1630        let mut f = parse(&args);
1631
1632        let err = f.deploy_on_cloud_run(&t.env).await.unwrap_err();
1633
1634        assert_eq!(err, "exit status 1");
1635        assert!(
1636            Path::new(&f.build.temp_dir).is_dir(),
1637            "temp dir removed after a failure"
1638        );
1639        let calls = t.runner.calls();
1640        assert_eq!(calls.len(), 2, "{calls:?}");
1641        let out = t.out.text();
1642        assert!(out.ends_with(
1643            "Deploying to Cloud Run : \x1b[31mFinished with error\x1b[0m\nError: exit status 1\n"
1644        ));
1645        assert!(!out.contains("Cleaning temp"));
1646    }
1647
1648    #[tokio::test]
1649    async fn steps_need_a_resolved_target() {
1650        let dir = tempfile::tempdir().unwrap();
1651        let t = TestEnv::builder(dir.path()).build();
1652        let mut f = CloudRunFlags::default();
1653        assert_eq!(f.stage_source(&t.env).await, Err(NO_TARGET.to_string()));
1654        assert_eq!(
1655            f.prepare_dockerfile(&t.env).await,
1656            Err(NO_TARGET.to_string())
1657        );
1658    }
1659}