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

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

runner.rs296 lines · 8.8 KiBRaw
1//! Typed client for the runner HTTP API defined in `proto`.
2//!
3//! Every call is slot-scoped (`/v1/slots/{slot}/...`) plus the global
4//! `/v1/builds/kill`. Request paths sent to the runner are validated to be
5//! repo-relative (no `..`, no absolute paths) — defense in depth on top of
6//! the runner's own checks.
7
8use proto::{
9 CommitRequest, CommitResponse, DiffResponse, EditRequest, ExecKind, ExecRequest, ExecResponse,
10 HealthResponse, KillResponse, ListRequest, ListResponse, PrepareRequest, PrepareResponse,
11 ReadRequest, ReadResponse, SearchRequest, SearchResponse, WriteRequest,
12};
13
14#[derive(Clone)]
15pub struct Runner {
16 client: reqwest::Client,
17 base: String,
18}
19
20impl Runner {
21 pub fn new(base: String) -> Runner {
22 Runner {
23 client: reqwest::Client::new(),
24 base: base.trim_end_matches('/').to_string(),
25 }
26 }
27
28 fn url(&self, path: &str) -> String {
29 format!("{}{}", self.base, path)
30 }
31
32 async fn post<B: serde::Serialize, R: serde::de::DeserializeOwned>(
33 &self,
34 path: &str,
35 body: &B,
36 ) -> Result<R, String> {
37 let resp = self
38 .client
39 .post(self.url(path))
40 .json(body)
41 .send()
42 .await
43 .map_err(|e| format!("runner POST {path}: {e}"))?;
44 Self::read_json(path, resp).await
45 }
46
47 async fn post_empty<R: serde::de::DeserializeOwned>(&self, path: &str) -> Result<R, String> {
48 let resp = self
49 .client
50 .post(self.url(path))
51 .header("Content-Length", "0")
52 .send()
53 .await
54 .map_err(|e| format!("runner POST {path}: {e}"))?;
55 Self::read_json(path, resp).await
56 }
57
58 async fn read_json<R: serde::de::DeserializeOwned>(
59 path: &str,
60 resp: reqwest::Response,
61 ) -> Result<R, String> {
62 let status = resp.status();
63 let bytes = resp
64 .bytes()
65 .await
66 .map_err(|e| format!("runner {path} read body: {e}"))?;
67 if !status.is_success() {
68 let msg = serde_json::from_slice::<serde_json::Value>(&bytes)
69 .ok()
70 .and_then(|v| {
71 v.get("error")
72 .and_then(|e| e.as_str())
73 .map(|s| s.to_string())
74 })
75 .unwrap_or_else(|| format!("HTTP {status}"));
76 return Err(format!("runner {path}: {msg}"));
77 }
78 serde_json::from_slice(&bytes).map_err(|e| format!("runner {path} bad JSON: {e}"))
79 }
80
81 pub async fn prepare(&self, slot: u32, branch: &str) -> Result<PrepareResponse, String> {
82 self.post(
83 &format!("/v1/slots/{slot}/prepare"),
84 &PrepareRequest {
85 branch: branch.to_string(),
86 resume: None,
87 },
88 )
89 .await
90 }
91
92 /// Resume a parked task (possibly on a different slot): restore the WIP
93 /// ref's work over `base_sha`, or start clean from `base_sha` when there
94 /// is no parked work.
95 pub async fn prepare_resume(
96 &self,
97 slot: u32,
98 branch: &str,
99 resume: proto::ResumeSpec,
100 ) -> Result<PrepareResponse, String> {
101 self.post(
102 &format!("/v1/slots/{slot}/prepare"),
103 &PrepareRequest {
104 branch: branch.to_string(),
105 resume: Some(resume),
106 },
107 )
108 .await
109 }
110
111 pub async fn read(
112 &self,
113 slot: u32,
114 path: &str,
115 start_line: Option<usize>,
116 max_lines: Option<usize>,
117 ) -> Result<ReadResponse, String> {
118 check_rel_path(path)?;
119 self.post(
120 &format!("/v1/slots/{slot}/read"),
121 &ReadRequest {
122 path: path.to_string(),
123 start_line,
124 max_lines,
125 },
126 )
127 .await
128 }
129
130 pub async fn write(&self, slot: u32, path: &str, content: &str) -> Result<(), String> {
131 check_rel_path(path)?;
132 let v: serde_json::Value = self
133 .post(
134 &format!("/v1/slots/{slot}/write"),
135 &WriteRequest {
136 path: path.to_string(),
137 content: content.to_string(),
138 },
139 )
140 .await?;
141 let _ = v;
142 Ok(())
143 }
144
145 pub async fn edit(&self, slot: u32, path: &str, old: &str, new: &str) -> Result<(), String> {
146 check_rel_path(path)?;
147 let v: serde_json::Value = self
148 .post(
149 &format!("/v1/slots/{slot}/edit"),
150 &EditRequest {
151 path: path.to_string(),
152 old: old.to_string(),
153 new: new.to_string(),
154 },
155 )
156 .await?;
157 let _ = v;
158 Ok(())
159 }
160
161 pub async fn list(&self, slot: u32, path: &str) -> Result<ListResponse, String> {
162 // `list` of the repo root is allowed (single level) — the prompt
163 // tells the model not to; empty path means root.
164 if !path.is_empty() {
165 check_rel_path(path)?;
166 }
167 self.post(
168 &format!("/v1/slots/{slot}/list"),
169 &ListRequest {
170 path: path.to_string(),
171 },
172 )
173 .await
174 }
175
176 pub async fn search(
177 &self,
178 slot: u32,
179 pattern: &str,
180 path: Option<&str>,
181 glob: Option<&str>,
182 fixed_string: bool,
183 ) -> Result<SearchResponse, String> {
184 if let Some(p) = path {
185 if !p.is_empty() {
186 check_rel_path(p)?;
187 }
188 }
189 self.post(
190 &format!("/v1/slots/{slot}/search"),
191 &SearchRequest {
192 pattern: pattern.to_string(),
193 path: path.map(|s| s.to_string()),
194 glob: glob.map(|s| s.to_string()),
195 fixed_string,
196 },
197 )
198 .await
199 }
200
201 pub async fn diff(&self, slot: u32) -> Result<DiffResponse, String> {
202 let resp = self
203 .client
204 .post(self.url(&format!("/v1/slots/{slot}/diff")))
205 .json(&serde_json::json!({}))
206 .send()
207 .await
208 .map_err(|e| format!("runner diff: {e}"))?;
209 Self::read_json(&format!("/v1/slots/{slot}/diff"), resp).await
210 }
211
212 pub async fn exec(
213 &self,
214 slot: u32,
215 command: &str,
216 kind: ExecKind,
217 timeout_secs: u64,
218 ) -> Result<ExecResponse, String> {
219 self.post(
220 &format!("/v1/slots/{slot}/exec"),
221 &ExecRequest {
222 command: command.to_string(),
223 kind,
224 timeout_secs,
225 },
226 )
227 .await
228 }
229
230 pub async fn commit(&self, slot: u32, message: &str) -> Result<CommitResponse, String> {
231 self.post(
232 &format!("/v1/slots/{slot}/commit"),
233 &CommitRequest {
234 message: message.to_string(),
235 },
236 )
237 .await
238 }
239
240 /// Download the slot's git bundle (`application/octet-stream`) to memory.
241 pub async fn bundle(&self, slot: u32) -> Result<Vec<u8>, String> {
242 let resp = self
243 .client
244 .get(self.url(&format!("/v1/slots/{slot}/bundle")))
245 .send()
246 .await
247 .map_err(|e| format!("runner bundle: {e}"))?;
248 let status = resp.status();
249 if !status.is_success() {
250 return Err(format!("runner bundle: HTTP {status}"));
251 }
252 resp.bytes()
253 .await
254 .map(|b| b.to_vec())
255 .map_err(|e| format!("runner bundle read: {e}"))
256 }
257
258 pub async fn cancel_slot(&self, slot: u32) -> Result<bool, String> {
259 let r: KillResponse = self.post_empty(&format!("/v1/slots/{slot}/cancel")).await?;
260 Ok(r.killed)
261 }
262
263 pub async fn kill_build(&self) -> Result<bool, String> {
264 let r: KillResponse = self.post_empty("/v1/builds/kill").await?;
265 Ok(r.killed)
266 }
267
268 /// Readiness probe helper: the runner's build-slot state.
269 /// (`#[allow]` — exercised by the integration test and useful for ops.)
270 #[allow(dead_code)]
271 pub async fn health(&self) -> Result<HealthResponse, String> {
272 let resp = self
273 .client
274 .get(self.url("/v1/health"))
275 .send()
276 .await
277 .map_err(|e| format!("runner health: {e}"))?;
278 Self::read_json("/v1/health", resp).await
279 }
280}
281
282/// Reject absolute paths and `..` escapes before they reach the runner.
283fn check_rel_path(path: &str) -> Result<(), String> {
284 if path.is_empty() {
285 return Err("empty path".to_string());
286 }
287 if path.starts_with('/') {
288 return Err(format!("absolute paths are not allowed: {path:?}"));
289 }
290 for seg in path.split('/') {
291 if seg == ".." {
292 return Err(format!("`..` is not allowed in paths: {path:?}"));
293 }
294 }
295 Ok(())
296}