pr_01m47d15m3e54sn21z27rpy5n9/apps/api/src/rest.rs

457 lines11,867 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(
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 "GET",
138 "/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",
222 "/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(
233 "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 ),
244 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
245 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
246 route(
247 "POST",
248 "/repos/:owner/:name/plans/:plan/apply",
249 Op::ApplyPlan,
250 &[],
251 ),
252 route(
253 "POST",
254 "/repos/:owner/:name/issues/:number/comments",
255 Op::AddComment,
256 &[],
257 ),
258 route(
259 "GET",
260 "/repos/:owner/:name/pulls",
261 Op::ListPullRequests,
262 &[("state", "state")],
263 ),
264 route(
265 "POST",
266 "/repos/:owner/:name/pulls",
267 Op::CreatePullRequest,
268 &[],
269 ),
270 route(
271 "GET",
272 "/repos/:owner/:name/pulls/:number",
273 Op::GetPullRequest,
274 &[],
275 ),
276 route(
277 "GET",
278 "/repos/:owner/:name/pulls/:number/changes",
279 Op::GetPullRequestChanges,
280 &[],
281 ),
282 route(
283 "POST",
284 "/repos/:owner/:name/pulls/:number/reviews",
285 Op::ReviewPullRequest,
286 &[],
287 ),
288 route(
289 "GET",
290 "/repos/:owner/:name/pulls/:number/session",
291 Op::ReadSession,
292 &[("after", "after")],
293 ),
294 route(
295 "POST",
296 "/repos/:owner/:name/pulls/:number/session",
297 Op::RecordSession,
298 &[],
299 ),
300 route(
301 "POST",
302 "/repos/:owner/:name/pulls/:number/ready",
303 Op::MarkPullRequestReady,
304 &[],
305 ),
306 route(
307 "POST",
308 "/repos/:owner/:name/pulls/:number/close",
309 Op::ClosePullRequest,
310 &[],
311 ),
312 route(
313 "POST",
314 "/repos/:owner/:name/pulls/:number/merge",
315 Op::MergePullRequest,
316 &[],
317 ),
318];
319
320impl Route {
321 /// The names of the route's path parameters, in order.
322 pub fn params(&self) -> impl Iterator<Item = &'static str> {
323 self.path
324 .split('/')
325 .filter_map(|segment| segment.strip_prefix(':'))
326 }
327
328 /// The values of the path parameters, if `path` is this route's.
329 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
330 let mut values = Vec::new();
331 let mut actual = path.trim_end_matches('/').split('/');
332 for expected in self.path.split('/') {
333 let segment = actual.next()?;
334 match expected.strip_prefix(':') {
335 Some(name) if !segment.is_empty() => values.push((name, segment)),
336 Some(_) => return None,
337 None if expected == segment => {}
338 None => return None,
339 }
340 }
341 actual.next().is_none().then_some(values)
342 }
343}
344
345/// The route for a request, and the operation input it describes.
346///
347/// The input is the JSON body, overlaid with the query parameters the route
348/// reads and then with what the path names: `owner` and `name` become
349/// `repo`, and `number` becomes an integer.
350pub fn resolve(
351 method: &str,
352 path: &str,
353 query: &[(String, String)],
354 body: Value,
355) -> Option<(&'static Route, Value)> {
356 let (route, params) = ROUTES
357 .iter()
358 .filter(|route| route.method == method)
359 .find_map(|route| Some((route, route.matches(path)?)))?;
360
361 let mut input = match body {
362 Value::Object(fields) => fields,
363 _ => Map::new(),
364 };
365 for (name, key) in route.query {
366 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
367 input.insert((*key).to_owned(), Value::String(value.clone()));
368 }
369 }
370 let param = |wanted: &str| {
371 params
372 .iter()
373 .find(|(name, _)| *name == wanted)
374 .map(|(_, value)| *value)
375 };
376 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
377 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
378 }
379 for key in ["plan", "id", "workspace", "delivery"] {
380 if let Some(value) = param(key) {
381 input.insert(key.to_owned(), Value::String(value.to_owned()));
382 }
383 }
384 if let Some(number) = param("number") {
385 // Not a number: zero, which no issue or pull request has.
386 input.insert(
387 "number".to_owned(),
388 number.parse::<u32>().unwrap_or(0).into(),
389 );
390 }
391 Some((route, Value::Object(input)))
392}
393
394#[cfg(test)]
395mod tests {
396 use serde_json::json;
397
398 use super::*;
399
400 #[test]
401 fn a_path_resolves_to_its_operation_and_input() {
402 let (route, input) = resolve(
403 "POST",
404 "/repos/syntaqx/hello/pulls/14/merge",
405 &[],
406 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
407 )
408 .unwrap();
409 assert_eq!(route.op, Op::MergePullRequest);
410 // What the path names wins over the body.
411 assert_eq!(
412 input,
413 json!({ "keep_issue_open": true, "number": 14, "repo": "syntaqx/hello" })
414 );
415 }
416
417 #[test]
418 fn query_parameters_are_renamed() {
419 let query = [
420 ("q".to_owned(), "parser".to_owned()),
421 ("x".to_owned(), "y".to_owned()),
422 ];
423 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
424 assert_eq!(route.op, Op::ListRepos);
425 assert_eq!(input, json!({ "query": "parser" }));
426 }
427
428 #[test]
429 fn method_and_shape_must_match() {
430 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
431 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
432 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
433 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
434 }
435
436 #[test]
437 fn every_parameter_and_query_name_is_an_input() {
438 for route in ROUTES {
439 let properties = route.op.properties();
440 for (_, key) in route.query {
441 assert!(properties.contains_key(*key), "{}: {key}", route.path);
442 }
443 for name in route.params() {
444 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
445 || properties.contains_key(name);
446 assert!(covered, "{}: {name}", route.path);
447 }
448 }
449 }
450
451 #[test]
452 fn every_operation_has_a_route() {
453 for op in Op::ALL {
454 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
455 }
456 }
457}