flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/rest.rs

627 lines16,145 bytesCodeBlame
1//! 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] = &[
31 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, &[]),
50 route(
51 "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(
63 "POST",
64 "/repos/:owner/:name/messages/:id/answer",
65 Op::AnswerMessage,
66 &[],
67 ),
68 route("POST", "/repos/:owner/:name/memory", Op::Remember, &[]),
69 route(
70 "GET",
71 "/repos/:owner/:name/memory",
72 Op::Recall,
73 &[("q", "query"), ("limit", "limit")],
74 ),
75 route(
76 "GET",
77 "/repos/:owner/:name/events",
78 Op::ListEvents,
79 &[("before", "before")],
80 ),
81 route("GET", "/repos/:owner/:name/labels", Op::ListLabels, &[]),
82 route(
83 "GET",
84 "/repos/:owner/:name/issues",
85 Op::ListIssues,
86 &[("state", "state"), ("label", "label")],
87 ),
88 route("POST", "/repos/:owner/:name/issues", Op::CreateIssue, &[]),
89 route(
90 "GET",
91 "/repos/:owner/:name/issues/:number",
92 Op::GetIssue,
93 &[],
94 ),
95 route(
96 "PATCH",
97 "/repos/:owner/:name/issues/:number",
98 Op::UpdateIssue,
99 &[],
100 ),
101 route(
102 "POST",
103 "/repos/:owner/:name/issues/:number/close",
104 Op::CloseIssue,
105 &[],
106 ),
107 route(
108 "POST",
109 "/repos/:owner/:name/issues/:number/reopen",
110 Op::ReopenIssue,
111 &[],
112 ),
113 route(
114 "POST",
115 "/repos/:owner/:name/issues/:number/assign",
116 Op::AssignIssue,
117 &[],
118 ),
119 route(
120 "POST",
121 "/repos/:owner/:name/issues/import",
122 Op::ImportIssue,
123 &[],
124 ),
125 route(
126 "GET",
127 "/repos/:owner/:name/context",
128 Op::GetContext,
129 &[("reference", "reference")],
130 ),
131 route(
132 "GET",
133 "/workspaces/:workspace/integrations",
134 Op::ListIntegrations,
135 &[],
136 ),
137 route(
138 "POST",
139 "/workspaces/:workspace/integrations",
140 Op::ConnectIntegration,
141 &[],
142 ),
143 route(
144 "GET",
145 "/repos/:owner/:name/hooks",
146 Op::ListWebhooks,
147 &[],
148 ),
149 route(
150 "POST",
151 "/repos/:owner/:name/hooks",
152 Op::CreateWebhook,
153 &[],
154 ),
155 route(
156 "PATCH",
157 "/repos/:owner/:name/hooks/:id",
158 Op::UpdateWebhook,
159 &[],
160 ),
161 route(
162 "DELETE",
163 "/repos/:owner/:name/hooks/:id",
164 Op::DeleteWebhook,
165 &[],
166 ),
167 route(
168 "POST",
169 "/repos/:owner/:name/hooks/:id/pings",
170 Op::PingWebhook,
171 &[],
172 ),
173 route(
174 "GET",
175 "/repos/:owner/:name/hooks/:id/deliveries",
176 Op::ListWebhookDeliveries,
177 &[],
178 ),
179 route(
180 "POST",
181 "/repos/:owner/:name/hooks/:id/deliveries/:delivery/redeliver",
182 Op::RedeliverWebhook,
183 &[],
184 ),
185 route(
186 "GET",
187 "/workspaces/:workspace/hooks",
188 Op::ListWebhooks,
189 &[],
190 ),
191 route(
192 "POST",
193 "/workspaces/:workspace/hooks",
194 Op::CreateWebhook,
195 &[],
196 ),
197 route(
198 "PATCH",
199 "/workspaces/:workspace/hooks/:id",
200 Op::UpdateWebhook,
201 &[],
202 ),
203 route(
204 "DELETE",
205 "/workspaces/:workspace/hooks/:id",
206 Op::DeleteWebhook,
207 &[],
208 ),
209 route(
210 "POST",
211 "/workspaces/:workspace/hooks/:id/pings",
212 Op::PingWebhook,
213 &[],
214 ),
215 route(
216 "GET",
217 "/workspaces/:workspace/hooks/:id/deliveries",
218 Op::ListWebhookDeliveries,
219 &[],
220 ),
221 route(
222 "POST",
223 "/workspaces/:workspace/hooks/:id/deliveries/:delivery/redeliver",
224 Op::RedeliverWebhook,
225 &[],
226 ),
227 route(
228 "GET",
229 "/workspaces/:workspace/model-routes",
230 Op::GetModelRoutes,
231 &[],
232 ),
233 route(
234 "PUT",
235 "/workspaces/:workspace/model-routes",
236 Op::SetModelRoutes,
237 &[],
238 ),
239 route(
240 "DELETE",
241 "/workspaces/:workspace/integrations/:id",
242 Op::DisconnectIntegration,
243 &[],
244 ),
245 route(
246 "POST",
247 "/workspaces/:workspace/integrations/:id/test",
248 Op::TestIntegration,
249 &[],
250 ),
251 route(
252 "GET",
253 "/repos/:owner/:name/actions/workflows",
254 Op::ListWorkflows,
255 &[],
256 ),
257 route(
258 "GET",
259 "/repos/:owner/:name/actions/workflows/:workflow/runs",
260 Op::ListWorkflowRuns,
261 &[("branch", "branch"), ("event", "event"), ("per_page", "limit")],
262 ),
263 route(
264 "POST",
265 "/repos/:owner/:name/actions/workflows/:workflow/dispatches",
266 Op::DispatchWorkflow,
267 &[],
268 ),
269 route(
270 "PATCH",
271 "/repos/:owner/:name/actions/workflows/:workflow",
272 Op::UpdateWorkflow,
273 &[],
274 ),
275 route(
276 "PUT",
277 "/repos/:owner/:name/actions/workflows/:workflow/enable",
278 Op::UpdateWorkflow,
279 &[],
280 ),
281 route(
282 "PUT",
283 "/repos/:owner/:name/actions/workflows/:workflow/disable",
284 Op::UpdateWorkflow,
285 &[],
286 ),
287 route(
288 "GET",
289 "/repos/:owner/:name/actions/runs",
290 Op::ListWorkflowRuns,
291 &[("workflow", "workflow"), ("branch", "branch"), ("event", "event"), ("pull", "pull"), ("head_sha", "sha"), ("per_page", "limit")],
292 ),
293 route(
294 "GET",
295 "/repos/:owner/:name/actions/runs/:id",
296 Op::GetWorkflowRun,
297 &[],
298 ),
299 route(
300 "POST",
301 "/repos/:owner/:name/actions/runs/:id/cancel",
302 Op::CancelWorkflowRun,
303 &[],
304 ),
305 route(
306 "POST",
307 "/repos/:owner/:name/actions/runs/:id/rerun",
308 Op::RerunWorkflowRun,
309 &[],
310 ),
311 route(
312 "POST",
313 "/repos/:owner/:name/actions/runs/:id/rerun-failed-jobs",
314 Op::RerunWorkflowRun,
315 &[],
316 ),
317 route(
318 "GET",
319 "/repos/:owner/:name/actions/jobs/:job/logs",
320 Op::GetJobLogs,
321 &[("after", "after")],
322 ),
323 route(
324 "GET",
325 "/repos/:owner/:name/actions/secrets",
326 Op::ListActionsSecrets,
327 &[],
328 ),
329 route(
330 "PUT",
331 "/repos/:owner/:name/actions/secrets/:setting",
332 Op::SetActionsSecret,
333 &[],
334 ),
335 route(
336 "DELETE",
337 "/repos/:owner/:name/actions/secrets/:setting",
338 Op::DeleteActionsSecret,
339 &[],
340 ),
341 route(
342 "GET",
343 "/repos/:owner/:name/actions/variables",
344 Op::ListActionsVariables,
345 &[],
346 ),
347 route(
348 "POST",
349 "/repos/:owner/:name/actions/variables",
350 Op::SetActionsVariable,
351 &[],
352 ),
353 route(
354 "PATCH",
355 "/repos/:owner/:name/actions/variables/:setting",
356 Op::SetActionsVariable,
357 &[],
358 ),
359 route(
360 "DELETE",
361 "/repos/:owner/:name/actions/variables/:setting",
362 Op::DeleteActionsVariable,
363 &[],
364 ),
365 route(
366 "GET",
367 "/workspaces/:workspace/actions/secrets",
368 Op::ListActionsSecrets,
369 &[],
370 ),
371 route(
372 "PUT",
373 "/workspaces/:workspace/actions/secrets/:setting",
374 Op::SetActionsSecret,
375 &[],
376 ),
377 route(
378 "DELETE",
379 "/workspaces/:workspace/actions/secrets/:setting",
380 Op::DeleteActionsSecret,
381 &[],
382 ),
383 route(
384 "GET",
385 "/workspaces/:workspace/actions/variables",
386 Op::ListActionsVariables,
387 &[],
388 ),
389 route(
390 "POST",
391 "/workspaces/:workspace/actions/variables",
392 Op::SetActionsVariable,
393 &[],
394 ),
395 route(
396 "PATCH",
397 "/workspaces/:workspace/actions/variables/:setting",
398 Op::SetActionsVariable,
399 &[],
400 ),
401 route(
402 "DELETE",
403 "/workspaces/:workspace/actions/variables/:setting",
404 Op::DeleteActionsVariable,
405 &[],
406 ),
407 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
408 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
409 route(
410 "POST",
411 "/repos/:owner/:name/plans/:plan/apply",
412 Op::ApplyPlan,
413 &[],
414 ),
415 route(
416 "POST",
417 "/repos/:owner/:name/issues/:number/comments",
418 Op::AddComment,
419 &[],
420 ),
421 route(
422 "GET",
423 "/repos/:owner/:name/pulls",
424 Op::ListPullRequests,
425 &[("state", "state")],
426 ),
427 route(
428 "POST",
429 "/repos/:owner/:name/pulls",
430 Op::CreatePullRequest,
431 &[],
432 ),
433 route(
434 "GET",
435 "/repos/:owner/:name/pulls/:number",
436 Op::GetPullRequest,
437 &[],
438 ),
439 route(
440 "GET",
441 "/repos/:owner/:name/pulls/:number/changes",
442 Op::GetPullRequestChanges,
443 &[],
444 ),
445 route(
446 "POST",
447 "/repos/:owner/:name/pulls/:number/reviews",
448 Op::ReviewPullRequest,
449 &[],
450 ),
451 route(
452 "GET",
453 "/repos/:owner/:name/pulls/:number/session",
454 Op::ReadSession,
455 &[("after", "after")],
456 ),
457 route(
458 "POST",
459 "/repos/:owner/:name/pulls/:number/session",
460 Op::RecordSession,
461 &[],
462 ),
463 route(
464 "POST",
465 "/repos/:owner/:name/pulls/:number/ready",
466 Op::MarkPullRequestReady,
467 &[],
468 ),
469 route(
470 "POST",
471 "/repos/:owner/:name/pulls/:number/close",
472 Op::ClosePullRequest,
473 &[],
474 ),
475 route(
476 "POST",
477 "/repos/:owner/:name/pulls/:number/merge",
478 Op::MergePullRequest,
479 &[],
480 ),
481];
482
483impl Route {
484 /// The names of the route's path parameters, in order.
485 pub fn params(&self) -> impl Iterator<Item = &'static str> {
486 self.path
487 .split('/')
488 .filter_map(|segment| segment.strip_prefix(':'))
489 }
490
491 /// The values of the path parameters, if `path` is this route's.
492 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
493 let mut values = Vec::new();
494 let mut actual = path.trim_end_matches('/').split('/');
495 for expected in self.path.split('/') {
496 let segment = actual.next()?;
497 match expected.strip_prefix(':') {
498 Some(name) if !segment.is_empty() => values.push((name, segment)),
499 Some(_) => return None,
500 None if expected == segment => {}
501 None => return None,
502 }
503 }
504 actual.next().is_none().then_some(values)
505 }
506}
507
508/// The route for a request, and the operation input it describes.
509///
510/// The input is the JSON body, overlaid with the query parameters the route
511/// reads and then with what the path names: `owner` and `name` become
512/// `repo`, and `number` becomes an integer.
513pub fn resolve(
514 method: &str,
515 path: &str,
516 query: &[(String, String)],
517 body: Value,
518) -> Option<(&'static Route, Value)> {
519 let (route, params) = ROUTES
520 .iter()
521 .filter(|route| route.method == method)
522 .find_map(|route| Some((route, route.matches(path)?)))?;
523
524 let mut input = match body {
525 Value::Object(fields) => fields,
526 _ => Map::new(),
527 };
528 for (name, key) in route.query {
529 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
530 input.insert((*key).to_owned(), Value::String(value.clone()));
531 }
532 }
533 let param = |wanted: &str| {
534 params
535 .iter()
536 .find(|(name, _)| *name == wanted)
537 .map(|(_, value)| *value)
538 };
539 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
540 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
541 }
542 for key in ["plan", "id", "workspace", "delivery", "workflow", "job", "setting"] {
543 if let Some(value) = param(key) {
544 input.insert(key.to_owned(), Value::String(value.to_owned()));
545 }
546 }
547 // GitHub says some things with the path alone.
548 if route.path.ends_with("/enable") || route.path.ends_with("/disable") {
549 input.insert("enabled".to_owned(), Value::Bool(route.path.ends_with("/enable")));
550 }
551 if route.path.ends_with("/rerun-failed-jobs") {
552 input.insert("failed_only".to_owned(), Value::Bool(true));
553 }
554 if let Some(number) = param("number") {
555 // Not a number: zero, which no issue or pull request has.
556 input.insert(
557 "number".to_owned(),
558 number.parse::<u32>().unwrap_or(0).into(),
559 );
560 }
561 Some((route, Value::Object(input)))
562}
563
564#[cfg(test)]
565mod tests {
566 use serde_json::json;
567
568 use super::*;
569
570 #[test]
571 fn a_path_resolves_to_its_operation_and_input() {
572 let (route, input) = resolve(
573 "POST",
574 "/repos/syntaqx/hello/pulls/14/merge",
575 &[],
576 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
577 )
578 .unwrap();
579 assert_eq!(route.op, Op::MergePullRequest);
580 // What the path names wins over the body.
581 assert_eq!(
582 input,
583 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
584 );
585 }
586
587 #[test]
588 fn query_parameters_are_renamed() {
589 let query = [
590 ("q".to_owned(), "parser".to_owned()),
591 ("x".to_owned(), "y".to_owned()),
592 ];
593 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
594 assert_eq!(route.op, Op::ListRepos);
595 assert_eq!(input, json!({ "query": "parser" }));
596 }
597
598 #[test]
599 fn method_and_shape_must_match() {
600 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
601 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
602 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
603 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
604 }
605
606 #[test]
607 fn every_parameter_and_query_name_is_an_input() {
608 for route in ROUTES {
609 let properties = route.op.properties();
610 for (_, key) in route.query {
611 assert!(properties.contains_key(*key), "{}: {key}", route.path);
612 }
613 for name in route.params() {
614 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
615 || properties.contains_key(name);
616 assert!(covered, "{}: {name}", route.path);
617 }
618 }
619 }
620
621 #[test]
622 fn every_operation_has_a_route() {
623 for op in Op::ALL {
624 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
625 }
626 }
627}