pr_01m47d24b0e6n91zwymwxg0vpx/apps/api/src/rest.rs

325 lines9,103 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(
69 "GET",
70 "/repos/:owner/:name/events",
71 Op::ListEvents,
72 &[("before", "before")],
73 ),
74 route("GET", "/repos/:owner/:name/labels", Op::ListLabels, &[]),
75 route(
76 "GET",
77 "/repos/:owner/:name/issues",
78 Op::ListIssues,
79 &[("state", "state"), ("label", "label")],
80 ),
81 route("POST", "/repos/:owner/:name/issues", Op::CreateIssue, &[]),
82 route(
83 "GET",
84 "/repos/:owner/:name/issues/:number",
85 Op::GetIssue,
86 &[],
87 ),
88 route(
89 "PATCH",
90 "/repos/:owner/:name/issues/:number",
91 Op::UpdateIssue,
92 &[],
93 ),
94 route(
95 "POST",
96 "/repos/:owner/:name/issues/:number/close",
97 Op::CloseIssue,
98 &[],
99 ),
100 route(
101 "POST",
102 "/repos/:owner/:name/issues/:number/reopen",
103 Op::ReopenIssue,
104 &[],
105 ),
106 route(
107 "POST",
108 "/repos/:owner/:name/issues/:number/assign",
109 Op::AssignIssue,
110 &[],
111 ),
112 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
113 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
114 route(
115 "POST",
116 "/repos/:owner/:name/plans/:plan/apply",
117 Op::ApplyPlan,
118 &[],
119 ),
120 route(
121 "POST",
122 "/repos/:owner/:name/issues/:number/comments",
123 Op::AddComment,
124 &[],
125 ),
126 route(
127 "GET",
128 "/repos/:owner/:name/pulls",
129 Op::ListPullRequests,
130 &[("state", "state")],
131 ),
132 route(
133 "POST",
134 "/repos/:owner/:name/pulls",
135 Op::CreatePullRequest,
136 &[],
137 ),
138 route(
139 "GET",
140 "/repos/:owner/:name/pulls/:number",
141 Op::GetPullRequest,
142 &[],
143 ),
144 route(
145 "GET",
146 "/repos/:owner/:name/pulls/:number/changes",
147 Op::GetPullRequestChanges,
148 &[],
149 ),
150 route(
151 "POST",
152 "/repos/:owner/:name/pulls/:number/reviews",
153 Op::ReviewPullRequest,
154 &[],
155 ),
156 route(
157 "GET",
158 "/repos/:owner/:name/pulls/:number/session",
159 Op::ReadSession,
160 &[("after", "after")],
161 ),
162 route(
163 "POST",
164 "/repos/:owner/:name/pulls/:number/session",
165 Op::RecordSession,
166 &[],
167 ),
168 route(
169 "POST",
170 "/repos/:owner/:name/pulls/:number/ready",
171 Op::MarkPullRequestReady,
172 &[],
173 ),
174 route(
175 "POST",
176 "/repos/:owner/:name/pulls/:number/close",
177 Op::ClosePullRequest,
178 &[],
179 ),
180 route(
181 "POST",
182 "/repos/:owner/:name/pulls/:number/merge",
183 Op::MergePullRequest,
184 &[],
185 ),
186];
187
188impl Route {
189 /// The names of the route's path parameters, in order.
190 pub fn params(&self) -> impl Iterator<Item = &'static str> {
191 self.path
192 .split('/')
193 .filter_map(|segment| segment.strip_prefix(':'))
194 }
195
196 /// The values of the path parameters, if `path` is this route's.
197 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
198 let mut values = Vec::new();
199 let mut actual = path.trim_end_matches('/').split('/');
200 for expected in self.path.split('/') {
201 let segment = actual.next()?;
202 match expected.strip_prefix(':') {
203 Some(name) if !segment.is_empty() => values.push((name, segment)),
204 Some(_) => return None,
205 None if expected == segment => {}
206 None => return None,
207 }
208 }
209 actual.next().is_none().then_some(values)
210 }
211}
212
213/// The route for a request, and the operation input it describes.
214///
215/// The input is the JSON body, overlaid with the query parameters the route
216/// reads and then with what the path names: `owner` and `name` become
217/// `repo`, and `number` becomes an integer.
218pub fn resolve(
219 method: &str,
220 path: &str,
221 query: &[(String, String)],
222 body: Value,
223) -> Option<(&'static Route, Value)> {
224 let (route, params) = ROUTES
225 .iter()
226 .filter(|route| route.method == method)
227 .find_map(|route| Some((route, route.matches(path)?)))?;
228
229 let mut input = match body {
230 Value::Object(fields) => fields,
231 _ => Map::new(),
232 };
233 for (name, key) in route.query {
234 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
235 input.insert((*key).to_owned(), Value::String(value.clone()));
236 }
237 }
238 let param = |wanted: &str| {
239 params
240 .iter()
241 .find(|(name, _)| *name == wanted)
242 .map(|(_, value)| *value)
243 };
244 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
245 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
246 }
247 for key in ["plan", "id"] {
248 if let Some(value) = param(key) {
249 input.insert(key.to_owned(), Value::String(value.to_owned()));
250 }
251 }
252 if let Some(number) = param("number") {
253 // Not a number: zero, which no issue or pull request has.
254 input.insert(
255 "number".to_owned(),
256 number.parse::<u32>().unwrap_or(0).into(),
257 );
258 }
259 Some((route, Value::Object(input)))
260}
261
262#[cfg(test)]
263mod tests {
264 use serde_json::json;
265
266 use super::*;
267
268 #[test]
269 fn a_path_resolves_to_its_operation_and_input() {
270 let (route, input) = resolve(
271 "POST",
272 "/repos/syntaqx/hello/pulls/14/merge",
273 &[],
274 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
275 )
276 .unwrap();
277 assert_eq!(route.op, Op::MergePullRequest);
278 // What the path names wins over the body.
279 assert_eq!(
280 input,
281 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
282 );
283 }
284
285 #[test]
286 fn query_parameters_are_renamed() {
287 let query = [
288 ("q".to_owned(), "parser".to_owned()),
289 ("x".to_owned(), "y".to_owned()),
290 ];
291 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
292 assert_eq!(route.op, Op::ListRepos);
293 assert_eq!(input, json!({ "query": "parser" }));
294 }
295
296 #[test]
297 fn method_and_shape_must_match() {
298 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
299 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
300 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
301 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
302 }
303
304 #[test]
305 fn every_parameter_and_query_name_is_an_input() {
306 for route in ROUTES {
307 let properties = route.op.properties();
308 for (_, key) in route.query {
309 assert!(properties.contains_key(*key), "{}: {key}", route.path);
310 }
311 for name in route.params() {
312 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
313 || properties.contains_key(name);
314 assert!(covered, "{}: {name}", route.path);
315 }
316 }
317 }
318
319 #[test]
320 fn every_operation_has_a_route() {
321 for op in Op::ALL {
322 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
323 }
324 }
325}