g1t/apps/api/src/responses.rs

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