g1t/apps/api/src/responses.rs

253 lines11,525 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, integrations, repos, search, 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 // Built by the API itself, in `snake_case`.
83 Op::ListSecurityAlerts => return through::<Vec<crate::alerts::SecurityAlert>>(op, as_is),
84 Op::DismissSecurityAlert | Op::ReopenSecurityAlert => {
85 return through::<crate::alerts::SecurityAlert>(op, as_is);
86 }
87 _ => {}
88 }
89 let sent = as_services_send(example);
90 match op {
91 Op::CreateWorkspace | Op::UpdateWorkspace => through::<g1t_contracts::identity::Workspace>(op, sent),
92 Op::ListRepos => through::<Vec<repos::Repo>>(op, sent),
93 Op::Search => through::<search::SearchResults>(op, sent),
94 Op::GetRepo
95 | Op::CreateRepo
96 | Op::UpdateRepo
97 | Op::TransferRepo
98 | Op::RenameRepo
99 | Op::RenameBranch
100 | Op::ArchiveRepo
101 | Op::UnarchiveRepo
102 | Op::SetRepoVisibility
103 | Op::RestoreRepo => through::<repos::Repo>(op, sent),
104 Op::DeleteRepo => through::<repos::DeletedRepo>(op, sent),
105 Op::ListDeletedRepos => through::<Vec<repos::DeletedRepo>>(op, sent),
106 Op::GetRepoSettings | Op::UpdateRepoSettings => through::<work::RepoSettings>(op, sent),
107 Op::ListCheckNames => through::<Vec<work::SeenCheck>>(op, sent),
108 Op::GetMergeQueue => through::<work::QueueView>(op, sent),
109 Op::ListIssues => through::<Vec<work::Issue>>(op, sent),
110 Op::CreateIssue | Op::UpdateIssue | Op::CloseIssue | Op::ReopenIssue => {
111 through::<work::Issue>(op, sent)
112 }
113 Op::GetIssue => through::<work::IssueDetail>(op, sent),
114 Op::Delegate => through::<work::Delegated>(op, sent),
115 Op::ListPullRequests => through::<Vec<work::Pull>>(op, sent),
116 Op::GetPullRequest => through::<work::PullDetail>(op, sent),
117 Op::MarkPullRequestReady | Op::ClosePullRequest | Op::MergePullRequest | Op::AssignIssue => {
118 through::<work::Pull>(op, sent)
119 }
120 Op::ListWorkflows => through::<Vec<actions::Workflow>>(op, sent),
121 Op::ListWorkflowRuns => through::<Vec<actions::WorkflowRun>>(op, sent),
122 Op::GetWorkflowRun => through::<actions::RunDetail>(op, sent),
123 Op::GetJobLogs => through::<actions::JobLog>(op, sent),
124 Op::DispatchWorkflow | Op::CancelWorkflowRun | Op::RerunWorkflowRun => {
125 through::<actions::WorkflowRun>(op, sent)
126 }
127 Op::ListActionsSecrets | Op::ListActionsVariables => through::<Vec<actions::Setting>>(op, sent),
128 Op::ListRunners => through::<Vec<g1t_contracts::runners::Runner>>(op, sent),
129 Op::ListRunnerGroups => through::<Vec<g1t_contracts::runners::RunnerGroup>>(op, sent),
130 Op::CreateRunnerGroup | Op::UpdateRunnerGroup => through::<g1t_contracts::runners::RunnerGroup>(op, sent),
131 Op::GetRunnerSettings | Op::UpdateRunnerSettings => through::<g1t_contracts::runners::RunnerSettings>(op, sent),
132 Op::CreateRunnerRegistrationToken => through::<g1t_contracts::runners::RegistrationToken>(op, sent),
133 Op::ListWebhooks => through::<Vec<webhooks::Hook>>(op, sent),
134 Op::ListIntegrations => through::<Vec<integrations::Connection>>(op, sent),
135 Op::GetModelRoutes | Op::SetModelRoutes => through::<Vec<integrations::ModelRoute>>(op, sent),
136 Op::ListEvents => through::<Vec<g1t_contracts::events::Event>>(op, sent),
137 Op::ListEmails | Op::AddEmail | Op::RemoveEmail | Op::UpdateEmailSettings => {
138 through::<g1t_contracts::accounts::AccountEmails>(op, sent)
139 }
140 Op::ListInvites => through::<g1t_contracts::identity::InvitesOverview>(op, sent),
141 Op::CreateInvite | Op::RevokeInvite | Op::InviteMember | Op::RevokeWorkspaceInvite => {
142 through::<g1t_contracts::identity::Invite>(op, sent)
143 }
144 Op::ListWorkspaceInvites => through::<Vec<g1t_contracts::identity::Invite>>(op, sent),
145 _ => sent,
146 }
147}
148
149/// Every key of `example`, as paths, outside the maps passed through.
150fn paths(value: &Value, path: &str, out: &mut Vec<String>) {
151 match value {
152 Value::Object(fields) => {
153 for (key, value) in fields {
154 let here = format!("{path}.{key}");
155 out.push(here.clone());
156 let user_keyed = value.is_object()
157 && (USER_KEYED.contains(&key.as_str()) || key.starts_with("by_"));
158 if !user_keyed {
159 paths(value, &here, out);
160 }
161 }
162 }
163 Value::Array(items) => {
164 for item in items {
165 paths(item, &format!("{path}[]"), out);
166 }
167 }
168 _ => {}
169 }
170}
171
172#[test]
173fn no_route_answers_with_camel_case() {
174 let document = document();
175 let (mut checked, mut converted) = (0, 0);
176 for (path, methods) in document["paths"].as_object().unwrap() {
177 for (method, operation) in methods.as_object().unwrap() {
178 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
179 let tool = operation["x-operation"].as_str().unwrap_or_default();
180 let Some(op) = Op::by_name(tool) else {
181 // Device sign-in, which is written in `snake_case` by hand.
182 assert!(wire::camel_case_keys(example).is_empty(), "{method} {path}");
183 continue;
184 };
185 let sample = sample(op, example);
186 converted += wire::camel_case_keys(&sample).len();
187 let sent = wire::snake_case(sample);
188 let leaked = wire::camel_case_keys(&sent);
189 assert!(leaked.is_empty(), "{method} {path} sends {leaked:?}");
190 // The reference shows what is sent: each of its names is one.
191 let (mut shown, mut real) = (Vec::new(), Vec::new());
192 paths(example, "", &mut shown);
193 paths(&sent, "", &mut real);
194 for name in shown {
195 assert!(real.contains(&name), "{method} {path}: the reference shows {name}, which is not sent");
196 }
197 checked += 1;
198 }
199 }
200 assert!(checked >= Op::ALL.len());
201 // The samples are in the services' spelling, so there was something to
202 // convert.
203 assert!(converted > 100, "{converted}");
204}
205
206#[test]
207fn every_route_has_a_sample() {
208 let document = document();
209 for route in crate::rest::ROUTES {
210 let path = route
211 .path
212 .split('/')
213 .map(|segment| match segment.strip_prefix(':') {
214 Some(name) => format!("{{{name}}}"),
215 None => segment.to_owned(),
216 })
217 .collect::<Vec<_>>()
218 .join("/");
219 let example = &document["paths"][&path][route.method.to_lowercase()]["responses"]["200"]
220 ["content"]["application/json"]["example"];
221 assert!(!example.is_null(), "{} {path}", route.method);
222 }
223}
224
225#[test]
226fn errors_and_reports_are_snake_case() {
227 let failure = g1t_contracts::Failure {
228 code: g1t_contracts::FailureCode::NotFound,
229 message: "No such endpoint.".to_owned(),
230 };
231 assert!(wire::camel_case_keys(&wire::snake_case(json!({ "error": failure }))).is_empty());
232}
233
234#[test]
235fn a_job_spec_keeps_github_s_spelling() {
236 let spec = json!({
237 "job": "job_1",
238 "spec": { "runs-on": "ubuntu-latest", "timeoutMinutes": 5 },
239 "workflow": { "env": { "nodeEnv": "x" } },
240 "github": { "eventName": "push", "headRef": "" },
241 "event": { "pull_request": { "headSha": "x" } },
242 "contexts": { "inputs": { "dryRun": true }, "matrix": { "nodeVersion": 20 } },
243 "checkout": { "ref": "main" },
244 "timeoutMinutes": 30,
245 "masks": [],
246 });
247 let sent = wire::snake_case_keeping(spec.clone(), crate::JOB_SPEC_AS_GIVEN);
248 assert_eq!(sent["timeout_minutes"], 30);
249 assert!(sent.get("timeoutMinutes").is_none());
250 for kept in ["spec", "workflow", "github", "event", "contexts", "checkout"] {
251 assert_eq!(sent[kept], spec[kept], "{kept}");
252 }
253}