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