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

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