Skip to content

g1t/apps/api/src/responses.rs

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