g1t/apps/api/src/rest.rs

481 lines12,390 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(
Models per workspace: several providers, routed by kind of work137 "GET",
Webhooks: every event, to your own addresses, signed and retried138 "/repos/:owner/:name/hooks",
139 Op::ListWebhooks,
140 &[],
141 ),
142 route(
143 "POST",
144 "/repos/:owner/:name/hooks",
145 Op::CreateWebhook,
146 &[],
147 ),
148 route(
149 "PATCH",
150 "/repos/:owner/:name/hooks/:id",
151 Op::UpdateWebhook,
152 &[],
153 ),
154 route(
155 "DELETE",
156 "/repos/:owner/:name/hooks/:id",
157 Op::DeleteWebhook,
158 &[],
159 ),
160 route(
161 "POST",
162 "/repos/:owner/:name/hooks/:id/pings",
163 Op::PingWebhook,
164 &[],
165 ),
166 route(
167 "GET",
168 "/repos/:owner/:name/hooks/:id/deliveries",
169 Op::ListWebhookDeliveries,
170 &[],
171 ),
172 route(
173 "POST",
174 "/repos/:owner/:name/hooks/:id/deliveries/:delivery/redeliver",
175 Op::RedeliverWebhook,
176 &[],
177 ),
178 route(
179 "GET",
180 "/workspaces/:workspace/hooks",
181 Op::ListWebhooks,
182 &[],
183 ),
184 route(
185 "POST",
186 "/workspaces/:workspace/hooks",
187 Op::CreateWebhook,
188 &[],
189 ),
190 route(
191 "PATCH",
192 "/workspaces/:workspace/hooks/:id",
193 Op::UpdateWebhook,
194 &[],
195 ),
196 route(
197 "DELETE",
198 "/workspaces/:workspace/hooks/:id",
199 Op::DeleteWebhook,
200 &[],
201 ),
202 route(
203 "POST",
204 "/workspaces/:workspace/hooks/:id/pings",
205 Op::PingWebhook,
206 &[],
207 ),
208 route(
209 "GET",
210 "/workspaces/:workspace/hooks/:id/deliveries",
211 Op::ListWebhookDeliveries,
212 &[],
213 ),
214 route(
215 "POST",
216 "/workspaces/:workspace/hooks/:id/deliveries/:delivery/redeliver",
217 Op::RedeliverWebhook,
218 &[],
219 ),
220 route(
221 "GET",
Models per workspace: several providers, routed by kind of work222 "/workspaces/:workspace/model-routes",
223 Op::GetModelRoutes,
224 &[],
225 ),
226 route(
227 "PUT",
228 "/workspaces/:workspace/model-routes",
229 Op::SetModelRoutes,
230 &[],
231 ),
232 route(
Integrations: your own model provider, alerts that open issues, tickets agents read233 "DELETE",
234 "/workspaces/:workspace/integrations/:id",
235 Op::DisconnectIntegration,
236 &[],
237 ),
238 route(
239 "POST",
240 "/workspaces/:workspace/integrations/:id/test",
241 Op::TestIntegration,
242 &[],
243 ),
Automations: rules in .g1t/automations that act when something happens244 route(
245 "GET",
246 "/repos/:owner/:name/automations/runs",
247 Op::ListAutomationRuns,
248 &[("automation", "automation")],
249 ),
250 route(
251 "GET",
252 "/repos/:owner/:name/automations",
253 Op::ListAutomations,
254 &[],
255 ),
256 route(
257 "POST",
258 "/repos/:owner/:name/automations/:id/runs",
259 Op::RunAutomation,
260 &[],
261 ),
262 route(
263 "PATCH",
264 "/repos/:owner/:name/automations/:id",
265 Op::UpdateAutomation,
266 &[],
267 ),
Agents as a team: lifecycle, merge queue, billing and a new shell268 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
269 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
270 route(
271 "POST",
272 "/repos/:owner/:name/plans/:plan/apply",
273 Op::ApplyPlan,
274 &[],
275 ),
276 route(
277 "POST",
278 "/repos/:owner/:name/issues/:number/comments",
API and MCP server in Rust; a public index at the API root279 Op::AddComment,
280 &[],
281 ),
282 route(
283 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell284 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root285 Op::ListPullRequests,
286 &[("state", "state")],
287 ),
288 route(
289 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell290 "/repos/:owner/:name/pulls",
API and MCP server in Rust; a public index at the API root291 Op::CreatePullRequest,
292 &[],
293 ),
294 route(
295 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell296 "/repos/:owner/:name/pulls/:number",
API and MCP server in Rust; a public index at the API root297 Op::GetPullRequest,
298 &[],
299 ),
300 route(
301 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell302 "/repos/:owner/:name/pulls/:number/changes",
API and MCP server in Rust; a public index at the API root303 Op::GetPullRequestChanges,
304 &[],
305 ),
306 route(
Acceptance checks in sandboxes, line comments and review verdicts307 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell308 "/repos/:owner/:name/pulls/:number/reviews",
Acceptance checks in sandboxes, line comments and review verdicts309 Op::ReviewPullRequest,
310 &[],
311 ),
312 route(
API and MCP server in Rust; a public index at the API root313 "GET",
Agents as a team: lifecycle, merge queue, billing and a new shell314 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root315 Op::ReadSession,
316 &[("after", "after")],
317 ),
318 route(
319 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell320 "/repos/:owner/:name/pulls/:number/session",
API and MCP server in Rust; a public index at the API root321 Op::RecordSession,
322 &[],
323 ),
324 route(
325 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell326 "/repos/:owner/:name/pulls/:number/ready",
API and MCP server in Rust; a public index at the API root327 Op::MarkPullRequestReady,
328 &[],
329 ),
330 route(
331 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell332 "/repos/:owner/:name/pulls/:number/close",
API and MCP server in Rust; a public index at the API root333 Op::ClosePullRequest,
334 &[],
335 ),
336 route(
337 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell338 "/repos/:owner/:name/pulls/:number/merge",
API and MCP server in Rust; a public index at the API root339 Op::MergePullRequest,
340 &[],
341 ),
342];
343
344impl Route {
345 /// The names of the route's path parameters, in order.
346 pub fn params(&self) -> impl Iterator<Item = &'static str> {
347 self.path
348 .split('/')
349 .filter_map(|segment| segment.strip_prefix(':'))
350 }
351
352 /// The values of the path parameters, if `path` is this route's.
353 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
354 let mut values = Vec::new();
355 let mut actual = path.trim_end_matches('/').split('/');
356 for expected in self.path.split('/') {
357 let segment = actual.next()?;
358 match expected.strip_prefix(':') {
359 Some(name) if !segment.is_empty() => values.push((name, segment)),
360 Some(_) => return None,
361 None if expected == segment => {}
362 None => return None,
363 }
364 }
365 actual.next().is_none().then_some(values)
366 }
367}
368
369/// The route for a request, and the operation input it describes.
370///
371/// The input is the JSON body, overlaid with the query parameters the route
372/// reads and then with what the path names: `owner` and `name` become
373/// `repo`, and `number` becomes an integer.
374pub fn resolve(
375 method: &str,
376 path: &str,
377 query: &[(String, String)],
378 body: Value,
379) -> Option<(&'static Route, Value)> {
380 let (route, params) = ROUTES
381 .iter()
382 .filter(|route| route.method == method)
383 .find_map(|route| Some((route, route.matches(path)?)))?;
384
385 let mut input = match body {
386 Value::Object(fields) => fields,
387 _ => Map::new(),
388 };
389 for (name, key) in route.query {
390 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
391 input.insert((*key).to_owned(), Value::String(value.clone()));
392 }
393 }
394 let param = |wanted: &str| {
395 params
396 .iter()
397 .find(|(name, _)| *name == wanted)
398 .map(|(_, value)| *value)
399 };
400 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
401 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
402 }
Webhooks: every event, to your own addresses, signed and retried403 for key in ["plan", "id", "workspace", "delivery"] {
Docs worth reading, and kept that way404 if let Some(value) = param(key) {
405 input.insert(key.to_owned(), Value::String(value.to_owned()));
406 }
Agents as a team: lifecycle, merge queue, billing and a new shell407 }
API and MCP server in Rust; a public index at the API root408 if let Some(number) = param("number") {
409 // Not a number: zero, which no issue or pull request has.
410 input.insert(
411 "number".to_owned(),
412 number.parse::<u32>().unwrap_or(0).into(),
413 );
414 }
415 Some((route, Value::Object(input)))
416}
417
418#[cfg(test)]
419mod tests {
420 use serde_json::json;
421
422 use super::*;
423
424 #[test]
425 fn a_path_resolves_to_its_operation_and_input() {
426 let (route, input) = resolve(
427 "POST",
Agents as a team: lifecycle, merge queue, billing and a new shell428 "/repos/syntaqx/hello/pulls/14/merge",
API and MCP server in Rust; a public index at the API root429 &[],
430 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
431 )
432 .unwrap();
433 assert_eq!(route.op, Op::MergePullRequest);
434 // What the path names wins over the body.
435 assert_eq!(
436 input,
437 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
438 );
439 }
440
441 #[test]
442 fn query_parameters_are_renamed() {
443 let query = [
444 ("q".to_owned(), "parser".to_owned()),
445 ("x".to_owned(), "y".to_owned()),
446 ];
Agents as a team: lifecycle, merge queue, billing and a new shell447 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
API and MCP server in Rust; a public index at the API root448 assert_eq!(route.op, Op::ListRepos);
449 assert_eq!(input, json!({ "query": "parser" }));
450 }
451
452 #[test]
453 fn method_and_shape_must_match() {
Agents as a team: lifecycle, merge queue, billing and a new shell454 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
455 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
456 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
457 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
API and MCP server in Rust; a public index at the API root458 }
459
460 #[test]
461 fn every_parameter_and_query_name_is_an_input() {
462 for route in ROUTES {
463 let properties = route.op.properties();
464 for (_, key) in route.query {
465 assert!(properties.contains_key(*key), "{}: {key}", route.path);
466 }
467 for name in route.params() {
468 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
469 || properties.contains_key(name);
470 assert!(covered, "{}: {name}", route.path);
471 }
472 }
473 }
474
475 #[test]
476 fn every_operation_has_a_route() {
477 for op in Op::ALL {
478 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
479 }
480 }
481}