Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion codegen/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,25 @@ use quote::quote;
use std::collections::HashMap;
use std::path::Path;

use crate::TagSchemas;
use crate::{
TagSchemas,
tag::{ResourceParents, resource_parents},
};

/// Writes the top-level API client file and tag accessors to the output directory.
pub fn generate_client_file(
out_path: &Path,
spec: &OpenAPI,
tag_schemas: &HashMap<String, TagSchemas>,
) -> Result<(), String> {
generate_client_with_parents(out_path, spec, tag_schemas, &resource_parents(spec)?)
}

pub(crate) fn generate_client_with_parents(
out_path: &Path,
spec: &OpenAPI,
tag_schemas: &HashMap<String, TagSchemas>,
parents: &ResourceParents,
) -> Result<(), String> {
let mut client_path = out_path.to_path_buf();
client_path.push("client.rs");
Expand All @@ -31,6 +43,9 @@ pub fn generate_client_file(
// Generate accessor methods for each tag client
let mut tag_methods = Vec::new();
for tag in sorted_tags {
if parents.contains_key(tag.as_str()) {
continue;
}
let snake_tag = tag.to_snake_case();
let method_name = Ident::new(&snake_tag, Span::call_site());
let client_module = Ident::new(&snake_tag, Span::call_site());
Expand Down
51 changes: 45 additions & 6 deletions codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,21 @@ pub struct Generator {
spec: OpenAPI,
out_path: PathBuf,
schemas_by_tag: SchemasByTag,
parents: tag::ResourceParents,
}

impl Generator {
/// Prepares a generator by loading derived schema metadata for later use.
pub fn new(spec: OpenAPI, out_path: impl Into<PathBuf>) -> Result<Self, String> {
let mut out_path = out_path.into();
out_path.push("src");
let schemas_by_tag = collect_schemas_by_tag(&spec)?;
let parents = tag::resource_parents(&spec)?;
let schemas_by_tag = tag::collect_schemas_with_parents(&spec, &parents)?;
Ok(Self {
spec,
out_path,
schemas_by_tag,
parents,
})
}

Expand Down Expand Up @@ -221,13 +224,19 @@ impl Generator {
)?;
let body_tokens =
body::generate_operation_bodies_with_registry(&self.spec, tag, &mut symbols)?;
let client_tokens = generate_tag_client_with_registry(&self.spec, tag, &mut symbols)?;
let client_tokens =
generate_tag_client_with_registry(&self.spec, tag, &self.parents, &mut symbols)?;
let event_tokens = generate_tag_event_tokens(&self.spec, tag)?;
let module_doc_comment = tag_description(&self.spec, tag)
.map(generate_module_doc_comment)
.unwrap_or_default();

let use_common = if use_common_schemas {
let grouped =
self.parents.contains_key(tag) || self.parents.values().any(|parent| parent.tag == tag);
let use_common = if use_common_schemas && grouped {
// Keep type imports through the parent module working for existing callers.
quote! { pub use super::common::*; }
} else if use_common_schemas {
quote! {
use super::common::*;
}
Expand Down Expand Up @@ -279,7 +288,12 @@ impl Generator {

fn generate_client_module(&self) -> Result<(), String> {
Self::log("[generate sdk] generating client.rs ...");
generate_client_file(&self.out_path, &self.spec, &self.schemas_by_tag.tag_schemas)
client::generate_client_with_parents(
&self.out_path,
&self.spec,
&self.schemas_by_tag.tag_schemas,
&self.parents,
)
}

fn generate_events_module(&self) -> Result<(), String> {
Expand Down Expand Up @@ -456,12 +470,13 @@ fn format_with_rustfmt(code: &str) -> Result<String, std::io::Error> {
pub fn generate_tag_client(spec: &OpenAPI, tag: &str) -> Result<TokenStream, String> {
let mut symbols = symbol::SymbolRegistry::new(tag.to_snake_case());
symbols.reserve("Client", "import `crate::client::Client`")?;
generate_tag_client_with_registry(spec, tag, &mut symbols)
generate_tag_client_with_registry(spec, tag, &tag::resource_parents(spec)?, &mut symbols)
}

fn generate_tag_client_with_registry(
spec: &OpenAPI,
tag: &str,
parents: &tag::ResourceParents,
symbols: &mut symbol::SymbolRegistry,
) -> Result<TokenStream, String> {
let client_type = Ident::new(
Expand All @@ -478,6 +493,29 @@ fn generate_tag_client_with_registry(
extra_items,
} = operation::generate_client_methods_with_registry(spec, tag, symbols)?;
let methods_tokens = quote! { #(#methods)* };
let mut children: Vec<_> = parents
.iter()
.filter(|(_, parent)| parent.tag == tag)
.collect();
children.sort_by_key(|(tag, _)| *tag);
let mut accessors = Vec::new();
for (child, parent) in children {
let accessor = Ident::new(&parent.accessor, Span::call_site());
let module = Ident::new(&child.to_snake_case(), Span::call_site());
let client = Ident::new(
&format!("{}Client", child.to_upper_camel_case()),
Span::call_site(),
);
let doc = schema::generate_doc_comment(&format!(
"Returns a client for the {child} API endpoints."
));
accessors.push(quote! {
#doc
pub fn #accessor(&self) -> super::#module::#client<'a> {
super::#module::#client::new(self.client)
}
});
}
let extra_items_tokens = if extra_items.is_empty() {
quote! {}
} else {
Expand Down Expand Up @@ -506,6 +544,7 @@ fn generate_tag_client_with_registry(
}

#methods_tokens
#(#accessors)*
}
})
}
Expand Down Expand Up @@ -687,7 +726,7 @@ mod tests {
&mut symbols,
)?;
body::generate_operation_bodies_with_registry(spec, tag, &mut symbols)?;
generate_tag_client_with_registry(spec, tag, &mut symbols)?;
generate_tag_client_with_registry(spec, tag, &tag::resource_parents(spec)?, &mut symbols)?;
Ok(())
}

Expand Down
9 changes: 7 additions & 2 deletions codegen/src/samples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ pub fn generate_code_samples(
sdk_version: impl Into<String>,
) -> Result<CodeSampleCatalog, String> {
let mut samples = Vec::new();
let types = values::SampleTypes::new(spec)?;
let parents = crate::tag::resource_parents(spec)?;
let schemas = crate::tag::collect_schemas_with_parents(spec, &parents)?;
let types = values::SampleTypes::new(spec, &schemas)?;

for (path, path_item) in spec.paths.iter().flatten() {
for (http_method, operation) in crate::operations_for_path_item(path_item) {
Expand All @@ -85,6 +87,7 @@ pub fn generate_code_samples(
.first()
.ok_or_else(|| format!("operation {operation_id} is missing a tag"))?;

let accessor_path = crate::tag::resource_path(&parents, tag);
for example in request_examples(spec, operation) {
let id = match &example.name {
Some(name) => format!("{operation_id}.{name}"),
Expand All @@ -98,6 +101,7 @@ pub fn generate_code_samples(
path_item,
operation,
tag,
&accessor_path,
example.value.as_ref(),
&types,
)?;
Expand Down Expand Up @@ -224,6 +228,7 @@ fn render_program(
path_item: &openapiv3::PathItem,
operation: &Operation,
tag: &str,
accessor_path: &str,
example: Option<&Value>,
types: &values::SampleTypes,
) -> Result<String, String> {
Expand Down Expand Up @@ -278,7 +283,7 @@ fn render_program(

let arguments = arguments.join(", ");
let source = format!(
"use sumup::{{Authorization, Client}};\n\n#[tokio::main]\nasync fn main() {{\n let client = Client::default()\n .with_authorization(Authorization::api_key(\"sup_sk_test_...\"));\n{body_declaration}\n let response = client\n .{resource}()\n .{method}({arguments})\n .await\n .expect(\"{method} request failed\");\n\n println!(\"{{response:#?}}\");\n}}\n"
"use sumup::{{Authorization, Client}};\n\n#[tokio::main]\nasync fn main() {{\n let client = Client::default()\n .with_authorization(Authorization::api_key(\"sup_sk_test_...\"));\n{body_declaration}\n let response = client\n .{accessor_path}()\n .{method}({arguments})\n .await\n .expect(\"{method} request failed\");\n\n println!(\"{{response:#?}}\");\n}}\n"
);
let syntax = syn::parse_file(&source).map_err(|error| {
format!(
Expand Down
3 changes: 1 addition & 2 deletions codegen/src/samples/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ pub(super) struct SampleTypes {
}

impl SampleTypes {
pub(super) fn new(spec: &Spec) -> Result<Self, String> {
let schemas = crate::collect_schemas_by_tag(spec)?;
pub(super) fn new(spec: &Spec, schemas: &crate::SchemasByTag) -> Result<Self, String> {
let mut types = Self {
modules: HashMap::new(),
};
Expand Down
142 changes: 138 additions & 4 deletions codegen/src/tag.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,100 @@
use std::collections::{HashMap, HashSet};

use heck::ToSnakeCase;
use oas3::{
Spec,
spec::{ObjectOrReference, ObjectSchema, ParameterIn, Schema},
};

#[derive(serde::Deserialize)]
struct TagGroup {
name: String,
tags: Vec<String>,
}

pub(crate) struct ResourceParent {
pub tag: String,
pub accessor: String,
}

pub(crate) type ResourceParents = HashMap<String, ResourceParent>;

pub(crate) fn resource_parents(spec: &Spec) -> Result<ResourceParents, String> {
let Some(extension) = spec.extensions.get("tagGroups") else {
return Ok(HashMap::new());
};
let groups: Vec<TagGroup> = serde_json::from_value(extension.clone())
.map_err(|err| format!("decode x-tagGroups: {err}"))?;
let known: HashMap<_, _> = spec
.tags
.iter()
.map(|tag| (tag.name.as_str(), tag))
.collect();
let mut parents = ResourceParents::new();
for group in groups {
if !known.contains_key(group.name.as_str()) {
continue;
}
for child in group.tags {
let Some(tag) = known.get(child.as_str()) else {
continue;
};
if child == group.name || parents.contains_key(&child) {
continue;
}
let mut ancestor = Some(group.name.as_str());
while let Some(name) = ancestor {
if name == child {
return Err(format!("tag hierarchy contains a cycle at {child}"));
}
ancestor = parents.get(name).map(|parent| parent.tag.as_str());
}
let accessor = tag
.extensions
.get("displayName")
.and_then(serde_json::Value::as_str)
.unwrap_or(&child)
.to_snake_case();
parents.insert(
child,
ResourceParent {
tag: group.name.clone(),
accessor,
},
);
}
}
let mut active = HashSet::new();
for item in spec.paths.iter().flat_map(|paths| paths.values()) {
for (_, operation) in crate::operations_for_path_item(item) {
for tag in &operation.tags {
let mut child = tag.as_str();
while let Some(parent) = parents.get(child) {
if !active.insert(child.to_string()) {
break;
}
child = &parent.tag;
}
}
}
}
parents.retain(|child, _| active.contains(child));
Ok(parents)
}

pub(crate) fn resource_path(parents: &ResourceParents, tag: &str) -> String {
match parents.get(tag) {
Some(parent) => format!(
"{}().{}",
resource_path(parents, &parent.tag),
parent.accessor
),
None => tag.to_snake_case(),
}
}

/// Holds the schemas associated with a single OpenAPI tag.
#[derive(Default)]
pub struct TagSchemas {
pub all_schemas: HashSet<String>,
pub error_schemas: HashSet<String>,
Expand All @@ -20,6 +109,13 @@ pub struct SchemasByTag {

/// Collects schemas referenced by each tag and identifies shared/common schemas.
pub fn collect_schemas_by_tag(spec: &Spec) -> Result<SchemasByTag, String> {
collect_schemas_with_parents(spec, &resource_parents(spec)?)
}

pub(crate) fn collect_schemas_with_parents(
spec: &Spec,
parents: &ResourceParents,
) -> Result<SchemasByTag, String> {
let mut tag_schemas: HashMap<String, TagSchemas> = HashMap::new();

for path_item in spec.paths.iter().flat_map(|paths| paths.values()) {
Expand All @@ -31,10 +127,7 @@ pub fn collect_schemas_by_tag(spec: &Spec) -> Result<SchemasByTag, String> {
};

for tag in tags {
let tag_data = tag_schemas.entry(tag).or_insert_with(|| TagSchemas {
all_schemas: HashSet::new(),
error_schemas: HashSet::new(),
});
let tag_data = tag_schemas.entry(tag).or_default();

if let Some(request_body_ref) = &operation.request_body {
let request_body = crate::body::resolve_request_body(spec, request_body_ref)?;
Expand Down Expand Up @@ -81,6 +174,10 @@ pub fn collect_schemas_by_tag(spec: &Spec) -> Result<SchemasByTag, String> {
}
}

for parent in parents.values() {
tag_schemas.entry(parent.tag.clone()).or_default();
}

let Some(components) = &spec.components else {
return Ok(SchemasByTag {
tag_schemas,
Expand Down Expand Up @@ -199,6 +296,43 @@ fn collect_schema_references(schema: &ObjectSchema, schemas: &mut HashSet<String
mod tests {
use super::*;

#[test]
fn reader_checkout_uses_its_annotated_name_on_the_nested_resource() {
let spec: Spec = serde_json::from_value(serde_json::json!({
"openapi": "3.1.0",
"info": {"title": "Readers", "version": "1.0.0"},
"tags": [
{"name": "Readers"},
{"name": "ReaderCheckouts", "x-displayName": "Checkouts"}
],
"x-tagGroups": [{"name": "Readers", "tags": ["ReaderCheckouts"]}],
"paths": {"/readers/checkouts": {"post": {
"operationId": "CreateReaderCheckout",
"tags": ["ReaderCheckouts"],
"x-codegen": {"method_name": "create"},
"responses": {"204": {"description": "OK"}}
}}}
}))
.unwrap();

let parents = resource_parents(&spec).unwrap();
assert_eq!(
resource_path(&parents, "ReaderCheckouts"),
"readers().checkouts"
);
let schemas = collect_schemas_by_tag(&spec).unwrap();
assert!(schemas.tag_schemas.contains_key("Readers"));
let parent = crate::generate_tag_client(&spec, "Readers")
.unwrap()
.to_string();
assert!(parent.contains("pub fn checkouts"));
assert!(!parent.contains("pub async fn create"));
let child = crate::generate_tag_client(&spec, "ReaderCheckouts")
.unwrap()
.to_string();
assert!(child.contains("pub async fn create ("));
}

#[test]
fn tracks_common_and_untagged_schemas() {
let spec: Spec = serde_json::from_value(serde_json::json!({
Expand Down