pr_01m47d15m3e54sn21z27rpy5n9/apps/api/src/rest.rs

317 lines8,932 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

API and MCP server in Rust; a public index at the API root1//! REST: each route maps an HTTP request onto one operation.
2
3use serde_json::{Map, Value};
4
5use crate::operations::Op;
6
7pub struct Route {
8 pub method: &'static str,
9 /// Segments starting with `:` are parameters.
10 pub path: &'static str,
11 pub op: Op,
12 /// Query parameters the route reads, as `(name in the URL, input name)`.
13 pub query: &'static [(&'static str, &'static str)],
14}
15
16const fn route(
17 method: &'static str,
18 path: &'static str,
19 op: Op,
20 query: &'static [(&'static str, &'static str)],
21) -> Route {
22 Route {
23 method,
24 path,
25 op,
26 query,
27 }
28}
29
30pub const ROUTES: &[Route] = &[
Agents as a team: lifecycle, merge queue, billing and a new shell31 route("GET", "/user", Op::Whoami, &[]),
32 route("POST", "/workspaces", Op::CreateWorkspace, &[]),
33 route("GET", "/repos", Op::ListRepos, &[("q", "query")]),
34 route("POST", "/repos", Op::CreateRepo, &[]),
35 route("GET", "/repos/:owner/:name", Op::GetRepo, &[]),
36 route("PATCH", "/repos/:owner/:name", Op::UpdateRepo, &[]),
37 route(
38 "GET",
39 "/repos/:owner/:name/settings",
40 Op::GetRepoSettings,
41 &[],
42 ),
43 route(
44 "PATCH",
45 "/repos/:owner/:name/settings",
46 Op::UpdateRepoSettings,
47 &[],
48 ),
49 route("GET", "/repos/:owner/:name/queue", Op::GetMergeQueue, &[]),
API and MCP server in Rust; a public index at the API root50 route(
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request51 "POST",
52 "/repos/:owner/:name/pulls/:number/messages",
53 Op::MessageAgent,
54 &[],
55 ),
56 route(
57 "POST",
58 "/repos/:owner/:name/pulls/:number/messages/take",
59 Op::TakeMessages,
60 &[],
61 ),
62 route(
API and MCP server in Rust; a public index at the API root63 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell64 "/repos/:owner/:name/events",
API and MCP server in Rust; a public index at the API root65 Op::ListEvents,
66 &[("before", "before")],
67 ),
Agents as a team: lifecycle, merge queue, billing and a new shell68 route("GET", "/repos/:owner/:name/labels", Op::ListLabels, &[]),
API and MCP server in Rust; a public index at the API root69 route(
70 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell71 "/repos/:owner/:name/issues",
API and MCP server in Rust; a public index at the API root72 Op::ListIssues,
73 &[("state", "state"), ("label", "label")],
74 ),
Agents as a team: lifecycle, merge queue, billing and a new shell75 route("POST", "/repos/:owner/:name/issues", Op::CreateIssue, &[]),
API and MCP server in Rust; a public index at the API root76 route(
77 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell78 "/repos/:owner/:name/issues/:number",
API and MCP server in Rust; a public index at the API root79 Op::GetIssue,
80 &[],
81 ),
82 route(
83 "PATCH",
Agents as a team: lifecycle, merge queue, billing and a new shell84 "/repos/:owner/:name/issues/:number",
API and MCP server in Rust; a public index at the API root85 Op::UpdateIssue,
86 &[],
87 ),
88 route(
89 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell90 "/repos/:owner/:name/issues/:number/close",
API and MCP server in Rust; a public index at the API root91 Op::CloseIssue,
92 &[],
93 ),
94 route(
95 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell96 "/repos/:owner/:name/issues/:number/reopen",
API and MCP server in Rust; a public index at the API root97 Op::ReopenIssue,
98 &[],
99 ),
100 route(
101 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell102 "/repos/:owner/:name/issues/:number/assign",
103 Op::AssignIssue,
104 &[],
105 ),
106 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
107 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
108 route(
109 "POST",
110 "/repos/:owner/:name/plans/:plan/apply",
111 Op::ApplyPlan,
112 &[],
113 ),
114 route(
115 "POST",
116 "/repos/:owner/:name/issues/:number/comments",
API and MCP server in Rust; a public index at the API root117 Op::AddComment,
118 &[],
119 ),
120 route(
121 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell122 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root123 Op::ListPullRequests,
124 &[("state", "state")],
125 ),
126 route(
127 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell128 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root129 Op::CreatePullRequest,
130 &[],
131 ),
132 route(
133 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell134 "/repos/:owner/:name/pulls/:number",
API and MCP server in Rust; a public index at the API root135 Op::GetPullRequest,
136 &[],
137 ),
138 route(
139 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell140 "/repos/:owner/:name/pulls/:number/changes",
API and MCP server in Rust; a public index at the API root141 Op::GetPullRequestChanges,
142 &[],
143 ),
144 route(
Acceptance checks in sandboxes, line comments and review verdicts145 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell146 "/repos/:owner/:name/pulls/:number/reviews",
Acceptance checks in sandboxes, line comments and review verdicts147 Op::ReviewPullRequest,
148 &[],
149 ),
150 route(
API and MCP server in Rust; a public index at the API root151 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell152 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root153 Op::ReadSession,
154 &[("after", "after")],
155 ),
156 route(
157 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell158 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root159 Op::RecordSession,
160 &[],
161 ),
162 route(
163 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell164 "/repos/:owner/:name/pulls/:number/ready",
API and MCP server in Rust; a public index at the API root165 Op::MarkPullRequestReady,
166 &[],
167 ),
168 route(
169 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell170 "/repos/:owner/:name/pulls/:number/close",
API and MCP server in Rust; a public index at the API root171 Op::ClosePullRequest,
172 &[],
173 ),
174 route(
175 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell176 "/repos/:owner/:name/pulls/:number/merge",
API and MCP server in Rust; a public index at the API root177 Op::MergePullRequest,
178 &[],
179 ),
180];
181
182impl Route {
183 /// The names of the route's path parameters, in order.
184 pub fn params(&self) -> impl Iterator<Item = &'static str> {
185 self.path
186 .split('/')
187 .filter_map(|segment| segment.strip_prefix(':'))
188 }
189
190 /// The values of the path parameters, if `path` is this route's.
191 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
192 let mut values = Vec::new();
193 let mut actual = path.trim_end_matches('/').split('/');
194 for expected in self.path.split('/') {
195 let segment = actual.next()?;
196 match expected.strip_prefix(':') {
197 Some(name) if !segment.is_empty() => values.push((name, segment)),
198 Some(_) => return None,
199 None if expected == segment => {}
200 None => return None,
201 }
202 }
203 actual.next().is_none().then_some(values)
204 }
205}
206
207/// The route for a request, and the operation input it describes.
208///
209/// The input is the JSON body, overlaid with the query parameters the route
210/// reads and then with what the path names: `owner` and `name` become
211/// `repo`, and `number` becomes an integer.
212pub fn resolve(
213 method: &str,
214 path: &str,
215 query: &[(String, String)],
216 body: Value,
217) -> Option<(&'static Route, Value)> {
218 let (route, params) = ROUTES
219 .iter()
220 .filter(|route| route.method == method)
221 .find_map(|route| Some((route, route.matches(path)?)))?;
222
223 let mut input = match body {
224 Value::Object(fields) => fields,
225 _ => Map::new(),
226 };
227 for (name, key) in route.query {
228 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
229 input.insert((*key).to_owned(), Value::String(value.clone()));
230 }
231 }
232 let param = |wanted: &str| {
233 params
234 .iter()
235 .find(|(name, _)| *name == wanted)
236 .map(|(_, value)| *value)
237 };
238 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
239 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
240 }
Agents as a team: lifecycle, merge queue, billing and a new shell241 if let Some(plan) = param("plan") {
242 input.insert("plan".to_owned(), Value::String(plan.to_owned()));
243 }
API and MCP server in Rust; a public index at the API root244 if let Some(number) = param("number") {
245 // Not a number: zero, which no issue or pull request has.
246 input.insert(
247 "number".to_owned(),
248 number.parse::<u32>().unwrap_or(0).into(),
249 );
250 }
251 Some((route, Value::Object(input)))
252}
253
254#[cfg(test)]
255mod tests {
256 use serde_json::json;
257
258 use super::*;
259
260 #[test]
261 fn a_path_resolves_to_its_operation_and_input() {
262 let (route, input) = resolve(
263 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell264 "/repos/syntaqx/hello/pulls/14/merge",
API and MCP server in Rust; a public index at the API root265 &[],
266 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
267 )
268 .unwrap();
269 assert_eq!(route.op, Op::MergePullRequest);
270 // What the path names wins over the body.
271 assert_eq!(
272 input,
273 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
274 );
275 }
276
277 #[test]
278 fn query_parameters_are_renamed() {
279 let query = [
280 ("q".to_owned(), "parser".to_owned()),
281 ("x".to_owned(), "y".to_owned()),
282 ];
Agents as a team: lifecycle, merge queue, billing and a new shell283 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
API and MCP server in Rust; a public index at the API root284 assert_eq!(route.op, Op::ListRepos);
285 assert_eq!(input, json!({ "query": "parser" }));
286 }
287
288 #[test]
289 fn method_and_shape_must_match() {
Agents as a team: lifecycle, merge queue, billing and a new shell290 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
291 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
292 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
293 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
API and MCP server in Rust; a public index at the API root294 }
295
296 #[test]
297 fn every_parameter_and_query_name_is_an_input() {
298 for route in ROUTES {
299 let properties = route.op.properties();
300 for (_, key) in route.query {
301 assert!(properties.contains_key(*key), "{}: {key}", route.path);
302 }
303 for name in route.params() {
304 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
305 || properties.contains_key(name);
306 assert!(covered, "{}: {name}", route.path);
307 }
308 }
309 }
310
311 #[test]
312 fn every_operation_has_a_route() {
313 for op in Op::ALL {
314 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
315 }
316 }
317}