Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / runner / src / lib.rs

lib.rs1372 lines · 47.8 KiBRaw
1//! agent-runner: HTTP sandbox API served from inside the builder container.
2//!
3//! Implements every route in `proto` exactly. See `proto/src/lib.rs` for the
4//! wire contract. No auth: this server only listens on the internal Docker
5//! network and itself runs inside the untrusted sandbox.
6
7use std::collections::HashMap;
8use std::os::unix::process::CommandExt;
9use std::path::{Component, Path, PathBuf};
10use std::process::Stdio;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::{Duration, Instant};
14
15use axum::body::Bytes;
16use axum::extract::{Path as AxumPath, State};
17use axum::http::{StatusCode, header};
18use axum::response::{IntoResponse, Json};
19use axum::routing::{get, post};
20use axum::Router;
21use proto::{
22 CommitRequest, CommitResponse, DiffResponse, EditRequest, ErrorBody, ExecKind, ExecRequest,
23 ExecResponse, HealthResponse, KillResponse, ListRequest, ListResponse, PrepareRequest,
24 PrepareResponse, ReadRequest, ReadResponse, ResumeSpec, SearchRequest, SearchResponse,
25 WriteRequest, AGENT_BRANCH_PREFIX, RUNNER_PORT,
26};
27use tokio::sync::{Mutex, Semaphore};
28
29/// Stdout/stderr cap per stream for exec/search (head + tail kept).
30pub const OUTPUT_CAP_BYTES: usize = 64 * 1024;
31/// Cap for `diff.stat`.
32pub const DIFF_STAT_CAP_BYTES: usize = 32 * 1024;
33/// Cap for `diff.diff`.
34pub const DIFF_CAP_BYTES: usize = 256 * 1024;
35/// Default line cap for reads.
36pub const READ_DEFAULT_MAX_LINES: usize = 2000;
37/// Hard ceiling for reads even when the caller asks for more.
38pub const READ_HARD_MAX_LINES: usize = 100_000;
39/// Max entries returned by list.
40pub const LIST_MAX_ENTRIES: usize = 2000;
41/// Bounded time for `./gradlew --stop` after a killed/timed-out build.
42const GRADLE_STOP_TIMEOUT: Duration = Duration::from_secs(120);
43/// Timeout for individual git invocations.
44const GIT_TIMEOUT: Duration = Duration::from_secs(300);
45/// Timeout for ripgrep searches.
46const SEARCH_TIMEOUT: Duration = Duration::from_secs(120);
47/// Grace period to drain stdio after the process exits (a backgrounded
48/// grandchild can hold the pipes open; don't wait forever).
49const STDIO_DRAIN_GRACE: Duration = Duration::from_secs(10);
50/// Name of the file (inside `<slot>/.git/`) recording the branch base.
51const AGENT_BASE_FILE: &str = "agent-base";
52
53/// Error with an HTTP status, rendered as [`ErrorBody`] JSON.
54#[derive(Debug)]
55pub struct ApiError {
56 pub status: StatusCode,
57 pub message: String,
58}
59
60impl ApiError {
61 fn new(status: StatusCode, message: impl Into<String>) -> Self {
62 Self {
63 status,
64 message: message.into(),
65 }
66 }
67
68 fn bad_request(message: impl Into<String>) -> Self {
69 Self::new(StatusCode::BAD_REQUEST, message)
70 }
71
72 fn not_found(message: impl Into<String>) -> Self {
73 Self::new(StatusCode::NOT_FOUND, message)
74 }
75
76 fn conflict(message: impl Into<String>) -> Self {
77 Self::new(StatusCode::CONFLICT, message)
78 }
79
80 fn internal(message: impl Into<String>) -> Self {
81 Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
82 }
83}
84
85type ErrTuple = (StatusCode, Json<ErrorBody>);
86
87fn to_err_tuple(e: ApiError) -> ErrTuple {
88 (e.status, Json(ErrorBody { error: e.message }))
89}
90
91struct RunningEntry {
92 pgid: i32,
93 killed: Arc<AtomicBool>,
94 is_build: bool,
95}
96
97pub struct AppState {
98 pub slots_dir: PathBuf,
99 pub mirror: PathBuf,
100 pub num_slots: u32,
101 build_sem: Arc<Semaphore>,
102 build_running: AtomicBool,
103 running: Mutex<HashMap<u32, RunningEntry>>,
104 build_slot: Mutex<Option<u32>>,
105}
106
107impl AppState {
108 pub fn new(slots_dir: PathBuf, mirror: PathBuf, num_slots: u32) -> Self {
109 Self {
110 slots_dir,
111 mirror,
112 num_slots: num_slots.max(1),
113 build_sem: Arc::new(Semaphore::new(1)),
114 build_running: AtomicBool::new(false),
115 running: Mutex::new(HashMap::new()),
116 build_slot: Mutex::new(None),
117 }
118 }
119
120 pub fn from_env() -> Self {
121 let num_slots = std::env::var("RUNNER_SLOTS")
122 .ok()
123 .and_then(|v| v.parse::<u32>().ok())
124 .unwrap_or(4);
125 let slots_dir = std::env::var("RUNNER_SLOTS_DIR")
126 .map(PathBuf::from)
127 .unwrap_or_else(|_| PathBuf::from("/builds/slots"));
128 let mirror = std::env::var("RUNNER_MIRROR")
129 .map(PathBuf::from)
130 .unwrap_or_else(|_| PathBuf::from("/mirror/Modern-Apps.git"));
131 Self::new(slots_dir, mirror, num_slots)
132 }
133
134 pub fn listen_addr() -> String {
135 std::env::var("RUNNER_LISTEN").unwrap_or_else(|_| format!("0.0.0.0:{RUNNER_PORT}"))
136 }
137}
138
139/// Parse a `{slot}` path param: integer in `0..num_slots`, else 404.
140pub fn parse_slot(state: &AppState, raw: &str) -> Result<u32, ApiError> {
141 match raw.parse::<u32>() {
142 Ok(n) if n < state.num_slots => Ok(n),
143 _ => Err(ApiError::not_found(format!(
144 "unknown slot {raw:?}; valid slots are 0..{}",
145 state.num_slots
146 ))),
147 }
148}
149
150pub fn slot_root(state: &AppState, slot: u32) -> PathBuf {
151 state.slots_dir.join(format!("slot-{slot}"))
152}
153
154/// Resolve a request path relative to the slot root.
155///
156/// Rejects absolute paths, `..` escapes, NUL bytes, anything under `.git/`,
157/// and symlinks (on existing ancestors) that resolve outside the slot root.
158pub fn resolve_in_slot(slot_root: &Path, rel: &str) -> Result<PathBuf, String> {
159 if rel.is_empty() {
160 return Err("empty path".to_string());
161 }
162 if rel.contains('\0') {
163 return Err("path contains NUL byte".to_string());
164 }
165 let rel_path = Path::new(rel);
166 if rel_path.is_absolute() {
167 return Err(format!("absolute paths are rejected: {rel:?}"));
168 }
169 // Lexical normalization: collapse `.`, reject escaping `..`.
170 let mut parts: Vec<String> = Vec::new();
171 for comp in rel_path.components() {
172 match comp {
173 Component::Prefix(_) | Component::RootDir => {
174 return Err(format!("absolute paths are rejected: {rel:?}"));
175 }
176 Component::CurDir => {}
177 Component::ParentDir => {
178 if parts.pop().is_none() {
179 return Err(format!("path escapes the slot root: {rel:?}"));
180 }
181 }
182 Component::Normal(c) => parts.push(c.to_string_lossy().into_owned()),
183 }
184 }
185 if parts.is_empty() {
186 return Err(format!("path resolves to the slot root itself: {rel:?}"));
187 }
188 if parts[0] == ".git" {
189 return Err("paths under .git/ are rejected".to_string());
190 }
191 let mut resolved = slot_root.to_path_buf();
192 for p in &parts {
193 resolved.push(p);
194 }
195 // Symlink check: canonicalize the longest existing prefix (the slot root
196 // itself if nothing exists yet) and require it to stay inside the
197 // canonical slot root. This covers new files created through a symlinked
198 // directory as well as existing symlinked files.
199 let canonical_root = slot_root
200 .canonicalize()
201 .map_err(|e| format!("slot root is not usable: {e}"))?;
202 let mut probe = resolved.clone();
203 loop {
204 if probe.exists() {
205 let canon = probe
206 .canonicalize()
207 .map_err(|e| format!("cannot canonicalize {probe:?}: {e}"))?;
208 if !canon.starts_with(&canonical_root) {
209 return Err(format!("path resolves outside the slot root: {rel:?}"));
210 }
211 break;
212 }
213 if !probe.pop() {
214 break;
215 }
216 }
217 Ok(resolved)
218}
219
220/// Validate an agent branch name: `agent/` prefix + safe ref name.
221pub fn validate_branch(branch: &str) -> Result<(), String> {
222 if !branch.starts_with(AGENT_BRANCH_PREFIX) {
223 return Err(format!(
224 "branch must start with {AGENT_BRANCH_PREFIX:?}, got {branch:?}"
225 ));
226 }
227 if branch.contains('\0') || branch.chars().any(|c| c.is_control()) {
228 return Err("branch contains control characters".to_string());
229 }
230 for bad in ["..", "@{", "//", "~", "^", ":", "?", "*", "[", "\\"] {
231 if branch.contains(bad) {
232 return Err(format!("branch contains forbidden sequence {bad:?}"));
233 }
234 }
235 if branch.starts_with('/') || branch.starts_with('.') {
236 return Err("branch has a forbidden leading character".to_string());
237 }
238 if branch.ends_with('/') || branch.ends_with('.') || branch.ends_with(".lock") {
239 return Err("branch has a forbidden trailing component".to_string());
240 }
241 for comp in branch.split('/') {
242 if comp.is_empty() || comp.starts_with('.') {
243 return Err(format!("branch has a forbidden component in {branch:?}"));
244 }
245 if comp == "agent" && branch == "agent/" {
246 return Err("branch name is empty after the agent/ prefix".to_string());
247 }
248 if !comp
249 .chars()
250 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
251 {
252 return Err(format!(
253 "branch contains a forbidden character in {branch:?}"
254 ));
255 }
256 }
257 Ok(())
258}
259
260/// Keep head + tail of `data` over `cap` bytes, with a marker line.
261pub fn truncate_bytes(data: &[u8], cap: usize) -> (String, bool) {
262 if data.len() <= cap {
263 return (String::from_utf8_lossy(data).into_owned(), false);
264 }
265 let half = cap / 2;
266 let marker = format!("\n... [truncated {} bytes] ...\n", data.len() - cap);
267 let mut out = String::from_utf8_lossy(&data[..half]).into_owned();
268 out.push_str(&marker);
269 out.push_str(&String::from_utf8_lossy(&data[data.len() - half..]));
270 (out, true)
271}
272
273/// Replace exactly one occurrence of `old` with `new`.
274pub fn apply_edit(content: &str, old: &str, new: &str) -> Result<String, String> {
275 if old.is_empty() {
276 return Err("`old` must not be empty".to_string());
277 }
278 let count = content.matches(old).count();
279 if count != 1 {
280 return Err(format!(
281 "`old` matched {count} times (expected exactly 1); refusing to edit"
282 ));
283 }
284 Ok(content.replacen(old, new, 1))
285}
286
287fn read_base_sha(slot: &Path) -> Result<String, ApiError> {
288 let base_file = slot.join(".git").join(AGENT_BASE_FILE);
289 let raw = std::fs::read_to_string(&base_file).map_err(|_| {
290 ApiError::conflict("slot has no recorded base; run prepare first".to_string())
291 })?;
292 let sha = raw.trim().to_string();
293 if sha.is_empty() {
294 return Err(ApiError::conflict(
295 "slot has no recorded base; run prepare first".to_string(),
296 ));
297 }
298 Ok(sha)
299}
300
301fn git_args(mirror: &Path, slot: Option<&Path>, args: &[&str]) -> Vec<String> {
302 let mut out = vec![
303 "-c".to_string(),
304 format!("safe.directory={}", mirror.display()),
305 ];
306 if let Some(slot) = slot {
307 out.push("-c".to_string());
308 out.push(format!("safe.directory={}", slot.display()));
309 out.push("-C".to_string());
310 out.push(slot.display().to_string());
311 }
312 out.extend(args.iter().map(|s| s.to_string()));
313 out
314}
315
316async fn run_git(
317 mirror: &Path,
318 slot: Option<&Path>,
319 args: &[&str],
320) -> Result<std::process::Output, ApiError> {
321 let argv = git_args(mirror, slot, args);
322 let mut cmd = tokio::process::Command::new("git");
323 cmd.args(&argv);
324 cmd.stdin(Stdio::null());
325 cmd.stdout(Stdio::piped());
326 cmd.stderr(Stdio::piped());
327 cmd.kill_on_drop(true);
328 let child = cmd.spawn().map_err(|e| {
329 ApiError::internal(format!("failed to spawn git {}: {e}", args.join(" ")))
330 })?;
331 let status_str = args.join(" ");
332 let pid = child.id();
333 match tokio::time::timeout(GIT_TIMEOUT, child.wait_with_output()).await {
334 Ok(Ok(out)) => Ok(out),
335 Ok(Err(e)) => Err(ApiError::internal(format!(
336 "failed to wait for git {status_str}: {e}"
337 ))),
338 Err(_) => {
339 // wait_with_output consumed the Child; kill by pid explicitly
340 // (kill_on_drop cannot fire since the Child was moved). These are
341 // leaf git invocations, so signalling the pid is sufficient.
342 if let Some(pid) = pid {
343 unsafe {
344 libc::kill(pid as i32, libc::SIGKILL);
345 }
346 }
347 Err(ApiError::internal(format!(
348 "git {status_str} timed out after {}s",
349 GIT_TIMEOUT.as_secs()
350 )))
351 }
352 }
353}
354
355fn check_git_output(out: &std::process::Output, what: &str) -> Result<String, ApiError> {
356 if out.status.success() {
357 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
358 } else {
359 Err(ApiError::internal(format!(
360 "{what} failed: {}",
361 String::from_utf8_lossy(&out.stderr).trim()
362 )))
363 }
364}
365
366/// True when `s` is a 40-char hex object id.
367fn is_hex_sha(s: &str) -> bool {
368 s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
369}
370
371/// Validate a parked-WIP ref: exactly `refs/agent-wip/<digits>`.
372fn validate_wip_ref(wip_ref: &str) -> Result<(), String> {
373 const PREFIX: &str = "refs/agent-wip/";
374 match wip_ref.strip_prefix(PREFIX) {
375 Some(rest) if !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()) => Ok(()),
376 _ => Err(format!("wip_ref must match ^refs/agent-wip/[0-9]+$, got {wip_ref:?}")),
377 }
378}
379
380/// Resume a parked task: restore the slot checkout from a `refs/agent-wip/N`
381/// ref previously imported into the mirror by agentd.
382///
383/// Sequence (mirrors the `ResumeSpec` contract): ensure the slot repo exists
384/// (`clone --shared` as in fresh prepare if not), tear down leftover state
385/// (`reset --hard HEAD`, `clean -fd`), then with a `wip_ref` fetch it via an
386/// explicit refspec (`fetch origin +<wip_ref>:<wip_ref>` — a plain
387/// `fetch origin` never fetches this namespace) and `checkout -B <branch>
388/// <wip_sha>` after verifying the fetched ref resolves to `wip_sha`, else
389/// `fetch origin` and `checkout -B <branch> <base_sha>`; then
390/// `reset --soft <base_sha>` so the parked work reappears as uncommitted
391/// changes, record `base_sha` in `.git/agent-base`, and set user.name/email
392/// as in fresh prepare. Deliberately no `clean` afterwards: it would delete
393/// the just-restored untracked files.
394async fn prepare_slot_resume(
395 state: &Arc<AppState>,
396 slot: u32,
397 branch: &str,
398 spec: &ResumeSpec,
399) -> Result<String, ApiError> {
400 // Validate everything before touching the slot.
401 if !is_hex_sha(&spec.base_sha) {
402 return Err(ApiError::bad_request(format!(
403 "base_sha must be a 40-char hex sha, got {:?}",
404 spec.base_sha
405 )));
406 }
407 let (wip_ref, wip_sha): (Option<&str>, Option<&str>) = match (&spec.wip_ref, &spec.wip_sha) {
408 (Some(r), Some(s)) => {
409 validate_wip_ref(r).map_err(ApiError::bad_request)?;
410 if !is_hex_sha(s) {
411 return Err(ApiError::bad_request(format!(
412 "wip_sha must be a 40-char hex sha, got {s:?}"
413 )));
414 }
415 (Some(r.as_str()), Some(s.as_str()))
416 }
417 (Some(_), None) => {
418 return Err(ApiError::bad_request("wip_ref is set but wip_sha is missing".to_string()));
419 }
420 (None, Some(_)) => {
421 return Err(ApiError::bad_request("wip_sha is set but wip_ref is missing".to_string()));
422 }
423 (None, None) => (None, None),
424 };
425 let base_sha = spec.base_sha.as_str();
426
427 let slot_path = slot_root(state, slot);
428 let is_repo = slot_path.join(".git").is_dir();
429 if !is_repo {
430 if slot_path.exists() {
431 if slot_path.is_dir() {
432 std::fs::remove_dir_all(&slot_path).map_err(|e| {
433 ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))
434 })?;
435 } else {
436 std::fs::remove_file(&slot_path).map_err(|e| {
437 ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))
438 })?;
439 }
440 }
441 if let Some(parent) = slot_path.parent() {
442 std::fs::create_dir_all(parent)
443 .map_err(|e| ApiError::internal(format!("failed to create slots dir: {e}")))?;
444 }
445 let out = run_git(
446 &state.mirror,
447 None,
448 &[
449 "clone",
450 "--shared",
451 &state.mirror.display().to_string(),
452 &slot_path.display().to_string(),
453 ],
454 )
455 .await?;
456 check_git_output(&out, "git clone")?;
457 } else {
458 // Tear down leftover state first so the checkout below cannot fail on
459 // untracked files shadowing the restored work.
460 let out = run_git(&state.mirror, Some(&slot_path), &["reset", "--hard", "HEAD"]).await?;
461 check_git_output(&out, "git reset")?;
462 let out = run_git(&state.mirror, Some(&slot_path), &["clean", "-fd"]).await?;
463 check_git_output(&out, "git clean")?;
464 }
465
466 if let (Some(wip_ref), Some(wip_sha)) = (wip_ref, wip_sha) {
467 // Explicit refspec: plain `fetch origin` does not fetch the
468 // `refs/agent-wip/` namespace.
469 let refspec = format!("+{wip_ref}:{wip_ref}");
470 let out = run_git(&state.mirror, Some(&slot_path), &["fetch", "origin", refspec.as_str()])
471 .await?;
472 if !out.status.success() {
473 return Err(ApiError::conflict(format!(
474 "failed to fetch {wip_ref} from the mirror: {}",
475 String::from_utf8_lossy(&out.stderr).trim()
476 )));
477 }
478 let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", wip_ref]).await?;
479 if !out.status.success() {
480 return Err(ApiError::conflict(format!(
481 "fetched {wip_ref} but cannot resolve it: {}",
482 String::from_utf8_lossy(&out.stderr).trim()
483 )));
484 }
485 let resolved = String::from_utf8_lossy(&out.stdout).trim().to_string();
486 if resolved != wip_sha {
487 return Err(ApiError::conflict(format!(
488 "wip ref {wip_ref} resolved to {resolved}, expected wip_sha {wip_sha}; \
489 refusing to resume"
490 )));
491 }
492 let out =
493 run_git(&state.mirror, Some(&slot_path), &["checkout", "-B", branch, wip_sha]).await?;
494 check_git_output(&out, "git checkout")?;
495 } else {
496 let out = run_git(&state.mirror, Some(&slot_path), &["fetch", "origin"]).await?;
497 check_git_output(&out, "git fetch")?;
498 let verify_arg = format!("{base_sha}^{{commit}}");
499 let out = run_git(
500 &state.mirror,
501 Some(&slot_path),
502 &["rev-parse", "--verify", verify_arg.as_str()],
503 )
504 .await?;
505 if !out.status.success() {
506 return Err(ApiError::conflict(format!(
507 "base_sha {base_sha} not found in the mirror; cannot resume"
508 )));
509 }
510 let out =
511 run_git(&state.mirror, Some(&slot_path), &["checkout", "-B", branch, base_sha]).await?;
512 check_git_output(&out, "git checkout")?;
513 }
514
515 // Soft reset onto the base: the branch pointer moves back to base_sha
516 // while index and worktree keep the parked work, so it reappears as
517 // uncommitted changes. No `clean` afterwards — it would delete the
518 // restored untracked files.
519 let out = run_git(&state.mirror, Some(&slot_path), &["reset", "--soft", base_sha]).await?;
520 if !out.status.success() {
521 return Err(ApiError::conflict(format!(
522 "cannot reset onto base_sha {base_sha}: {}",
523 String::from_utf8_lossy(&out.stderr).trim()
524 )));
525 }
526 let out =
527 run_git(&state.mirror, Some(&slot_path), &["config", "user.name", "maproj agent"]).await?;
528 check_git_output(&out, "git config user.name")?;
529 let out =
530 run_git(&state.mirror, Some(&slot_path), &["config", "user.email", "[email protected]"])
531 .await?;
532 check_git_output(&out, "git config user.email")?;
533 std::fs::write(slot_path.join(".git").join(AGENT_BASE_FILE), format!("{base_sha}\n"))
534 .map_err(|e| ApiError::internal(format!("failed to record base sha: {e}")))?;
535 Ok(base_sha.to_string())
536}
537
538/// (Re)create the slot checkout on a fresh branch from the mirror's main.
539///
540/// When `resume` is set, restore a parked task instead (see
541/// [`prepare_slot_resume`]).
542pub async fn prepare_slot(
543 state: &Arc<AppState>,
544 slot: u32,
545 branch: &str,
546 resume: Option<&ResumeSpec>,
547) -> Result<String, ApiError> {
548 validate_branch(branch).map_err(ApiError::bad_request)?;
549 if let Some(spec) = resume {
550 return prepare_slot_resume(state, slot, branch, spec).await;
551 }
552 let slot_path = slot_root(state, slot);
553 let is_repo = slot_path.join(".git").is_dir();
554 if !is_repo {
555 if slot_path.exists() {
556 if slot_path.is_dir() {
557 std::fs::remove_dir_all(&slot_path).map_err(|e| {
558 ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))
559 })?;
560 } else {
561 std::fs::remove_file(&slot_path).map_err(|e| {
562 ApiError::internal(format!("failed to clear {slot_path:?}: {e}"))
563 })?;
564 }
565 }
566 if let Some(parent) = slot_path.parent() {
567 std::fs::create_dir_all(parent)
568 .map_err(|e| ApiError::internal(format!("failed to create slots dir: {e}")))?;
569 }
570 let out = run_git(
571 &state.mirror,
572 None,
573 &[
574 "clone",
575 "--shared",
576 &state.mirror.display().to_string(),
577 &slot_path.display().to_string(),
578 ],
579 )
580 .await?;
581 check_git_output(&out, "git clone")?;
582 } else {
583 // Tear down leftover state first so the checkout below cannot fail on
584 // untracked files shadowing the target branch.
585 let out = run_git(&state.mirror, Some(&slot_path), &["reset", "--hard", "HEAD"]).await?;
586 check_git_output(&out, "git reset")?;
587 let out = run_git(&state.mirror, Some(&slot_path), &["clean", "-fd"]).await?;
588 check_git_output(&out, "git clean")?;
589 }
590 let out = run_git(&state.mirror, Some(&slot_path), &["fetch", "origin"]).await?;
591 check_git_output(&out, "git fetch")?;
592 let out = run_git(
593 &state.mirror,
594 Some(&slot_path),
595 &["rev-parse", "--verify", "origin/main"],
596 )
597 .await?;
598 if !out.status.success() {
599 return Err(ApiError::internal(
600 "mirror has no origin/main; cannot prepare slot".to_string(),
601 ));
602 }
603 let out = run_git(
604 &state.mirror,
605 Some(&slot_path),
606 &["checkout", "-B", branch, "origin/main"],
607 )
608 .await?;
609 check_git_output(&out, "git checkout")?;
610 let out = run_git(
611 &state.mirror,
612 Some(&slot_path),
613 &["reset", "--hard", "origin/main"],
614 )
615 .await?;
616 check_git_output(&out, "git reset")?;
617 // `clean -fd` without `-x`: drop untracked work but keep ignored
618 // build outputs (build/, target/, .gradle/) warm.
619 let out = run_git(&state.mirror, Some(&slot_path), &["clean", "-fd"]).await?;
620 check_git_output(&out, "git clean")?;
621 let out = run_git(
622 &state.mirror,
623 Some(&slot_path),
624 &["config", "user.name", "maproj agent"],
625 )
626 .await?;
627 check_git_output(&out, "git config user.name")?;
628 let out = run_git(
629 &state.mirror,
630 Some(&slot_path),
631 &["config", "user.email", "[email protected]"],
632 )
633 .await?;
634 check_git_output(&out, "git config user.email")?;
635 let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;
636 let base_sha = check_git_output(&out, "git rev-parse")?;
637 std::fs::write(
638 slot_path.join(".git").join(AGENT_BASE_FILE),
639 format!("{base_sha}\n"),
640 )
641 .map_err(|e| ApiError::internal(format!("failed to record base sha: {e}")))?;
642 Ok(base_sha)
643}
644
645fn kill_process_group(pgid: i32) {
646 // ESRCH (no such group) just means nothing was running.
647 unsafe {
648 libc::killpg(pgid, libc::SIGKILL);
649 }
650}
651
652/// Run `bash -lc <command>` in the slot root, in its own process group.
653pub async fn exec_in_slot(
654 state: &Arc<AppState>,
655 slot: u32,
656 req: &ExecRequest,
657) -> Result<ExecResponse, ApiError> {
658 let slot_path = slot_root(state, slot);
659 if !slot_path.is_dir() {
660 return Err(ApiError::not_found(
661 "slot is not prepared; run prepare first".to_string(),
662 ));
663 }
664 let mut queued_ms = 0u64;
665
666 // Build commands serialize behind the single build permit.
667 let _permit = match req.kind {
668 ExecKind::Build => {
669 let wait_start = Instant::now();
670 let permit = state
671 .build_sem
672 .clone()
673 .acquire_owned()
674 .await
675 .map_err(|e| ApiError::internal(format!("build semaphore closed: {e}")))?;
676 queued_ms = wait_start
677 .elapsed()
678 .as_millis()
679 .min(u128::from(u64::MAX)) as u64;
680 state.build_running.store(true, Ordering::SeqCst);
681 *state.build_slot.lock().await = Some(slot);
682 Some(permit)
683 }
684 ExecKind::Shell => None,
685 };
686
687 let result = run_command(state, slot, &slot_path, req).await;
688
689 if _permit.is_some() {
690 state.build_running.store(false, Ordering::SeqCst);
691 *state.build_slot.lock().await = None;
692 drop(_permit);
693 }
694
695 let mut resp = result?;
696 resp.queued_ms = queued_ms;
697 Ok(resp)
698}
699
700/// Drain an async reader, bounded by a deadline; returns bytes + whether the
701/// deadline cut the drain short (a backgrounded grandchild can hold pipes).
702async fn drain_bounded<R>(mut reader: R, deadline: Instant) -> (Vec<u8>, bool)
703where
704 R: tokio::io::AsyncRead + Unpin,
705{
706 let mut buf = Vec::new();
707 let mut chunk = [0u8; 8192];
708 loop {
709 let now = Instant::now();
710 if now >= deadline {
711 return (buf, true);
712 }
713 tokio::select! {
714 res = tokio::io::AsyncReadExt::read(&mut reader, &mut chunk) => {
715 match res {
716 Ok(0) => return (buf, false),
717 Ok(n) => buf.extend_from_slice(&chunk[..n]),
718 Err(_) => return (buf, true),
719 }
720 }
721 _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
722 return (buf, true);
723 }
724 }
725 }
726}
727
728async fn run_command(
729 state: &Arc<AppState>,
730 slot: u32,
731 slot_path: &Path,
732 req: &ExecRequest,
733) -> Result<ExecResponse, ApiError> {
734 let started = Instant::now();
735 let use_nice = req.kind == ExecKind::Shell && Path::new("/usr/bin/nice").exists();
736 let mut std_cmd = std::process::Command::new(if use_nice { "/usr/bin/nice" } else { "bash" });
737 if use_nice {
738 std_cmd.arg("-n").arg("10").arg("bash");
739 }
740 std_cmd
741 .arg("-lc")
742 .arg(&req.command)
743 .current_dir(slot_path)
744 .stdin(Stdio::null())
745 .stdout(Stdio::piped())
746 .stderr(Stdio::piped())
747 .process_group(0);
748
749 let mut child = tokio::process::Command::from(std_cmd)
750 .kill_on_drop(true)
751 .spawn()
752 .map_err(|e| ApiError::internal(format!("failed to spawn command: {e}")))?;
753 // With `process_group(0)` the child is its own group leader, so its pid
754 // doubles as the pgid we signal for timeout/cancel.
755 let pgid = child.id().map(|id| id as i32).ok_or_else(|| {
756 ApiError::internal("spawned command has no pid".to_string())
757 })?;
758 let killed_flag = Arc::new(AtomicBool::new(false));
759 {
760 let mut running = state.running.lock().await;
761 running.insert(
762 slot,
763 RunningEntry {
764 pgid,
765 killed: killed_flag.clone(),
766 is_build: req.kind == ExecKind::Build,
767 },
768 );
769 }
770
771 let stdout = child.stdout.take().ok_or_else(|| {
772 ApiError::internal("spawned command has no stdout pipe".to_string())
773 })?;
774 let stderr = child.stderr.take().ok_or_else(|| {
775 ApiError::internal("spawned command has no stderr pipe".to_string())
776 })?;
777 // Drain concurrently: a child writing more than the pipe buffer must not
778 // block forever while we wait for its exit.
779 let drain_deadline = Instant::now()
780 + Duration::from_secs(req.timeout_secs)
781 + STDIO_DRAIN_GRACE;
782 let out_task = tokio::spawn(drain_bounded(stdout, drain_deadline));
783 let err_task = tokio::spawn(drain_bounded(stderr, drain_deadline));
784
785 // Wait for exit or timeout; on timeout SIGKILL the whole process group
786 // (daemons that double-fork out of the group are handled separately for
787 // builds via `./gradlew --stop` below).
788 let mut timed_out = false;
789 let wait_status = tokio::select! {
790 status = child.wait() => status.map_err(|e| {
791 ApiError::internal(format!("failed to wait for command: {e}"))
792 })?,
793 _ = tokio::time::sleep(Duration::from_secs(req.timeout_secs)) => {
794 timed_out = true;
795 kill_process_group(pgid);
796 child.wait().await.map_err(|e| {
797 ApiError::internal(format!("failed to reap timed-out command: {e}"))
798 })?
799 }
800 };
801 let (out_buf, out_cut) = out_task.await.unwrap_or_default();
802 let (err_buf, err_cut) = err_task.await.unwrap_or_default();
803
804 let was_killed = killed_flag.load(Ordering::SeqCst);
805 {
806 let mut running = state.running.lock().await;
807 running.remove(&slot);
808 }
809
810 let exit_code = if timed_out || was_killed {
811 None
812 } else {
813 wait_status.code()
814 };
815 let (stdout_str, stdout_trunc) = truncate_bytes(&out_buf, OUTPUT_CAP_BYTES);
816 let (stderr_str, stderr_trunc) = truncate_bytes(&err_buf, OUTPUT_CAP_BYTES);
817
818 // Gradle/Kotlin daemons detach from the process group, so killpg alone
819 // does not free their RAM. Ask Gradle to stop them after a killed build.
820 if req.kind == ExecKind::Build && (timed_out || was_killed) {
821 gradle_stop(slot_path).await;
822 }
823
824 Ok(ExecResponse {
825 exit_code,
826 stdout: stdout_str,
827 stderr: stderr_str,
828 truncated: stdout_trunc || stderr_trunc || out_cut || err_cut,
829 timed_out,
830 killed: was_killed && !timed_out,
831 queued_ms: 0,
832 duration_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
833 })
834}
835
836async fn gradle_stop(slot_path: &Path) {
837 if !slot_path.join("gradlew").exists() {
838 return;
839 }
840 let mut cmd = tokio::process::Command::new("bash");
841 cmd.arg("-lc")
842 .arg("./gradlew --stop")
843 .current_dir(slot_path)
844 .stdin(Stdio::null())
845 .stdout(Stdio::null())
846 .stderr(Stdio::null())
847 .kill_on_drop(true);
848 if let Ok(mut child) = cmd.spawn() {
849 let _ = tokio::time::timeout(GRADLE_STOP_TIMEOUT, child.wait()).await;
850 }
851}
852
853pub async fn cancel_slot(state: &Arc<AppState>, slot: u32) -> bool {
854 let running = state.running.lock().await;
855 match running.get(&slot) {
856 Some(entry) => {
857 entry.killed.store(true, Ordering::SeqCst);
858 kill_process_group(entry.pgid);
859 true
860 }
861 None => false,
862 }
863}
864
865pub async fn kill_build(state: &Arc<AppState>) -> bool {
866 let slot = { *state.build_slot.lock().await };
867 match slot {
868 Some(slot) => {
869 let running = state.running.lock().await;
870 match running.get(&slot) {
871 Some(entry) if entry.is_build => {
872 entry.killed.store(true, Ordering::SeqCst);
873 kill_process_group(entry.pgid);
874 true
875 }
876 _ => false,
877 }
878 }
879 None => false,
880 }
881}
882
883pub async fn read_slot_file(
884 state: &Arc<AppState>,
885 slot: u32,
886 req: &ReadRequest,
887) -> Result<ReadResponse, ApiError> {
888 let root = slot_root(state, slot);
889 let path = resolve_in_slot(&root, &req.path).map_err(ApiError::not_found)?;
890 if path.is_dir() {
891 return Err(ApiError::bad_request(format!(
892 "{:?} is a directory",
893 req.path
894 )));
895 }
896 let content = std::fs::read(&path)
897 .map_err(|e| ApiError::not_found(format!("cannot read {:?}: {e}", req.path)))?;
898 let text = String::from_utf8_lossy(&content).into_owned();
899 let lines: Vec<&str> = text.lines().collect();
900 let total_lines = lines.len();
901 let start = req.start_line.unwrap_or(1).max(1);
902 let max_lines = req
903 .max_lines
904 .unwrap_or(READ_DEFAULT_MAX_LINES)
905 .min(READ_HARD_MAX_LINES);
906 let selected: Vec<&str> = if start > lines.len() {
907 Vec::new()
908 } else {
909 lines[(start - 1)..].iter().take(max_lines).copied().collect()
910 };
911 let truncated = lines.len() > (start - 1) + selected.len();
912 Ok(ReadResponse {
913 content: selected.join("\n"),
914 total_lines,
915 truncated,
916 })
917}
918
919pub async fn write_slot_file(
920 state: &Arc<AppState>,
921 slot: u32,
922 req: &WriteRequest,
923) -> Result<(), ApiError> {
924 let root = slot_root(state, slot);
925 let path = resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?;
926 if path.is_dir() {
927 return Err(ApiError::bad_request(format!(
928 "{:?} is a directory",
929 req.path
930 )));
931 }
932 if let Some(parent) = path.parent() {
933 std::fs::create_dir_all(parent)
934 .map_err(|e| ApiError::internal(format!("cannot create parent dirs: {e}")))?;
935 }
936 std::fs::write(&path, &req.content)
937 .map_err(|e| ApiError::internal(format!("cannot write {:?}: {e}", req.path)))?;
938 Ok(())
939}
940
941pub async fn edit_slot_file(
942 state: &Arc<AppState>,
943 slot: u32,
944 req: &EditRequest,
945) -> Result<(), ApiError> {
946 let root = slot_root(state, slot);
947 let path = resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?;
948 let content = std::fs::read_to_string(&path)
949 .map_err(|e| ApiError::not_found(format!("cannot read {:?}: {e}", req.path)))?;
950 let updated = apply_edit(&content, &req.old, &req.new).map_err(ApiError::conflict)?;
951 std::fs::write(&path, updated)
952 .map_err(|e| ApiError::internal(format!("cannot write {:?}: {e}", req.path)))?;
953 Ok(())
954}
955
956pub async fn list_slot_dir(
957 state: &Arc<AppState>,
958 slot: u32,
959 req: &ListRequest,
960) -> Result<ListResponse, ApiError> {
961 let root = slot_root(state, slot);
962 let dir: PathBuf = if req.path.is_empty() || req.path == "." {
963 root.clone()
964 } else {
965 resolve_in_slot(&root, &req.path).map_err(ApiError::bad_request)?
966 };
967 let read_dir =
968 std::fs::read_dir(&dir).map_err(|e| ApiError::not_found(format!("cannot list: {e}")))?;
969 let mut entries: Vec<String> = Vec::new();
970 for entry in read_dir {
971 let entry = entry.map_err(|e| ApiError::internal(format!("cannot list: {e}")))?;
972 let name = entry.file_name().to_string_lossy().into_owned();
973 let file_type = entry
974 .file_type()
975 .map_err(|e| ApiError::internal(format!("cannot stat entry: {e}")))?;
976 if file_type.is_dir() {
977 entries.push(format!("{name}/"));
978 } else {
979 entries.push(name);
980 }
981 if entries.len() >= LIST_MAX_ENTRIES {
982 break;
983 }
984 }
985 entries.sort();
986 // `truncated` is approximate: we stopped early at the cap.
987 let truncated = entries.len() >= LIST_MAX_ENTRIES;
988 Ok(ListResponse { entries, truncated })
989}
990
991const SEARCH_EXCLUDES: &[&str] = &[
992 "!build/",
993 "!target/",
994 "!.gradle/",
995 "!.kotlin/",
996 "!metadata_data/photos/",
997 "!third_party/",
998 "!*.onnx",
999 "!*.log",
1000];
1001
1002pub async fn search_slot(
1003 state: &Arc<AppState>,
1004 slot: u32,
1005 req: &SearchRequest,
1006) -> Result<SearchResponse, ApiError> {
1007 let root = slot_root(state, slot);
1008 let cwd: PathBuf = match &req.path {
1009 Some(p) if !p.is_empty() && *p != "." => {
1010 resolve_in_slot(&root, p).map_err(ApiError::bad_request)?
1011 }
1012 _ => root.clone(),
1013 };
1014 if !cwd.exists() {
1015 return Err(ApiError::not_found(
1016 "search path does not exist".to_string(),
1017 ));
1018 }
1019 let mut cmd = tokio::process::Command::new("rg");
1020 cmd.arg("--line-number")
1021 .arg("--no-heading")
1022 .arg("--max-columns")
1023 .arg("300");
1024 if req.fixed_string {
1025 cmd.arg("--fixed-strings");
1026 }
1027 if let Some(glob) = &req.glob {
1028 cmd.arg("--glob").arg(glob);
1029 }
1030 for excl in SEARCH_EXCLUDES {
1031 cmd.arg("--glob").arg(excl);
1032 }
1033 cmd.arg("--").arg(&req.pattern);
1034 if cwd != root {
1035 let rel = cwd
1036 .strip_prefix(&root)
1037 .map_err(|e| ApiError::internal(format!("search path escaped slot root: {e}")))?;
1038 cmd.arg(rel);
1039 }
1040 cmd.current_dir(&root)
1041 .stdin(Stdio::null())
1042 .stdout(Stdio::piped())
1043 .stderr(Stdio::piped())
1044 .kill_on_drop(true);
1045 let child = cmd.spawn().map_err(|e| {
1046 ApiError::internal(format!("failed to spawn rg (is ripgrep installed?): {e}"))
1047 })?;
1048 let rg_pid = child.id();
1049 let out = match tokio::time::timeout(SEARCH_TIMEOUT, child.wait_with_output()).await {
1050 Ok(Ok(out)) => out,
1051 Ok(Err(e)) => return Err(ApiError::internal(format!("failed to wait for rg: {e}"))),
1052 Err(_) => {
1053 // wait_with_output consumed the Child; kill by pid (leaf process).
1054 if let Some(pid) = rg_pid {
1055 unsafe {
1056 libc::kill(pid as i32, libc::SIGKILL);
1057 }
1058 }
1059 return Err(ApiError::internal("rg search timed out".to_string()));
1060 }
1061 };
1062 match out.status.code() {
1063 // 0 = matches, 1 = no matches.
1064 Some(0) | Some(1) => {}
1065 // The include glob filtered out every file: not a failure, just no
1066 // matches. (Other exit-2 causes, e.g. a bad regex, still 500 below.)
1067 Some(2)
1068 if String::from_utf8_lossy(&out.stderr).contains("No files were searched") =>
1069 {
1070 return Ok(SearchResponse {
1071 matches: String::new(),
1072 truncated: false,
1073 });
1074 }
1075 other => {
1076 return Err(ApiError::internal(format!(
1077 "rg failed (exit {other:?}): {}",
1078 String::from_utf8_lossy(&out.stderr).trim()
1079 )));
1080 }
1081 }
1082 let (matches, truncated) = truncate_bytes(&out.stdout, OUTPUT_CAP_BYTES);
1083 Ok(SearchResponse { matches, truncated })
1084}
1085
1086pub async fn diff_slot(state: &Arc<AppState>, slot: u32) -> Result<DiffResponse, ApiError> {
1087 let slot_path = slot_root(state, slot);
1088 if !slot_path.join(".git").is_dir() {
1089 return Err(ApiError::not_found(
1090 "slot is not prepared; run prepare first".to_string(),
1091 ));
1092 }
1093 let base_sha = read_base_sha(&slot_path)?;
1094 let out = run_git(&state.mirror, Some(&slot_path), &["add", "-A"]).await?;
1095 check_git_output(&out, "git add")?;
1096 let out = run_git(
1097 &state.mirror,
1098 Some(&slot_path),
1099 &["diff", "--no-color", "--stat", &base_sha, "--"],
1100 )
1101 .await?;
1102 let stat_raw = check_git_output(&out, "git diff --stat")?;
1103 let out = run_git(
1104 &state.mirror,
1105 Some(&slot_path),
1106 &["diff", "--no-color", &base_sha, "--"],
1107 )
1108 .await?;
1109 let diff_raw = check_git_output(&out, "git diff")?;
1110 let (stat, stat_trunc) = truncate_bytes(stat_raw.as_bytes(), DIFF_STAT_CAP_BYTES);
1111 let (diff, diff_trunc) = truncate_bytes(diff_raw.as_bytes(), DIFF_CAP_BYTES);
1112 Ok(DiffResponse {
1113 stat,
1114 diff,
1115 truncated: stat_trunc || diff_trunc,
1116 })
1117}
1118
1119pub async fn commit_slot(
1120 state: &Arc<AppState>,
1121 slot: u32,
1122 req: &CommitRequest,
1123) -> Result<String, ApiError> {
1124 let slot_path = slot_root(state, slot);
1125 if !slot_path.join(".git").is_dir() {
1126 return Err(ApiError::not_found(
1127 "slot is not prepared; run prepare first".to_string(),
1128 ));
1129 }
1130 let out = run_git(&state.mirror, Some(&slot_path), &["add", "-A"]).await?;
1131 check_git_output(&out, "git add")?;
1132 let out = run_git(
1133 &state.mirror,
1134 Some(&slot_path),
1135 &["status", "--porcelain"],
1136 )
1137 .await?;
1138 let status = check_git_output(&out, "git status")?;
1139 if status.is_empty() {
1140 return Err(ApiError::conflict("nothing to commit".to_string()));
1141 }
1142 let out = run_git(
1143 &state.mirror,
1144 Some(&slot_path),
1145 &["commit", "-m", &req.message],
1146 )
1147 .await?;
1148 check_git_output(&out, "git commit")?;
1149 let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;
1150 check_git_output(&out, "git rev-parse")
1151}
1152
1153pub async fn bundle_slot(state: &Arc<AppState>, slot: u32) -> Result<(String, Vec<u8>), ApiError> {
1154 let slot_path = slot_root(state, slot);
1155 if !slot_path.join(".git").is_dir() {
1156 return Err(ApiError::not_found(
1157 "slot is not prepared; run prepare first".to_string(),
1158 ));
1159 }
1160 let base_sha = read_base_sha(&slot_path)?;
1161 let out = run_git(
1162 &state.mirror,
1163 Some(&slot_path),
1164 &["branch", "--show-current"],
1165 )
1166 .await?;
1167 let branch = check_git_output(&out, "git branch --show-current")?;
1168 if branch.is_empty() {
1169 return Err(ApiError::conflict(
1170 "slot is not on a branch; run prepare first".to_string(),
1171 ));
1172 }
1173 let out = run_git(&state.mirror, Some(&slot_path), &["rev-parse", "HEAD"]).await?;
1174 let head = check_git_output(&out, "git rev-parse")?;
1175 if head == base_sha {
1176 return Err(ApiError::conflict(
1177 "no commits on the branch; nothing to bundle".to_string(),
1178 ));
1179 }
1180 let range = format!("{base_sha}..{branch}");
1181 let out = run_git(
1182 &state.mirror,
1183 Some(&slot_path),
1184 &["bundle", "create", "-", &range],
1185 )
1186 .await?;
1187 if !out.status.success() {
1188 return Err(ApiError::conflict(format!(
1189 "git bundle failed: {}",
1190 String::from_utf8_lossy(&out.stderr).trim()
1191 )));
1192 }
1193 Ok((branch, out.stdout))
1194}
1195
1196// ---------------------------------------------------------------------------
1197// HTTP layer
1198// ---------------------------------------------------------------------------
1199
1200fn parse_json<T: serde::de::DeserializeOwned>(body: &Bytes) -> Result<T, ApiError> {
1201 serde_json::from_slice(body)
1202 .map_err(|e| ApiError::bad_request(format!("invalid JSON body: {e}")))
1203}
1204
1205async fn h_prepare(
1206 State(state): State<Arc<AppState>>,
1207 AxumPath(slot_raw): AxumPath<String>,
1208 body: Bytes,
1209) -> Result<Json<PrepareResponse>, ErrTuple> {
1210 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1211 let req: PrepareRequest = parse_json(&body).map_err(to_err_tuple)?;
1212 let base_sha = prepare_slot(&state, slot, &req.branch, req.resume.as_ref())
1213 .await
1214 .map_err(to_err_tuple)?;
1215 Ok(Json(PrepareResponse { base_sha }))
1216}
1217
1218async fn h_exec(
1219 State(state): State<Arc<AppState>>,
1220 AxumPath(slot_raw): AxumPath<String>,
1221 body: Bytes,
1222) -> Result<Json<ExecResponse>, ErrTuple> {
1223 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1224 let req: ExecRequest = parse_json(&body).map_err(to_err_tuple)?;
1225 let resp = exec_in_slot(&state, slot, &req).await.map_err(to_err_tuple)?;
1226 Ok(Json(resp))
1227}
1228
1229async fn h_read(
1230 State(state): State<Arc<AppState>>,
1231 AxumPath(slot_raw): AxumPath<String>,
1232 body: Bytes,
1233) -> Result<Json<ReadResponse>, ErrTuple> {
1234 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1235 let req: ReadRequest = parse_json(&body).map_err(to_err_tuple)?;
1236 let resp = read_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;
1237 Ok(Json(resp))
1238}
1239
1240async fn h_write(
1241 State(state): State<Arc<AppState>>,
1242 AxumPath(slot_raw): AxumPath<String>,
1243 body: Bytes,
1244) -> Result<Json<serde_json::Value>, ErrTuple> {
1245 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1246 let req: WriteRequest = parse_json(&body).map_err(to_err_tuple)?;
1247 write_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;
1248 Ok(Json(serde_json::json!({})))
1249}
1250
1251async fn h_edit(
1252 State(state): State<Arc<AppState>>,
1253 AxumPath(slot_raw): AxumPath<String>,
1254 body: Bytes,
1255) -> Result<Json<serde_json::Value>, ErrTuple> {
1256 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1257 let req: EditRequest = parse_json(&body).map_err(to_err_tuple)?;
1258 edit_slot_file(&state, slot, &req).await.map_err(to_err_tuple)?;
1259 Ok(Json(serde_json::json!({})))
1260}
1261
1262async fn h_list(
1263 State(state): State<Arc<AppState>>,
1264 AxumPath(slot_raw): AxumPath<String>,
1265 body: Bytes,
1266) -> Result<Json<ListResponse>, ErrTuple> {
1267 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1268 let req: ListRequest = parse_json(&body).map_err(to_err_tuple)?;
1269 let resp = list_slot_dir(&state, slot, &req).await.map_err(to_err_tuple)?;
1270 Ok(Json(resp))
1271}
1272
1273async fn h_search(
1274 State(state): State<Arc<AppState>>,
1275 AxumPath(slot_raw): AxumPath<String>,
1276 body: Bytes,
1277) -> Result<Json<SearchResponse>, ErrTuple> {
1278 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1279 let req: SearchRequest = parse_json(&body).map_err(to_err_tuple)?;
1280 let resp = search_slot(&state, slot, &req).await.map_err(to_err_tuple)?;
1281 Ok(Json(resp))
1282}
1283
1284async fn h_diff(
1285 State(state): State<Arc<AppState>>,
1286 AxumPath(slot_raw): AxumPath<String>,
1287) -> Result<Json<DiffResponse>, ErrTuple> {
1288 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1289 let resp = diff_slot(&state, slot).await.map_err(to_err_tuple)?;
1290 Ok(Json(resp))
1291}
1292
1293async fn h_commit(
1294 State(state): State<Arc<AppState>>,
1295 AxumPath(slot_raw): AxumPath<String>,
1296 body: Bytes,
1297) -> Result<Json<CommitResponse>, ErrTuple> {
1298 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1299 let req: CommitRequest = parse_json(&body).map_err(to_err_tuple)?;
1300 let sha = commit_slot(&state, slot, &req).await.map_err(to_err_tuple)?;
1301 Ok(Json(CommitResponse { sha }))
1302}
1303
1304async fn h_bundle(
1305 State(state): State<Arc<AppState>>,
1306 AxumPath(slot_raw): AxumPath<String>,
1307) -> Result<impl IntoResponse, ErrTuple> {
1308 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1309 let (_branch, bytes) = bundle_slot(&state, slot).await.map_err(to_err_tuple)?;
1310 Ok((
1311 StatusCode::OK,
1312 [(header::CONTENT_TYPE, "application/octet-stream")],
1313 bytes,
1314 ))
1315}
1316
1317async fn h_cancel(
1318 State(state): State<Arc<AppState>>,
1319 AxumPath(slot_raw): AxumPath<String>,
1320) -> Result<Json<KillResponse>, ErrTuple> {
1321 let slot = parse_slot(&state, &slot_raw).map_err(to_err_tuple)?;
1322 let killed = cancel_slot(&state, slot).await;
1323 Ok(Json(KillResponse { killed }))
1324}
1325
1326async fn h_builds_kill(State(state): State<Arc<AppState>>) -> Json<KillResponse> {
1327 let killed = kill_build(&state).await;
1328 Json(KillResponse { killed })
1329}
1330
1331async fn h_health(State(state): State<Arc<AppState>>) -> Json<HealthResponse> {
1332 Json(HealthResponse {
1333 slots: state.num_slots,
1334 build_running: state.build_running.load(Ordering::SeqCst),
1335 })
1336}
1337
1338pub fn router(state: Arc<AppState>) -> Router {
1339 Router::new()
1340 .route("/v1/slots/:slot/prepare", post(h_prepare))
1341 .route("/v1/slots/:slot/exec", post(h_exec))
1342 .route("/v1/slots/:slot/read", post(h_read))
1343 .route("/v1/slots/:slot/write", post(h_write))
1344 .route("/v1/slots/:slot/edit", post(h_edit))
1345 .route("/v1/slots/:slot/list", post(h_list))
1346 .route("/v1/slots/:slot/search", post(h_search))
1347 .route("/v1/slots/:slot/diff", post(h_diff))
1348 .route("/v1/slots/:slot/commit", post(h_commit))
1349 .route("/v1/slots/:slot/bundle", get(h_bundle))
1350 .route("/v1/slots/:slot/cancel", post(h_cancel))
1351 .route("/v1/builds/kill", post(h_builds_kill))
1352 .route("/v1/health", get(h_health))
1353 .with_state(state)
1354}
1355
1356pub async fn run() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1357 let state = Arc::new(AppState::from_env());
1358 std::fs::create_dir_all(&state.slots_dir)?;
1359 let addr = AppState::listen_addr();
1360 let listener = tokio::net::TcpListener::bind(&addr).await?;
1361 eprintln!(
1362 "agent-runner: listening on {addr} (slots={} dir={} mirror={})",
1363 state.num_slots,
1364 state.slots_dir.display(),
1365 state.mirror.display()
1366 );
1367 axum::serve(listener, router(state)).await?;
1368 Ok(())
1369}
1370
1371#[cfg(test)]
1372mod tests;