flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/responses.rs

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