Skip to content

g1t/apps/api/src/responses.rs

288 lines13,667 bytesCodeBlame
1//! Every response the REST routes give, run through the converter the API
2//! sends them with, checked for `camelCase` that would leak out.
3//!
4//! The samples are the reference's example responses, put back into the
5//! `camelCase` the services send (as serde's `rename_all` writes it) and,
6//! where an operation returns a contract type, decoded into that type and
7//! encoded again, so that every field the type has is sent, not only the
8//! ones an example shows.
9
10use g1t_contracts::{access, actions, codeowners, integrations, repos, search, teams, webhooks, work};
11use g1t_kit::wire::{self, USER_KEYED};
12use serde::Serialize;
13use serde::de::DeserializeOwned;
14use serde_json::{Map, Value, json};
15
16use crate::openapi::document;
17use crate::operations::Op;
18
19/// A key as `#[serde(rename_all = "camelCase")]` writes it.
20fn camel_key(key: &str) -> String {
21 let mut out = String::with_capacity(key.len());
22 let mut upper = false;
23 for c in key.chars() {
24 if c == '_' {
25 upper = true;
26 } else if upper {
27 out.extend(c.to_uppercase());
28 upper = false;
29 } else {
30 out.push(c);
31 }
32 }
33 out
34}
35
36/// A response as the services send it: `camelCase`, but for the maps the
37/// converter passes through, which are data.
38fn as_services_send(value: &Value) -> Value {
39 match value {
40 Value::Object(fields) => {
41 let mut out = Map::new();
42 for (key, value) in fields {
43 let user_keyed = value.is_object()
44 && (USER_KEYED.contains(&key.as_str()) || key.starts_with("by_"));
45 let value = if user_keyed { value.clone() } else { as_services_send(value) };
46 // A `by_…` map keeps its name in the converter's spelling.
47 let key = if key.starts_with("by_") { key.clone() } else { camel_key(key) };
48 out.insert(key, value);
49 }
50 Value::Object(out)
51 }
52 Value::Array(items) => Value::Array(items.iter().map(as_services_send).collect()),
53 other => other.clone(),
54 }
55}
56
57/// `value` decoded as `T` and encoded again, as the service would send it.
58fn through<T: DeserializeOwned + Serialize>(op: Op, value: Value) -> Value {
59 let decoded: T = serde_json::from_value(value)
60 .unwrap_or_else(|error| panic!("{}: the example is not a {}: {error}", op.name(), std::any::type_name::<T>()));
61 serde_json::to_value(decoded).unwrap()
62}
63
64/// What the service behind an operation sends, from its example.
65fn sample(op: Op, example: &Value) -> Value {
66 // Types serde already writes in `snake_case`: a person, and who has
67 // access. Sent as they are.
68 let as_is = example.clone();
69 match op {
70 Op::Whoami => return through::<g1t_contracts::User>(op, as_is),
71 Op::ListCollaborators => return through::<access::RepoAccess>(op, as_is),
72 Op::AddCollaborator => return through::<access::Added>(op, as_is),
73 Op::UpdateCollaborator => return through::<access::Collaborator>(op, as_is),
74 Op::GetCollaboratorPermission => return through::<access::PermissionInfo>(op, as_is),
75 Op::ListRepoInvitations | Op::ListMyRepoInvitations => {
76 return through::<Vec<access::RepoInvitation>>(op, as_is);
77 }
78 Op::RevokeRepoInvitation | Op::AcceptRepoInvitation | Op::DeclineRepoInvitation => {
79 return through::<access::RepoInvitation>(op, as_is);
80 }
81 Op::ListOutsideCollaborators => return through::<Vec<access::OutsideCollaborator>>(op, as_is),
82 // Teams and code owners, also `snake_case`.
83 Op::ListTeams | Op::ListChildTeams | Op::ListUserTeams => return through::<Vec<teams::Team>>(op, as_is),
84 Op::GetTeam | Op::CreateTeam | Op::UpdateTeam | Op::SetTeamReviewAssignment => {
85 return through::<teams::Team>(op, as_is);
86 }
87 Op::ListTeamMembers => return through::<Vec<teams::TeamMember>>(op, as_is),
88 Op::SetTeamMember => return through::<teams::TeamMember>(op, as_is),
89 Op::ListTeamRepos => return through::<Vec<teams::TeamRepo>>(op, as_is),
90 Op::SetTeamRepo => return through::<teams::TeamRepo>(op, as_is),
91 Op::DeleteTeam | Op::RemoveTeamMember | Op::RemoveTeamRepo => return through::<bool>(op, as_is),
92 Op::GetCodeownersErrors => return through::<codeowners::CodeOwnersReport>(op, as_is),
93 // Built by the API itself, in `snake_case`.
94 Op::ListSecurityAlerts => return through::<Vec<crate::alerts::SecurityAlert>>(op, as_is),
95 Op::DismissSecurityAlert | Op::ReopenSecurityAlert => {
96 return through::<crate::alerts::SecurityAlert>(op, as_is);
97 }
98 _ => {}
99 }
100 let mut sent = as_services_send(example);
101 // A pull request's code owners are `snake_case` inside it.
102 if op == Op::GetPullRequest
103 && let Some(code_owners) = example.get("code_owners")
104 {
105 sent["codeOwners"] = code_owners.clone();
106 }
107 match op {
108 Op::GetWorkspace | Op::CreateWorkspace | Op::UpdateWorkspace => through::<g1t_contracts::identity::Workspace>(op, sent),
109 Op::ListRepos => through::<Vec<repos::Repo>>(op, sent),
110 Op::Search => through::<search::SearchResults>(op, sent),
111 Op::GetRepo
112 | Op::CreateRepo
113 | Op::UpdateRepo
114 | Op::TransferRepo
115 | Op::RenameRepo
116 | Op::RenameBranch
117 | Op::ArchiveRepo
118 | Op::UnarchiveRepo
119 | Op::SetRepoVisibility
120 | Op::RestoreRepo => through::<repos::Repo>(op, sent),
121 Op::DeleteRepo => through::<repos::DeletedRepo>(op, sent),
122 Op::ListDeletedRepos => through::<Vec<repos::DeletedRepo>>(op, sent),
123 Op::GetRepoSettings | Op::UpdateRepoSettings => through::<work::RepoSettings>(op, sent),
124 Op::ListCheckNames => through::<Vec<work::SeenCheck>>(op, sent),
125 Op::GetMergeQueue => through::<work::QueueView>(op, sent),
126 Op::ListIssues => through::<Vec<work::Issue>>(op, sent),
127 Op::CreateIssue | Op::UpdateIssue | Op::CloseIssue | Op::ReopenIssue => {
128 through::<work::Issue>(op, sent)
129 }
130 Op::GetIssue => through::<work::IssueDetail>(op, sent),
131 Op::Delegate => through::<work::Delegated>(op, sent),
132 Op::ListPullRequests => through::<Vec<work::Pull>>(op, sent),
133 Op::UpdatePullRequest => through::<work::Pull>(op, sent),
134 Op::ListLabels | Op::AddDefaultLabels | Op::ListIssueLabels => through::<Vec<work::Label>>(op, sent),
135 Op::CreateLabel | Op::UpdateLabel => through::<work::Label>(op, sent),
136 Op::ListMilestones => through::<Vec<work::Milestone>>(op, sent),
137 Op::CreateMilestone | Op::UpdateMilestone => through::<work::Milestone>(op, sent),
138 Op::GetMilestone => through::<work::MilestoneDetail>(op, sent),
139 Op::GetPullRequest => through::<work::PullDetail>(op, sent),
140 Op::MarkPullRequestReady
141 | Op::ClosePullRequest
142 | Op::MergePullRequest
143 | Op::AssignIssue
144 | Op::RequestReviewers
145 | Op::RemoveRequestedReviewers => {
146 through::<work::Pull>(op, sent)
147 }
148 Op::ListWorkflows => through::<Vec<actions::Workflow>>(op, sent),
149 Op::ListWorkflowRuns => through::<Vec<actions::WorkflowRun>>(op, sent),
150 Op::GetWorkflowRun => through::<actions::RunDetail>(op, sent),
151 Op::GetJobLogs => through::<actions::JobLog>(op, sent),
152 Op::DispatchWorkflow | Op::CancelWorkflowRun | Op::RerunWorkflowRun => {
153 through::<actions::WorkflowRun>(op, sent)
154 }
155 Op::ListActionsSecrets | Op::ListActionsVariables => through::<Vec<actions::Setting>>(op, sent),
156 Op::ListRunners => through::<Vec<g1t_contracts::runners::Runner>>(op, sent),
157 Op::ListRunnerGroups => through::<Vec<g1t_contracts::runners::RunnerGroup>>(op, sent),
158 Op::CreateRunnerGroup | Op::UpdateRunnerGroup => through::<g1t_contracts::runners::RunnerGroup>(op, sent),
159 Op::GetRunnerSettings | Op::UpdateRunnerSettings => through::<g1t_contracts::runners::RunnerSettings>(op, sent),
160 Op::CreateRunnerRegistrationToken => through::<g1t_contracts::runners::RegistrationToken>(op, sent),
161 Op::ListWebhooks => through::<Vec<webhooks::Hook>>(op, sent),
162 Op::ListIntegrations => through::<Vec<integrations::Connection>>(op, sent),
163 Op::GetModelRoutes | Op::SetModelRoutes => through::<Vec<integrations::ModelRoute>>(op, sent),
164 Op::ListEvents => through::<Vec<g1t_contracts::events::Event>>(op, sent),
165 Op::ListEmails | Op::AddEmail | Op::RemoveEmail | Op::UpdateEmailSettings => {
166 through::<g1t_contracts::accounts::AccountEmails>(op, sent)
167 }
168 Op::ListInvites => through::<g1t_contracts::identity::InvitesOverview>(op, sent),
169 Op::CreateInvite | Op::RevokeInvite | Op::InviteMember | Op::RevokeWorkspaceInvite => {
170 through::<g1t_contracts::identity::Invite>(op, sent)
171 }
172 Op::ListWorkspaceInvites => through::<Vec<g1t_contracts::identity::Invite>>(op, sent),
173 Op::ListNotifications => through::<g1t_contracts::inbox::InboxPage>(op, sent),
174 Op::GetNotificationThread | Op::MarkThreadRead | Op::MarkThreadDone | Op::SaveThread | Op::SnoozeThread => {
175 through::<g1t_contracts::inbox::InboxThread>(op, sent)
176 }
177 Op::GetThreadSubscription | Op::SetThreadSubscription | Op::DeleteThreadSubscription => {
178 through::<g1t_contracts::inbox::ThreadSubscription>(op, sent)
179 }
180 _ => sent,
181 }
182}
183
184/// Every key of `example`, as paths, outside the maps passed through.
185fn paths(value: &Value, path: &str, out: &mut Vec<String>) {
186 match value {
187 Value::Object(fields) => {
188 for (key, value) in fields {
189 let here = format!("{path}.{key}");
190 out.push(here.clone());
191 let user_keyed = value.is_object()
192 && (USER_KEYED.contains(&key.as_str()) || key.starts_with("by_"));
193 if !user_keyed {
194 paths(value, &here, out);
195 }
196 }
197 }
198 Value::Array(items) => {
199 for item in items {
200 paths(item, &format!("{path}[]"), out);
201 }
202 }
203 _ => {}
204 }
205}
206
207#[test]
208fn no_route_answers_with_camel_case() {
209 let document = document();
210 let (mut checked, mut converted) = (0, 0);
211 for (path, methods) in document["paths"].as_object().unwrap() {
212 for (method, operation) in methods.as_object().unwrap() {
213 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
214 let tool = operation["x-operation"].as_str().unwrap_or_default();
215 let Some(op) = Op::by_name(tool) else {
216 // Device sign-in, which is written in `snake_case` by hand.
217 assert!(wire::camel_case_keys(example).is_empty(), "{method} {path}");
218 continue;
219 };
220 let sample = sample(op, example);
221 converted += wire::camel_case_keys(&sample).len();
222 let sent = wire::snake_case(sample);
223 let leaked = wire::camel_case_keys(&sent);
224 assert!(leaked.is_empty(), "{method} {path} sends {leaked:?}");
225 // The reference shows what is sent: each of its names is one.
226 let (mut shown, mut real) = (Vec::new(), Vec::new());
227 paths(example, "", &mut shown);
228 paths(&sent, "", &mut real);
229 for name in shown {
230 assert!(real.contains(&name), "{method} {path}: the reference shows {name}, which is not sent");
231 }
232 checked += 1;
233 }
234 }
235 assert!(checked >= Op::ALL.len());
236 // The samples are in the services' spelling, so there was something to
237 // convert.
238 assert!(converted > 100, "{converted}");
239}
240
241#[test]
242fn every_route_has_a_sample() {
243 let document = document();
244 for route in crate::rest::ROUTES {
245 let path = route
246 .path
247 .split('/')
248 .map(|segment| match segment.strip_prefix(':') {
249 Some(name) => format!("{{{name}}}"),
250 None => segment.to_owned(),
251 })
252 .collect::<Vec<_>>()
253 .join("/");
254 let example = &document["paths"][&path][route.method.to_lowercase()]["responses"]["200"]
255 ["content"]["application/json"]["example"];
256 assert!(!example.is_null(), "{} {path}", route.method);
257 }
258}
259
260#[test]
261fn errors_and_reports_are_snake_case() {
262 let failure = g1t_contracts::Failure {
263 code: g1t_contracts::FailureCode::NotFound,
264 message: "No such endpoint.".to_owned(),
265 };
266 assert!(wire::camel_case_keys(&wire::snake_case(json!({ "error": failure }))).is_empty());
267}
268
269#[test]
270fn a_job_spec_keeps_github_s_spelling() {
271 let spec = json!({
272 "job": "job_1",
273 "spec": { "runs-on": "ubuntu-latest", "timeoutMinutes": 5 },
274 "workflow": { "env": { "nodeEnv": "x" } },
275 "github": { "eventName": "push", "headRef": "" },
276 "event": { "pull_request": { "headSha": "x" } },
277 "contexts": { "inputs": { "dryRun": true }, "matrix": { "nodeVersion": 20 } },
278 "checkout": { "ref": "main" },
279 "timeoutMinutes": 30,
280 "masks": [],
281 });
282 let sent = wire::snake_case_keeping(spec.clone(), crate::JOB_SPEC_AS_GIVEN);
283 assert_eq!(sent["timeout_minutes"], 30);
284 assert!(sent.get("timeoutMinutes").is_none());
285 for kept in ["spec", "workflow", "github", "event", "contexts", "checkout"] {
286 assert_eq!(sent[kept], spec[kept], "{kept}");
287 }
288}