g1t/apps/api/src/rest.rs

361 lines9,884 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(
Docs worth reading, and kept that way63 "POST",
64 "/repos/:owner/:name/messages/:id/answer",
65 Op::AnswerMessage,
66 &[],
67 ),
68 route(
API and MCP server in Rust; a public index at the API root69 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell70 "/repos/:owner/:name/events",
API and MCP server in Rust; a public index at the API root71 Op::ListEvents,
72 &[("before", "before")],
73 ),
Agents as a team: lifecycle, merge queue, billing and a new shell74 route("GET", "/repos/:owner/:name/labels", Op::ListLabels, &[]),
API and MCP server in Rust; a public index at the API root75 route(
76 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell77 "/repos/:owner/:name/issues",
API and MCP server in Rust; a public index at the API root78 Op::ListIssues,
79 &[("state", "state"), ("label", "label")],
80 ),
Agents as a team: lifecycle, merge queue, billing and a new shell81 route("POST", "/repos/:owner/:name/issues", Op::CreateIssue, &[]),
API and MCP server in Rust; a public index at the API root82 route(
83 "GET",
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::GetIssue,
86 &[],
87 ),
88 route(
89 "PATCH",
Agents as a team: lifecycle, merge queue, billing and a new shell90 "/repos/:owner/:name/issues/:number",
API and MCP server in Rust; a public index at the API root91 Op::UpdateIssue,
92 &[],
93 ),
94 route(
95 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell96 "/repos/:owner/:name/issues/:number/close",
API and MCP server in Rust; a public index at the API root97 Op::CloseIssue,
98 &[],
99 ),
100 route(
101 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell102 "/repos/:owner/:name/issues/:number/reopen",
API and MCP server in Rust; a public index at the API root103 Op::ReopenIssue,
104 &[],
105 ),
106 route(
107 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell108 "/repos/:owner/:name/issues/:number/assign",
109 Op::AssignIssue,
110 &[],
111 ),
Integrations: your own model provider, alerts that open issues, tickets agents read112 route(
113 "POST",
114 "/repos/:owner/:name/issues/import",
115 Op::ImportIssue,
116 &[],
117 ),
118 route(
119 "GET",
120 "/repos/:owner/:name/context",
121 Op::GetContext,
122 &[("reference", "reference")],
123 ),
124 route(
125 "GET",
126 "/workspaces/:workspace/integrations",
127 Op::ListIntegrations,
128 &[],
129 ),
130 route(
131 "POST",
132 "/workspaces/:workspace/integrations",
133 Op::ConnectIntegration,
134 &[],
135 ),
136 route(
137 "DELETE",
138 "/workspaces/:workspace/integrations/:id",
139 Op::DisconnectIntegration,
140 &[],
141 ),
142 route(
143 "POST",
144 "/workspaces/:workspace/integrations/:id/test",
145 Op::TestIntegration,
146 &[],
147 ),
Agents as a team: lifecycle, merge queue, billing and a new shell148 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
149 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
150 route(
151 "POST",
152 "/repos/:owner/:name/plans/:plan/apply",
153 Op::ApplyPlan,
154 &[],
155 ),
156 route(
157 "POST",
158 "/repos/:owner/:name/issues/:number/comments",
API and MCP server in Rust; a public index at the API root159 Op::AddComment,
160 &[],
161 ),
162 route(
163 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell164 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root165 Op::ListPullRequests,
166 &[("state", "state")],
167 ),
168 route(
169 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell170 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root171 Op::CreatePullRequest,
172 &[],
173 ),
174 route(
175 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell176 "/repos/:owner/:name/pulls/:number",
API and MCP server in Rust; a public index at the API root177 Op::GetPullRequest,
178 &[],
179 ),
180 route(
181 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell182 "/repos/:owner/:name/pulls/:number/changes",
API and MCP server in Rust; a public index at the API root183 Op::GetPullRequestChanges,
184 &[],
185 ),
186 route(
Acceptance checks in sandboxes, line comments and review verdicts187 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell188 "/repos/:owner/:name/pulls/:number/reviews",
Acceptance checks in sandboxes, line comments and review verdicts189 Op::ReviewPullRequest,
190 &[],
191 ),
192 route(
API and MCP server in Rust; a public index at the API root193 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell194 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root195 Op::ReadSession,
196 &[("after", "after")],
197 ),
198 route(
199 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell200 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root201 Op::RecordSession,
202 &[],
203 ),
204 route(
205 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell206 "/repos/:owner/:name/pulls/:number/ready",
API and MCP server in Rust; a public index at the API root207 Op::MarkPullRequestReady,
208 &[],
209 ),
210 route(
211 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell212 "/repos/:owner/:name/pulls/:number/close",
API and MCP server in Rust; a public index at the API root213 Op::ClosePullRequest,
214 &[],
215 ),
216 route(
217 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell218 "/repos/:owner/:name/pulls/:number/merge",
API and MCP server in Rust; a public index at the API root219 Op::MergePullRequest,
220 &[],
221 ),
222];
223
224impl Route {
225 /// The names of the route's path parameters, in order.
226 pub fn params(&self) -> impl Iterator<Item = &'static str> {
227 self.path
228 .split('/')
229 .filter_map(|segment| segment.strip_prefix(':'))
230 }
231
232 /// The values of the path parameters, if `path` is this route's.
233 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
234 let mut values = Vec::new();
235 let mut actual = path.trim_end_matches('/').split('/');
236 for expected in self.path.split('/') {
237 let segment = actual.next()?;
238 match expected.strip_prefix(':') {
239 Some(name) if !segment.is_empty() => values.push((name, segment)),
240 Some(_) => return None,
241 None if expected == segment => {}
242 None => return None,
243 }
244 }
245 actual.next().is_none().then_some(values)
246 }
247}
248
249/// The route for a request, and the operation input it describes.
250///
251/// The input is the JSON body, overlaid with the query parameters the route
252/// reads and then with what the path names: `owner` and `name` become
253/// `repo`, and `number` becomes an integer.
254pub fn resolve(
255 method: &str,
256 path: &str,
257 query: &[(String, String)],
258 body: Value,
259) -> Option<(&'static Route, Value)> {
260 let (route, params) = ROUTES
261 .iter()
262 .filter(|route| route.method == method)
263 .find_map(|route| Some((route, route.matches(path)?)))?;
264
265 let mut input = match body {
266 Value::Object(fields) => fields,
267 _ => Map::new(),
268 };
269 for (name, key) in route.query {
270 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
271 input.insert((*key).to_owned(), Value::String(value.clone()));
272 }
273 }
274 let param = |wanted: &str| {
275 params
276 .iter()
277 .find(|(name, _)| *name == wanted)
278 .map(|(_, value)| *value)
279 };
280 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
281 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
282 }
Integrations: your own model provider, alerts that open issues, tickets agents read283 for key in ["plan", "id", "workspace"] {
Docs worth reading, and kept that way284 if let Some(value) = param(key) {
285 input.insert(key.to_owned(), Value::String(value.to_owned()));
286 }
Agents as a team: lifecycle, merge queue, billing and a new shell287 }
API and MCP server in Rust; a public index at the API root288 if let Some(number) = param("number") {
289 // Not a number: zero, which no issue or pull request has.
290 input.insert(
291 "number".to_owned(),
292 number.parse::<u32>().unwrap_or(0).into(),
293 );
294 }
295 Some((route, Value::Object(input)))
296}
297
298#[cfg(test)]
299mod tests {
300 use serde_json::json;
301
302 use super::*;
303
304 #[test]
305 fn a_path_resolves_to_its_operation_and_input() {
306 let (route, input) = resolve(
307 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell308 "/repos/syntaqx/hello/pulls/14/merge",
API and MCP server in Rust; a public index at the API root309 &[],
310 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
311 )
312 .unwrap();
313 assert_eq!(route.op, Op::MergePullRequest);
314 // What the path names wins over the body.
315 assert_eq!(
316 input,
317 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
318 );
319 }
320
321 #[test]
322 fn query_parameters_are_renamed() {
323 let query = [
324 ("q".to_owned(), "parser".to_owned()),
325 ("x".to_owned(), "y".to_owned()),
326 ];
Agents as a team: lifecycle, merge queue, billing and a new shell327 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
API and MCP server in Rust; a public index at the API root328 assert_eq!(route.op, Op::ListRepos);
329 assert_eq!(input, json!({ "query": "parser" }));
330 }
331
332 #[test]
333 fn method_and_shape_must_match() {
Agents as a team: lifecycle, merge queue, billing and a new shell334 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
335 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
336 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
337 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
API and MCP server in Rust; a public index at the API root338 }
339
340 #[test]
341 fn every_parameter_and_query_name_is_an_input() {
342 for route in ROUTES {
343 let properties = route.op.properties();
344 for (_, key) in route.query {
345 assert!(properties.contains_key(*key), "{}: {key}", route.path);
346 }
347 for name in route.params() {
348 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
349 || properties.contains_key(name);
350 assert!(covered, "{}: {name}", route.path);
351 }
352 }
353 }
354
355 #[test]
356 fn every_operation_has_a_route() {
357 for op in Op::ALL {
358 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
359 }
360 }
361}