1use std::collections::HashMap;
28use std::ffi::OsString;
29use std::path::{Path, PathBuf};
30use std::process::Stdio;
31use std::sync::Arc;
32use std::time::Duration;
33
34use adk_sandbox::{
35 ExecRequest, ExecResult, Language, ProcessBackend, SandboxBackend, SandboxError,
36};
37use tracing::{debug, info, instrument};
38
39use crate::diagnostics::{RustDiagnostic, parse_diagnostics};
40use crate::error::CodeError;
41use crate::harness::{HARNESS_TEMPLATE, extract_structured_output, validate_rust_source};
42use crate::host_process;
43
44#[derive(Debug, Clone)]
55pub struct RustExecutorConfig {
56 pub rustc_path: String,
58 pub serde_json_path: Option<PathBuf>,
61 pub rustc_flags: Vec<String>,
63}
64
65impl Default for RustExecutorConfig {
66 fn default() -> Self {
67 Self { rustc_path: "rustc".to_string(), serde_json_path: None, rustc_flags: vec![] }
68 }
69}
70
71struct RustcOutput {
73 success: bool,
74 stderr: String,
75}
76
77#[derive(Debug, Clone)]
82pub struct CodeResult {
83 pub exec_result: ExecResult,
85 pub diagnostics: Vec<RustDiagnostic>,
87 pub output: Option<serde_json::Value>,
89 pub display_stdout: String,
91}
92
93pub struct RustExecutor {
128 backend: Arc<dyn SandboxBackend>,
129 config: RustExecutorConfig,
130}
131
132impl RustExecutor {
133 pub fn new(backend: Arc<dyn SandboxBackend>, config: RustExecutorConfig) -> Self {
135 Self { backend, config }
136 }
137
138 #[instrument(skip_all, fields(backend = %self.backend.name()))]
150 pub async fn execute(
151 &self,
152 code: &str,
153 input: Option<&serde_json::Value>,
154 timeout: Duration,
155 ) -> Result<CodeResult, CodeError> {
156 validate_rust_source(code).map_err(|e| CodeError::InvalidCode(e.to_string()))?;
158
159 let tmp_dir = tempfile::tempdir()
161 .map_err(|e| CodeError::InvalidCode(format!("failed to create temp directory: {e}")))?;
162
163 let source_path = tmp_dir.path().join("main.rs");
164 let binary_path = tmp_dir.path().join(format!("main{}", std::env::consts::EXE_SUFFIX));
168
169 let harnessed_source = HARNESS_TEMPLATE.replace("{user_code}", code);
171 tokio::fs::write(&source_path, &harnessed_source)
172 .await
173 .map_err(|e| CodeError::InvalidCode(format!("failed to write source file: {e}")))?;
174
175 debug!(source_path = %source_path.display(), "wrote harnessed source");
176
177 let serde_json_path = self.find_serde_json_dep().await?;
179
180 let diagnostics = self.check(&source_path, &serde_json_path, timeout).await?;
182
183 self.build(&source_path, &binary_path, &serde_json_path, timeout).await?;
185
186 info!("compilation succeeded, delegating execution to sandbox backend");
187
188 let stdin = input.map(|v| serde_json::to_string(v).unwrap_or_default());
190 let exec_request = ExecRequest {
191 language: Language::Command,
192 code: binary_path.to_string_lossy().to_string(),
193 stdin,
194 timeout,
195 memory_limit_mb: None,
196 env: HashMap::new(),
197 };
198
199 let exec_result = self.backend.execute(exec_request).await?;
200
201 let (output, display_stdout) = extract_structured_output(&exec_result.stdout);
203
204 debug!(
205 exit_code = exec_result.exit_code,
206 duration_ms = exec_result.duration.as_millis() as u64,
207 has_output = output.is_some(),
208 "execution completed"
209 );
210
211 Ok(CodeResult { exec_result, diagnostics, output, display_stdout })
212 }
213
214 async fn check(
219 &self,
220 source_path: &Path,
221 serde_json_path: &Option<PathBuf>,
222 timeout: Duration,
223 ) -> Result<Vec<RustDiagnostic>, CodeError> {
224 let check_dir = tempfile::tempdir().map_err(|e| {
226 CodeError::InvalidCode(format!("failed to create check temp directory: {e}"))
227 })?;
228 let metadata_out = check_dir.path().join("check_output");
229
230 let mut args: Vec<OsString> = vec![
231 source_path.into(),
232 "--edition".into(),
233 "2021".into(),
234 "--error-format=json".into(),
235 "--color".into(),
236 "never".into(),
237 "--emit=metadata".into(),
238 "-o".into(),
239 metadata_out.into(),
240 ];
241 args.extend(self.dependency_args(serde_json_path));
242
243 let RustcOutput { stderr, .. } = self.run_rustc(args, timeout, "check").await?;
244 let diagnostics = parse_diagnostics(&stderr);
245
246 let has_errors = diagnostics.iter().any(|d| d.level == "error");
247 if has_errors {
248 debug!(
249 error_count = diagnostics.iter().filter(|d| d.level == "error").count(),
250 "check step found errors"
251 );
252 return Err(CodeError::CompileError { diagnostics, stderr });
253 }
254
255 let warning_count = diagnostics.iter().filter(|d| d.level == "warning").count();
256 if warning_count > 0 {
257 debug!(warning_count, "check step found warnings");
258 }
259
260 Ok(diagnostics)
261 }
262
263 async fn build(
265 &self,
266 source_path: &Path,
267 binary_path: &Path,
268 serde_json_path: &Option<PathBuf>,
269 timeout: Duration,
270 ) -> Result<(), CodeError> {
271 let mut args: Vec<OsString> = vec![
272 source_path.into(),
273 "-o".into(),
274 binary_path.into(),
275 "--edition".into(),
276 "2021".into(),
277 ];
278 args.extend(self.dependency_args(serde_json_path));
279
280 let output = self.run_rustc(args, timeout, "build").await?;
281 if !output.success {
282 let diagnostics = parse_diagnostics(&output.stderr);
283 return Err(CodeError::CompileError { diagnostics, stderr: output.stderr });
284 }
285
286 Ok(())
287 }
288
289 fn dependency_args(&self, serde_json_path: &Option<PathBuf>) -> Vec<OsString> {
292 let mut args = Vec::new();
293 if let Some(dep_path) = serde_json_path {
294 args.push("--extern".into());
295 args.push(format!("serde_json={}", dep_path.display()).into());
296
297 if let Some(parent) = dep_path.parent() {
298 args.push("-L".into());
299 args.push(format!("dependency={}", parent.display()).into());
300 }
301 }
302 args.extend(self.config.rustc_flags.iter().map(OsString::from));
303 args
304 }
305
306 async fn run_rustc(
314 &self,
315 args: Vec<OsString>,
316 timeout: Duration,
317 step: &str,
318 ) -> Result<RustcOutput, CodeError> {
319 let capabilities = self.backend.capabilities();
320 let compile_in_backend = cfg!(unix)
322 && capabilities.enforced_limits.filesystem_read_isolation
323 && capabilities.supported_languages.contains(&Language::Command);
324
325 if compile_in_backend {
326 let code = std::iter::once(OsString::from(&self.config.rustc_path))
327 .chain(args)
328 .map(|arg| format!("'{}'", arg.to_string_lossy().replace('\'', r"'\''")))
329 .collect::<Vec<_>>()
330 .join(" ");
331 let env = ProcessBackend::toolchain_env()
332 .into_iter()
333 .filter_map(|(key, value)| value.into_string().ok().map(|value| (key, value)))
334 .collect();
335 debug!(step, "running rustc inside the sandbox backend");
336
337 let request = ExecRequest {
338 language: Language::Command,
339 code,
340 stdin: None,
341 timeout,
342 memory_limit_mb: None,
343 env,
344 };
345 return match self.backend.execute(request).await {
346 Ok(result) => {
347 Ok(RustcOutput { success: result.exit_code == 0, stderr: result.stderr })
348 }
349 Err(SandboxError::Timeout { .. }) => {
350 Err(CodeError::InvalidCode(format!("{step} step timed out")))
351 }
352 Err(error) => Err(error.into()),
353 };
354 }
355
356 let mut cmd = host_process::rustc_command(&self.config.rustc_path);
357 cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
358
359 match tokio::time::timeout(timeout, cmd.output()).await {
360 Ok(Ok(output)) => Ok(RustcOutput {
361 success: output.status.success(),
362 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
363 }),
364 Ok(Err(e)) => {
365 Err(CodeError::InvalidCode(format!("failed to invoke rustc for {step}: {e}")))
366 }
367 Err(_) => Err(CodeError::InvalidCode(format!("{step} step timed out"))),
369 }
370 }
371
372 async fn find_serde_json_dep(&self) -> Result<Option<PathBuf>, CodeError> {
377 let mut searched = Vec::new();
378
379 if let Some(ref path) = self.config.serde_json_path {
381 if path.exists() {
382 debug!(path = %path.display(), "using configured serde_json path");
383 return Ok(Some(path.clone()));
384 }
385 searched.push(format!("config: {}", path.display()));
386 }
387
388 let output = tokio::process::Command::new("cargo")
390 .args(["metadata", "--format-version=1", "--no-deps"])
391 .stdout(std::process::Stdio::piped())
392 .stderr(std::process::Stdio::null())
393 .output()
394 .await;
395
396 if let Ok(output) = output
397 && output.status.success()
398 && let Ok(metadata) = serde_json::from_slice::<serde_json::Value>(&output.stdout)
399 && let Some(target_dir) = metadata["target_directory"].as_str()
400 {
401 let deps_dir = PathBuf::from(target_dir).join("debug").join("deps");
402 searched.push(format!("cargo metadata: {}", deps_dir.display()));
403 if let Some(rlib) = find_rlib_in_dir(&deps_dir, "serde_json").await {
404 debug!(path = %rlib.display(), "found serde_json via cargo metadata");
405 return Ok(Some(rlib));
406 }
407 } else {
408 searched.push("cargo metadata: command failed".to_string());
409 }
410
411 Err(CodeError::DependencyNotFound { name: "serde_json".to_string(), searched })
413 }
414}
415
416async fn find_rlib_in_dir(dir: &Path, crate_name: &str) -> Option<PathBuf> {
418 let prefix = format!("lib{crate_name}-");
419 let mut entries = match tokio::fs::read_dir(dir).await {
420 Ok(entries) => entries,
421 Err(_) => return None,
422 };
423
424 while let Ok(Some(entry)) = entries.next_entry().await {
425 let name = entry.file_name();
426 let name_str = name.to_string_lossy();
427 if name_str.starts_with(&prefix) && name_str.ends_with(".rlib") {
428 return Some(entry.path());
429 }
430 }
431 None
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437 use adk_sandbox::{BackendCapabilities, EnforcedLimits, SandboxError};
438 use async_trait::async_trait;
439 use std::sync::Mutex;
440
441 struct MockBackend {
443 captured: Mutex<Vec<ExecRequest>>,
445 response: Mutex<Option<Result<ExecResult, SandboxError>>>,
447 }
448
449 impl MockBackend {
450 fn new(response: Result<ExecResult, SandboxError>) -> Self {
451 Self { captured: Mutex::new(Vec::new()), response: Mutex::new(Some(response)) }
452 }
453
454 fn success(stdout: &str) -> Self {
455 Self::new(Ok(ExecResult {
456 stdout: stdout.to_string(),
457 stderr: String::new(),
458 exit_code: 0,
459 duration: Duration::from_millis(10),
460 }))
461 }
462 }
463
464 #[async_trait]
465 impl SandboxBackend for MockBackend {
466 fn name(&self) -> &str {
467 "mock"
468 }
469
470 fn capabilities(&self) -> BackendCapabilities {
471 BackendCapabilities {
472 supported_languages: vec![Language::Command],
473 isolation_class: "mock".to_string(),
474 enforced_limits: EnforcedLimits {
475 timeout: true,
476 memory: false,
477 network_isolation: false,
478 filesystem_write_isolation: false,
479 filesystem_read_isolation: false,
480 environment_isolation: false,
481 },
482 }
483 }
484
485 async fn execute(&self, request: ExecRequest) -> Result<ExecResult, SandboxError> {
486 self.captured.lock().unwrap().push(request);
487 self.response
488 .lock()
489 .unwrap()
490 .take()
491 .unwrap_or(Err(SandboxError::ExecutionFailed("no canned response".to_string())))
492 }
493 }
494
495 struct ReadConfiningBackend {
497 captured: Mutex<Vec<ExecRequest>>,
498 }
499
500 #[async_trait]
501 impl SandboxBackend for ReadConfiningBackend {
502 fn name(&self) -> &str {
503 "read-confining"
504 }
505
506 fn capabilities(&self) -> BackendCapabilities {
507 BackendCapabilities {
508 supported_languages: vec![Language::Command],
509 isolation_class: "mock".to_string(),
510 enforced_limits: EnforcedLimits {
511 timeout: true,
512 memory: false,
513 network_isolation: true,
514 filesystem_write_isolation: true,
515 filesystem_read_isolation: true,
516 environment_isolation: true,
517 },
518 }
519 }
520
521 async fn execute(&self, request: ExecRequest) -> Result<ExecResult, SandboxError> {
522 self.captured.lock().unwrap().push(request);
523 Ok(ExecResult {
524 stdout: r#"{"ok":true}"#.to_string(),
525 stderr: String::new(),
526 exit_code: 0,
527 duration: Duration::from_millis(1),
528 })
529 }
530 }
531
532 #[cfg(unix)]
535 #[tokio::test]
536 async fn compilation_runs_inside_a_read_confining_backend() {
537 let tmp_dir = tempfile::tempdir().unwrap();
538 let fake_rlib = tmp_dir.path().join("libserde_json-abc123.rlib");
539 tokio::fs::write(&fake_rlib, b"fake rlib").await.unwrap();
540
541 let backend = Arc::new(ReadConfiningBackend { captured: Mutex::new(Vec::new()) });
542 let config = RustExecutorConfig {
543 rustc_path: "/nonexistent/rustc-must-not-run-on-host".to_string(),
544 serde_json_path: Some(fake_rlib),
545 ..Default::default()
546 };
547 let executor = RustExecutor::new(backend.clone(), config);
548
549 let code = "fn run(input: serde_json::Value) -> serde_json::Value { input }";
550 let result = executor.execute(code, None, Duration::from_secs(5)).await.unwrap();
551 assert_eq!(result.output, Some(serde_json::json!({ "ok": true })));
552
553 let captured = backend.captured.lock().unwrap();
554 assert_eq!(captured.len(), 3, "check, build, and execute all go through the backend");
555
556 let toolchain: Vec<String> =
557 ProcessBackend::toolchain_env().into_iter().map(|(key, _)| key).collect();
558 for (request, step_flag) in captured[..2].iter().zip(["'--error-format=json'", "'-o'"]) {
559 assert_eq!(request.language, Language::Command);
560 assert!(
561 request.code.starts_with("'/nonexistent/rustc-must-not-run-on-host' "),
562 "{}",
563 request.code
564 );
565 assert!(request.code.contains(step_flag), "{}", request.code);
566 assert!(
567 request.env.keys().all(|key| toolchain.contains(key)),
568 "compile environment must be the toolchain allowlist: {:?}",
569 request.env.keys()
570 );
571 }
572 assert!(captured[2].env.is_empty());
573 }
574
575 #[test]
576 fn default_config() {
577 let config = RustExecutorConfig::default();
578 assert_eq!(config.rustc_path, "rustc");
579 assert!(config.serde_json_path.is_none());
580 assert!(config.rustc_flags.is_empty());
581 }
582
583 #[tokio::test]
584 async fn check_valid_code_produces_no_errors() {
585 let backend = Arc::new(MockBackend::success(r#"{"result":42}"#));
586 let executor = RustExecutor::new(backend, RustExecutorConfig::default());
587
588 let tmp_dir = tempfile::tempdir().unwrap();
589 let source_path = tmp_dir.path().join("valid.rs");
590 let code = r#"
591fn run(input: serde_json::Value) -> serde_json::Value {
592 input
593}
594"#;
595 let harnessed = HARNESS_TEMPLATE.replace("{user_code}", code);
596 tokio::fs::write(&source_path, &harnessed).await.unwrap();
597
598 let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
601
602 match result {
605 Ok(diagnostics) => {
606 assert!(
608 !diagnostics.iter().any(|d| d.level == "error"),
609 "expected no error diagnostics for valid code"
610 );
611 }
612 Err(CodeError::CompileError { diagnostics, .. }) => {
613 assert!(
615 diagnostics.iter().any(|d| d.level == "error"),
616 "expected error diagnostics when serde_json is missing"
617 );
618 }
619 Err(other) => panic!("unexpected error: {other}"),
620 }
621 }
622
623 #[tokio::test]
624 async fn check_invalid_code_returns_compile_error() {
625 let backend = Arc::new(MockBackend::success(""));
626 let executor = RustExecutor::new(backend, RustExecutorConfig::default());
627
628 let tmp_dir = tempfile::tempdir().unwrap();
629 let source_path = tmp_dir.path().join("invalid.rs");
630 let code = "fn broken( { }";
632 tokio::fs::write(&source_path, code).await.unwrap();
633
634 let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
635
636 match result {
637 Err(CodeError::CompileError { diagnostics, stderr }) => {
638 assert!(
639 diagnostics.iter().any(|d| d.level == "error"),
640 "expected at least one error diagnostic"
641 );
642 assert!(!stderr.is_empty(), "expected non-empty stderr");
643 }
644 other => panic!("expected CompileError, got: {other:?}"),
645 }
646 }
647
648 #[tokio::test]
649 async fn check_warnings_are_returned_without_halting() {
650 let backend = Arc::new(MockBackend::success(""));
651 let executor = RustExecutor::new(backend, RustExecutorConfig::default());
652
653 let tmp_dir = tempfile::tempdir().unwrap();
654 let source_path = tmp_dir.path().join("warnings.rs");
655 let code = "fn main() { let x = 42; }";
657 tokio::fs::write(&source_path, code).await.unwrap();
658
659 let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
660
661 match result {
662 Ok(diagnostics) => {
663 assert!(
665 diagnostics.iter().any(|d| d.level == "warning"),
666 "expected at least one warning diagnostic, got: {diagnostics:?}"
667 );
668 }
669 Err(CodeError::CompileError { diagnostics, .. }) => {
670 panic!("unexpected compile errors: {diagnostics:?}");
672 }
673 Err(other) => panic!("unexpected error: {other}"),
674 }
675 }
676
677 #[tokio::test]
678 async fn serde_json_discovery_config_path_exists() {
679 let tmp_dir = tempfile::tempdir().unwrap();
680 let fake_rlib = tmp_dir.path().join("libserde_json-abc123.rlib");
681 tokio::fs::write(&fake_rlib, b"fake rlib").await.unwrap();
682
683 let config =
684 RustExecutorConfig { serde_json_path: Some(fake_rlib.clone()), ..Default::default() };
685 let backend = Arc::new(MockBackend::success(""));
686 let executor = RustExecutor::new(backend, config);
687
688 let result = executor.find_serde_json_dep().await.unwrap();
689 assert_eq!(result, Some(fake_rlib));
690 }
691
692 #[tokio::test]
693 async fn serde_json_discovery_config_path_missing() {
694 let config = RustExecutorConfig {
695 serde_json_path: Some(PathBuf::from("/nonexistent/libserde_json.rlib")),
696 ..Default::default()
697 };
698 let backend = Arc::new(MockBackend::success(""));
699 let executor = RustExecutor::new(backend, config);
700
701 let result = executor.find_serde_json_dep().await;
704 match result {
705 Err(CodeError::DependencyNotFound { name, searched }) => {
706 assert_eq!(name, "serde_json");
707 assert!(
708 searched.iter().any(|s| s.contains("/nonexistent/")),
709 "expected searched to include the config path, got: {searched:?}"
710 );
711 }
712 Ok(Some(_)) => {}
714 other => panic!("unexpected result: {other:?}"),
715 }
716 }
717
718 #[test]
719 fn code_error_from_sandbox_error() {
720 let sandbox_err = SandboxError::Timeout { timeout: Duration::from_secs(5) };
721 let code_err: CodeError = sandbox_err.into();
722 assert!(matches!(code_err, CodeError::Sandbox(_)));
723 assert!(code_err.to_string().contains("sandbox error"));
724 }
725
726 #[test]
727 fn validate_rejects_fn_main() {
728 let code = "fn main() { }";
729 let result = validate_rust_source(code);
730 assert!(result.is_err());
731 }
732
733 #[test]
734 fn validate_accepts_valid_run() {
735 let code = r#"
736fn run(input: serde_json::Value) -> serde_json::Value {
737 input
738}
739"#;
740 assert!(validate_rust_source(code).is_ok());
741 }
742}