olai_codegen/analysis/types.rs
1use std::collections::HashSet;
2
3use syn::Ident;
4
5use crate::error::{Error, Result};
6use crate::google::api::{ResourceDescriptor, http_rule::Pattern};
7use crate::parsing::types::UnifiedType;
8use crate::parsing::{CodeGenMetadata, HttpPattern, MethodMetadata, OneofVariant};
9use crate::utils::last_segment;
10use crate::utils::strings::operation_to_method_name;
11
12/// The Operation a method is performing
13///
14/// There are standard CRUD operations, as well as custom operations.
15///
16/// Standard operations on collections are:
17/// - List: Retrieve a list of resources
18/// - Create: Create a new resource
19///
20/// Standard operations on individual resources are:
21/// - Get: Retrieve a single resource
22/// - Update: Update an existing resource
23/// - Delete: Delete a resource
24///
25/// Custom operations are:
26/// - Custom(Pattern): custom HTTP operation
27#[derive(Debug, Clone, PartialEq)]
28pub enum RequestType {
29 List,
30 Create,
31 Get,
32 Update,
33 Delete,
34 Custom(Pattern),
35}
36
37/// Where a method sits relative to a resource, independent of its CRUD verb.
38///
39/// Computed once during analysis from the method's [`RequestType`], name, and whether the owning
40/// service manages a `google.api.resource`. This makes the scoped/flat and collection/instance
41/// decisions explicit on the IR, so emitters don't re-derive them.
42///
43/// The three cases map onto the binding layout:
44/// - [`MethodShape::CollectionScoped`] and [`MethodShape::InstanceScoped`] both belong to a
45/// resource-scoped service; collection methods live on the root client, instance methods on the
46/// per-resource scoped client.
47/// - [`MethodShape::Unbound`] belongs to a resource-less service; every method lives on the root
48/// client and passes all params (the "flat" lowering).
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum MethodShape {
51 /// Collection-style operation on a resource service (list / create / factory RPC). Lives on the
52 /// root/aggregate client and passes every param.
53 CollectionScoped,
54 /// Instance operation on a resource service (get / update / delete / resource-targeted custom).
55 /// Lives on the per-resource scoped client, which already holds the path params.
56 InstanceScoped,
57 /// Method of a resource-less ("flat") service. Lives on the root client and passes every param,
58 /// including path params.
59 Unbound,
60}
61
62/// The structural template a language binding uses to emit a method, independent of language.
63///
64/// Collapses the per-binding `match request_type { … }` dispatch (which Python, Node, and
65/// TypeScript each repeated identically) into a single analysis decision. Each variant corresponds
66/// to one emit-shape helper every binding already has (`*_list_method_impl`,
67/// `*_create_method_impl`, `*_get_update_method_impl`, `*_delete_method_impl`).
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum EmitShape {
70 /// Streamed/collected list — returns the repeated item type. (`List`, or a custom `GET` named
71 /// `List*`.)
72 List,
73 /// Factory/create — body in, returns a (possibly unrelated) response message. (`Create`, or a
74 /// collection-style custom `POST`/`PATCH` factory like `Generate*`.)
75 Create,
76 /// Get-or-update — path params (+ optional body), returns the resource/response. (`Get`,
77 /// `Update`, a resource-targeted custom `POST`/`PATCH`, or any other custom verb on a flat
78 /// service.)
79 GetUpdate,
80 /// Delete — path params, no response. (`Delete`.)
81 Delete,
82}
83
84/// Classify a method's [`EmitShape`] from its request type and proto name.
85///
86/// The single place the emit shape is decided, for every client and binding emitter.
87///
88/// `is_collection` (from [`is_collection_method`]) only distinguishes a collection-style custom
89/// `POST`/`PATCH` factory (→ [`EmitShape::Create`]) from a resource-targeted custom `POST`/`PATCH`
90/// (→ [`EmitShape::GetUpdate`]). Note a resource-less `Custom(Get)` named `List*` is **not**
91/// List-shaped here: it is [`EmitShape::GetUpdate`] (returning the full response message, keeping
92/// `page_token`), and only a true
93/// [`RequestType::List`] gets streamed/`List` emit. Collection *routing* (which client a method
94/// lands on) is a separate decision driven by [`is_collection_method`].
95pub(crate) fn emit_shape(request_type: &RequestType, is_collection: bool) -> EmitShape {
96 match request_type {
97 RequestType::List => EmitShape::List,
98 RequestType::Create => EmitShape::Create,
99 RequestType::Delete => EmitShape::Delete,
100 RequestType::Get | RequestType::Update => EmitShape::GetUpdate,
101 // A collection-style custom POST/PATCH is a factory (Create-shaped); every other custom verb
102 // — including a `Custom(Get)` named `List*` — is GetUpdate-shaped (path + optional body,
103 // return the full response).
104 RequestType::Custom(Pattern::Post(_) | Pattern::Patch(_)) if is_collection => {
105 EmitShape::Create
106 }
107 RequestType::Custom(_) => EmitShape::GetUpdate,
108 }
109}
110
111/// A method that was skipped during analysis due to incomplete metadata.
112#[derive(Debug, Clone)]
113pub struct SkippedMethod {
114 /// Fully-qualified name of the service containing the skipped method.
115 pub service_name: String,
116 /// Name of the skipped method (e.g. `"GetCatalog"`).
117 pub method_name: String,
118 /// Human-readable reason the method was skipped (e.g. `"missing HTTP annotation"`).
119 pub reason: String,
120}
121
122/// High-level plan for what code to generate
123#[derive(Debug)]
124pub struct GenerationPlan {
125 /// Services to generate handlers for
126 pub services: Vec<ServicePlan>,
127 /// Methods that were excluded from the plan due to incomplete metadata.
128 ///
129 /// Callers can inspect this list to distinguish "service has zero methods" from "all methods
130 /// were skipped due to missing HTTP annotations", and to surface actionable warnings.
131 pub skipped_methods: Vec<SkippedMethod>,
132}
133
134/// Plan for generating code for a single service
135#[derive(Debug, Clone)]
136pub struct ServicePlan {
137 /// Service name (e.g., "CatalogsService")
138 pub service_name: String,
139 /// Handler trait name (e.g., "CatalogHandler")
140 pub handler_name: String,
141 /// Base URL path for this service (e.g., "catalogs")
142 pub base_path: String,
143 /// Proto package name (e.g., "example.catalogs.v1")
144 pub package: String,
145 /// Methods to generate for this service
146 pub methods: Vec<MethodPlan>,
147 /// Resources managed by this service
148 pub managed_resources: Vec<ManagedResource>,
149 /// Documentation from protobuf service comments
150 pub documentation: Option<String>,
151 /// Ancestor chain for this service's managed resource, derived cross-service from
152 /// `resource_reference { child_type }` annotations.
153 ///
154 /// Entries are ordered **root-first** (shallowest ancestor first). For example, for
155 /// a Table service this would be `[catalog_name (depth 0), schema_name (depth 1)]`.
156 ///
157 /// Empty when no `resource_reference` annotations are present — codegen falls back to
158 /// naming heuristics in that case.
159 pub hierarchy: Vec<ResourceHierarchy>,
160 /// Parameter names for this service's resource accessor on the aggregate client, e.g.
161 /// `["catalog_name", "schema_name"]` for a nested Schema or `["name"]` for a flat Catalog.
162 ///
163 /// The trailing element is the resource's own `<singular>_name`; any preceding elements are
164 /// ancestor identifiers. A list of length > 1 means the resource is *nested* and its full name
165 /// is the dot-joined components.
166 ///
167 /// `None` for resource-less services (no accessor is generated). Computed once during analysis
168 /// (Phase 2, after `hierarchy` is populated) so the four accessor emitters — Rust aggregate,
169 /// Python, Node, TypeScript — all read the same list instead of each re-deriving it.
170 pub resource_accessor_params: Option<Vec<String>>,
171 /// Direct child resources of this service's managed resource, used to generate child-navigation
172 /// accessors (e.g. `catalog.schema(name)`) and child-create methods (e.g. `catalog.create_schema`)
173 /// on the scoped client.
174 ///
175 /// A resource C is a *direct child* of P when C's [`Self::resource_accessor_params`] equals P's
176 /// plus exactly one additional trailing component (P's params are a prefix of C's, and
177 /// `C.len() == P.len() + 1`). Sorted by `child_singular`. Empty for leaf or flat resources.
178 /// Computed in Phase 2 of `analyze_metadata` after every service's accessor params are known.
179 pub direct_children: Vec<ChildLink>,
180}
181
182/// A direct child resource of a parent resource, for generating child-navigation and child-create
183/// methods on the parent's scoped client. See [`ServicePlan::direct_children`].
184#[derive(Debug, Clone)]
185pub struct ChildLink {
186 /// The child resource singular — used as the navigation accessor method name (e.g. `schema`).
187 pub child_singular: String,
188 /// The child service's `base_path` / module segment (e.g. `schemas`), used to reference the
189 /// child's generated clients as `crate::codegen::<base_path>::…`.
190 pub child_base_path: String,
191 /// The child's full accessor params (ancestors + own leaf), e.g. `["catalog_name","schema_name"]`.
192 /// The leading entries equal the parent's accessor params (the prefix relation); the final entry
193 /// is the child's own name component.
194 pub child_accessor_params: Vec<String>,
195}
196
197/// Plan for generating code for a single method
198#[derive(Debug, Clone)]
199pub struct MethodPlan {
200 /// Original method metadata
201 pub metadata: MethodMetadata,
202 /// Rust function name for the handler method
203 pub handler_function_name: String,
204 /// Pre-parsed HTTP URL pattern
205 pub http_pattern: HttpPattern,
206 /// HTTP method string for routing (e.g., "GET", "POST")
207 pub http_method: String,
208 /// Parameters passed to the method (path, query, and body)
209 pub parameters: Vec<RequestParam>,
210 /// Whether this method returns a response body
211 pub has_response: bool,
212 /// Request type for this method
213 pub request_type: RequestType,
214 /// The resource type name returned by this method (if any)
215 pub output_resource_type: Option<String>,
216 /// Whether the HTTP request carries a JSON body (create / update / custom POST·PATCH).
217 ///
218 /// Derived once from [`RequestType`] so the client emitter doesn't re-match the enum to
219 /// decide whether to attach `.json(request)`.
220 pub has_request_body: bool,
221 /// Whether the Axum server extractor reads from request *parts* (path/query only) rather
222 /// than the body — i.e. this is a `FromRequestParts` method, not `FromRequest`.
223 ///
224 /// Derived once from [`RequestType`] so the server emitter (extractor selection and the
225 /// `RequestPartsExt` import) doesn't re-match the enum.
226 pub needs_request_parts: bool,
227 /// The verb name to call on a resource-scoped client (`get` / `update` / `delete`), or
228 /// `None` for methods that are not standard instance verbs.
229 ///
230 /// Derived once from [`RequestType`]; the scoped binding call uses this instead of
231 /// re-deciding the verb from the enum (see `MethodPlan::resource_client_method`).
232 pub scoped_verb: Option<String>,
233 /// Where this method sits relative to a resource (collection / instance / unbound).
234 ///
235 /// Assigned in `analyze_service` once the owning service's managed resources are known, so it
236 /// reflects both the method's verb/name shape and whether the service is resource-scoped.
237 pub shape: MethodShape,
238 /// Whether this method has a `google.api.http` route.
239 ///
240 /// Analysis is protocol-agnostic: every method gets a plan. A method without an HTTP
241 /// annotation still produces a plan (with all request fields as body, no path/query) so the
242 /// ConnectRPC emitter can use it — but it has no REST route, so the REST client/handler
243 /// emitters skip it. `true` for methods with an HTTP annotation, `false` otherwise.
244 pub has_http_route: bool,
245}
246
247impl MethodPlan {
248 pub fn path_parameters(&self) -> impl Iterator<Item = &PathParam> {
249 self.parameters.iter().filter_map(|param| match param {
250 RequestParam::Path(path_param) => Some(path_param),
251 _ => None,
252 })
253 }
254
255 /// Whether the REST client formats path parameters into the URL.
256 pub fn formats_path_values(&self) -> bool {
257 self.has_http_route
258 && self.path_parameters().next().is_some()
259 && !self.http_pattern.parameter_names().is_empty()
260 }
261
262 pub fn query_parameters(&self) -> impl Iterator<Item = &QueryParam> {
263 self.parameters.iter().filter_map(|param| match param {
264 RequestParam::Query(query_param) => Some(query_param),
265 _ => None,
266 })
267 }
268
269 pub fn body_fields(&self) -> impl Iterator<Item = &BodyField> {
270 self.parameters.iter().filter_map(|param| match param {
271 RequestParam::Body(body_field) => Some(body_field),
272 _ => None,
273 })
274 }
275}
276
277#[derive(Debug, Clone)]
278pub enum RequestParam {
279 Path(PathParam),
280 Query(QueryParam),
281 Body(BodyField),
282}
283
284impl RequestParam {
285 pub fn name(&self) -> &str {
286 match self {
287 RequestParam::Path(param) => ¶m.name,
288 RequestParam::Query(param) => ¶m.name,
289 RequestParam::Body(param) => ¶m.name,
290 }
291 }
292
293 pub fn field_type(&self) -> &UnifiedType {
294 match self {
295 RequestParam::Path(param) => ¶m.field_type,
296 RequestParam::Query(param) => ¶m.field_type,
297 RequestParam::Body(param) => ¶m.field_type,
298 }
299 }
300
301 pub fn field_ident(&self) -> Ident {
302 crate::utils::field_ident(self.name())
303 }
304
305 pub fn is_optional(&self) -> bool {
306 match self {
307 RequestParam::Path(_) => false,
308 RequestParam::Query(param) => param.is_optional(),
309 RequestParam::Body(param) => param.is_optional(),
310 }
311 }
312
313 pub fn is_path_param(&self) -> bool {
314 matches!(self, RequestParam::Path(_))
315 }
316
317 pub fn documentation(&self) -> Option<&str> {
318 match self {
319 RequestParam::Path(param) => param.documentation.as_deref(),
320 RequestParam::Query(param) => param.documentation.as_deref(),
321 RequestParam::Body(param) => param.documentation.as_deref(),
322 }
323 }
324}
325
326/// A path parameter in a URL template
327#[derive(Debug, Clone)]
328pub struct PathParam {
329 /// Field name in the request struct (e.g., "full_name")
330 pub name: String,
331 /// Parsed type of the path parameter
332 pub field_type: UnifiedType,
333 /// Documentation from protobuf field comments
334 pub documentation: Option<String>,
335}
336
337impl From<PathParam> for RequestParam {
338 fn from(param: PathParam) -> Self {
339 RequestParam::Path(param)
340 }
341}
342
343/// A query parameter for HTTP requests
344#[derive(Debug, Clone)]
345pub struct QueryParam {
346 /// Parameter name
347 pub name: String,
348 /// The `json_name` of the field (see [`QueryParam::key`]).
349 pub json_name: Option<String>,
350 /// Parsed type of the query parameter
351 pub field_type: UnifiedType,
352 /// Documentation from protobuf field comments
353 pub documentation: Option<String>,
354 /// Resource reference annotation, if present on the corresponding proto field.
355 ///
356 /// - `child_type` non-empty: this param scopes a parent of that resource type
357 /// (e.g. `catalog_name` with `child_type = "example.io/Schema"`).
358 /// - `r#type` non-empty: this param directly identifies a resource of that type.
359 pub resource_reference: Option<crate::google::api::ResourceReference>,
360}
361
362impl QueryParam {
363 /// The query-string key: the explicit `json_name`, else the lowerCamelCase JSON name with
364 /// `json_names`, else the proto name.
365 pub fn key(&self, json_names: bool) -> std::borrow::Cow<'_, str> {
366 match &self.json_name {
367 Some(json) => json.into(),
368 None if json_names => crate::utils::strings::lower_camel(&self.name).into(),
369 None => self.name.as_str().into(),
370 }
371 }
372
373 /// Denotes if the parameter is optional
374 pub fn is_optional(&self) -> bool {
375 self.field_type.is_optional
376 }
377}
378
379impl From<QueryParam> for RequestParam {
380 fn from(param: QueryParam) -> Self {
381 RequestParam::Query(param)
382 }
383}
384
385/// A body field that should be extracted from the request body
386#[derive(Debug, Clone)]
387pub struct BodyField {
388 /// Field name
389 pub name: String,
390 /// Parsed type of the body parameter
391 pub field_type: UnifiedType,
392 /// Whether this field is a repeated (Vec) type
393 pub repeated: bool,
394 /// Whether the field is explicitly marked `(google.api.field_behavior) = REQUIRED`.
395 pub required: bool,
396 /// For oneof fields, the variants with their names and types
397 pub oneof_variants: Option<Vec<OneofVariant>>,
398 /// Documentation from protobuf field comments
399 pub documentation: Option<String>,
400}
401
402impl BodyField {
403 /// Denotes whether this field should be treated as optional in builder APIs.
404 ///
405 /// A field marked `REQUIRED` is never optional — even for complex types — so it becomes a
406 /// required constructor parameter rather than a `with_*` setter. (Without this, a required
407 /// message body like `tag_assignment` would be a no-arg-constructor + optional setter, and the
408 /// NAPI binding would execute with an empty body.)
409 ///
410 /// Otherwise a field is optional when its `UnifiedType.is_optional` flag is set, when it is
411 /// repeated, or when its base type is `Map`, `Message`, or `OneOf` (complex types have a valid
412 /// default and are treated as optional constructor parameters).
413 pub fn is_optional(&self) -> bool {
414 use crate::parsing::types::BaseType;
415 if self.required {
416 return false;
417 }
418 self.field_type.is_optional
419 || self.repeated
420 || matches!(
421 self.field_type.base_type,
422 BaseType::Map(_, _) | BaseType::Message(_) | BaseType::OneOf(_)
423 )
424 }
425}
426
427impl From<BodyField> for RequestParam {
428 fn from(field: BodyField) -> Self {
429 RequestParam::Body(field)
430 }
431}
432
433/// Information about a resource managed by a service
434#[derive(Debug, Clone)]
435pub struct ManagedResource {
436 /// Resource type name (e.g., "Catalog")
437 pub type_name: String,
438 /// Resource descriptor information
439 pub descriptor: ResourceDescriptor,
440}
441
442/// Describes one ancestor step in a managed resource's parent chain, derived from
443/// `google.api.resource_reference { child_type }` annotations on List request fields.
444///
445/// Entries in [`ServicePlan::hierarchy`] are ordered **root-first** (shallowest ancestor first),
446/// so iterating them in order produces the correct param list for resource accessors (e.g.
447/// `["catalog_name", "schema_name"]` for a Table, where catalog is depth 0 and schema depth 1).
448///
449/// Built during analysis via the cross-service global parent map and stored on [`ServicePlan`].
450#[derive(Debug, Clone)]
451#[non_exhaustive]
452pub struct ResourceHierarchy {
453 /// The service's managed resource type string (e.g. `"example.io/Table"`).
454 ///
455 /// Note: on flat APIs this equals the `child_type` annotation value, but the *actual*
456 /// resource type of the ancestor is `parent_resource_type`, which may differ.
457 pub child_resource_type: String,
458 /// The actual resource type of the ancestor identified by `parent_field_name`
459 /// (e.g. `"example.io/Catalog"` for the `catalog_name` field on ListTablesRequest).
460 ///
461 /// This may differ from `child_resource_type` for grandparent fields on flat APIs
462 /// (e.g. `catalog_name` on ListTablesRequest has `child_type = Table` but the field
463 /// actually identifies a Catalog resource).
464 pub parent_resource_type: String,
465 /// The proto field name carrying the ancestor identifier (e.g. `"catalog_name"`).
466 pub parent_field_name: String,
467 /// The singular name of the ancestor resource (e.g. `"catalog"`), resolved by stripping
468 /// `"_name"` from `parent_field_name` and matching against known resource descriptors.
469 /// `None` when the singular cannot be resolved.
470 pub parent_singular: Option<String>,
471}
472
473/// Classifies an RPC method as a standard CRUD operation or custom operation.
474///
475/// This is an internal helper used by [`super::analyze_method`]. Construct via
476/// [`MethodPlanner::try_new`] and consume with [`MethodPlanner::request_type`] and
477/// [`MethodPlanner::http_pattern`].
478pub(crate) struct MethodPlanner<'a> {
479 method: &'a MethodMetadata,
480 pattern: Pattern,
481 path: HttpPattern,
482 metadata: &'a CodeGenMetadata,
483}
484
485impl<'a> MethodPlanner<'a> {
486 pub(crate) fn try_new(
487 method: &'a MethodMetadata,
488 metadata: &'a CodeGenMetadata,
489 ) -> Result<Self> {
490 let Some(pattern) = &method.http_rule.pattern else {
491 return Err(Error::MissingAnnotation {
492 object: method.method_name.clone(),
493 message: "Missing HTTP rule pattern".to_string(),
494 });
495 };
496 Ok(Self {
497 method,
498 path: method.http_pattern.clone(),
499 pattern: pattern.clone(),
500 metadata,
501 })
502 }
503
504 /// Consume the planner and return the pre-parsed HTTP URL pattern.
505 pub(crate) fn into_http_pattern(self) -> HttpPattern {
506 self.path
507 }
508
509 /// Classify the RPC as a standard CRUD operation per Google AIP 131-135.
510 ///
511 /// Each standard operation is identified by matching (verb, HTTP method, path shape,
512 /// resource lookup). See:
513 /// - [AIP-131](https://google.aip.dev/131) Get
514 /// - [AIP-132](https://google.aip.dev/132) List
515 /// - [AIP-133](https://google.aip.dev/133) Create
516 /// - [AIP-134](https://google.aip.dev/134) Update
517 /// - [AIP-135](https://google.aip.dev/135) Delete
518 pub(crate) fn request_type(&self) -> RequestType {
519 let snake_name = operation_to_method_name(&self.method.method_name);
520 let verb_resource = snake_name.split_once('_');
521
522 if let Some((verb, resource)) = verb_resource {
523 // Table of (verb, expected pattern, path must end with parameter?, lookup by plural?)
524 #[allow(clippy::type_complexity)]
525 let standard_ops: &[(
526 &str,
527 fn(&Pattern) -> bool,
528 bool,
529 bool,
530 RequestType,
531 )] = &[
532 (
533 "get",
534 |p| matches!(p, Pattern::Get(_)),
535 true,
536 false,
537 RequestType::Get,
538 ),
539 (
540 "list",
541 |p| matches!(p, Pattern::Get(_)),
542 false,
543 true,
544 RequestType::List,
545 ),
546 (
547 "create",
548 |p| matches!(p, Pattern::Post(_)),
549 false,
550 false,
551 RequestType::Create,
552 ),
553 (
554 "update",
555 |p| matches!(p, Pattern::Patch(_)),
556 true,
557 false,
558 RequestType::Update,
559 ),
560 (
561 "delete",
562 |p| matches!(p, Pattern::Delete(_)),
563 true,
564 false,
565 RequestType::Delete,
566 ),
567 ];
568
569 for &(expected_verb, pattern_check, ends_with_param, use_plural, ref result_type) in
570 standard_ops
571 {
572 if verb != expected_verb || !pattern_check(&self.pattern) {
573 continue;
574 }
575 if ends_with_param && self.path.ends_with_static() {
576 continue;
577 }
578 if !ends_with_param && self.path.ends_with_parameter() {
579 continue;
580 }
581 let found = if use_plural {
582 self.metadata.resource_from_plural(resource).is_some()
583 } else {
584 self.metadata.resource_from_singular(resource).is_some()
585 };
586 if found {
587 return result_type.clone();
588 }
589 }
590 }
591
592 RequestType::Custom(self.pattern.clone())
593 }
594
595 pub(crate) fn has_response(&self) -> bool {
596 !self.method.output_type.is_empty() && !self.method.output_type.ends_with("Empty")
597 }
598
599 /// Extract the simple resource type name from the method's output type.
600 ///
601 /// Strips the package prefix (e.g., `.example.catalog.v1.Catalog` → `Catalog`).
602 pub(crate) fn output_resource_type(&self) -> Option<String> {
603 if self.has_response() {
604 Some(last_segment(&self.method.output_type).to_string())
605 } else {
606 None
607 }
608 }
609}
610
611/// Whether a request of this type carries a JSON body (create / update / custom POST·PATCH).
612///
613/// Single source of truth for the body-attach decision.
614pub(crate) fn request_has_body(request_type: &RequestType) -> bool {
615 matches!(
616 request_type,
617 RequestType::Create
618 | RequestType::Update
619 | RequestType::Custom(Pattern::Post(_))
620 | RequestType::Custom(Pattern::Patch(_))
621 )
622}
623
624/// Whether the Axum server extractor reads request *parts* (path/query) rather than the body.
625///
626/// Single source of truth for the `FromRequestParts`-vs-`FromRequest` decision (and the
627/// `RequestPartsExt` import).
628pub(crate) fn request_needs_request_parts(request_type: &RequestType) -> bool {
629 matches!(
630 request_type,
631 RequestType::List
632 | RequestType::Get
633 | RequestType::Delete
634 | RequestType::Custom(Pattern::Get(_) | Pattern::Delete(_))
635 )
636}
637
638/// Whether a method is a collection-style operation (list / create / factory RPC).
639///
640/// Single source of truth for the collection/instance split. Standard `List`/`Create` always
641/// qualify; custom RPCs qualify by name convention — a `GET` named `List*` (a resource-less list)
642/// or a `POST` named `Generate*` (a factory RPC like `GenerateCredentials`). This is the only place
643/// the `List`/`Generate` proto-name heuristics live.
644pub(crate) fn is_collection_method(request_type: &RequestType, method_name: &str) -> bool {
645 matches!(request_type, RequestType::List | RequestType::Create)
646 || (matches!(request_type, RequestType::Custom(Pattern::Get(_)))
647 && method_name.starts_with("List"))
648 || (matches!(request_type, RequestType::Custom(Pattern::Post(_)))
649 && method_name.starts_with("Generate"))
650}
651
652/// Classify a method's [`MethodShape`] from its request type, proto name, and whether the owning
653/// service manages a `google.api.resource`.
654///
655/// - Resource-less service → [`MethodShape::Unbound`] for every method.
656/// - Resource service, collection-style method → [`MethodShape::CollectionScoped`].
657/// - Resource service, otherwise → [`MethodShape::InstanceScoped`].
658pub(crate) fn method_shape(
659 request_type: &RequestType,
660 method_name: &str,
661 service_has_resource: bool,
662) -> MethodShape {
663 if !service_has_resource {
664 MethodShape::Unbound
665 } else if is_collection_method(request_type, method_name) {
666 MethodShape::CollectionScoped
667 } else {
668 MethodShape::InstanceScoped
669 }
670}
671
672/// The verb to call on a resource-scoped client for standard instance operations, or `None`.
673///
674/// Single source of truth for the scoped-verb mapping.
675pub(crate) fn scoped_verb(request_type: &RequestType) -> Option<String> {
676 match request_type {
677 RequestType::Get => Some("get".to_string()),
678 RequestType::Update => Some("update".to_string()),
679 RequestType::Delete => Some("delete".to_string()),
680 _ => None,
681 }
682}
683
684/// Split body fields from a `MethodPlan` into required and optional subsets.
685///
686/// Delegates to [`BodyField::is_optional`] for the classification. Optional fields
687/// become `with_*` setter methods; required fields become constructor parameters.
688pub fn split_body_fields(plan: &MethodPlan) -> (Vec<&BodyField>, Vec<&BodyField>) {
689 plan.body_fields().partition(|field| !field.is_optional())
690}
691
692/// Extract managed resources from service methods, deduplicating by type name.
693pub fn extract_managed_resources(
694 metadata: &CodeGenMetadata,
695 methods: &[MethodPlan],
696) -> Vec<ManagedResource> {
697 let mut resources = Vec::new();
698 let mut seen_types = HashSet::<String>::new();
699
700 for method in methods {
701 if let Some(ref resource_type) = method.output_resource_type {
702 if seen_types.contains(resource_type) {
703 continue;
704 }
705 if let Some(descriptor) = metadata.get_resource_descriptor(resource_type) {
706 resources.push(ManagedResource {
707 type_name: resource_type.clone(),
708 descriptor: descriptor.clone(),
709 });
710 seen_types.insert(resource_type.clone());
711 }
712 }
713 }
714
715 resources
716}
717
718#[cfg(test)]
719mod tests {
720
721 #[test]
722 fn query_key_is_the_proto_name_unless_json_names_are_asked_or_explicit() {
723 let param = |name: &str, json: Option<&str>| QueryParam {
724 name: name.to_string(),
725 json_name: json.map(str::to_string),
726 field_type: crate::parsing::types::UnifiedType {
727 base_type: crate::parsing::types::BaseType::Int32,
728 is_optional: true,
729 is_repeated: false,
730 },
731 documentation: None,
732 resource_reference: None,
733 };
734 // No `json_name` in the proto: the proto name, unless the package sends JSON names.
735 assert_eq!(param("start_index", None).key(false), "start_index");
736 assert_eq!(param("start_index", None).key(true), "startIndex");
737 // A `json_name` that the proto writes out, even when it is the default one.
738 assert_eq!(param("first", Some("startIndex")).key(false), "startIndex");
739 assert_eq!(
740 param("page_token", Some("pageToken")).key(false),
741 "pageToken"
742 );
743 }
744
745 use super::*;
746
747 fn custom(p: Pattern) -> RequestType {
748 RequestType::Custom(p)
749 }
750
751 #[test]
752 fn request_has_body_matches_write_verbs() {
753 assert!(request_has_body(&RequestType::Create));
754 assert!(request_has_body(&RequestType::Update));
755 assert!(request_has_body(&custom(Pattern::Post(String::new()))));
756 assert!(request_has_body(&custom(Pattern::Patch(String::new()))));
757
758 assert!(!request_has_body(&RequestType::List));
759 assert!(!request_has_body(&RequestType::Get));
760 assert!(!request_has_body(&RequestType::Delete));
761 assert!(!request_has_body(&custom(Pattern::Get(String::new()))));
762 assert!(!request_has_body(&custom(Pattern::Delete(String::new()))));
763 }
764
765 #[test]
766 fn needs_request_parts_matches_read_verbs() {
767 assert!(request_needs_request_parts(&RequestType::List));
768 assert!(request_needs_request_parts(&RequestType::Get));
769 assert!(request_needs_request_parts(&RequestType::Delete));
770 assert!(request_needs_request_parts(&custom(Pattern::Get(
771 String::new()
772 ))));
773 assert!(request_needs_request_parts(&custom(Pattern::Delete(
774 String::new()
775 ))));
776
777 assert!(!request_needs_request_parts(&RequestType::Create));
778 assert!(!request_needs_request_parts(&RequestType::Update));
779 assert!(!request_needs_request_parts(&custom(Pattern::Post(
780 String::new()
781 ))));
782 assert!(!request_needs_request_parts(&custom(Pattern::Patch(
783 String::new()
784 ))));
785 }
786
787 #[test]
788 fn has_body_and_needs_parts_are_mutually_exclusive_for_known_verbs() {
789 // A method either reads from parts or carries a body — never both, never neither —
790 // for the verb shapes the emitters actually produce extractors/clients for.
791 for rt in [
792 RequestType::List,
793 RequestType::Create,
794 RequestType::Get,
795 RequestType::Update,
796 RequestType::Delete,
797 custom(Pattern::Get(String::new())),
798 custom(Pattern::Post(String::new())),
799 custom(Pattern::Patch(String::new())),
800 custom(Pattern::Delete(String::new())),
801 ] {
802 assert_ne!(
803 request_has_body(&rt),
804 request_needs_request_parts(&rt),
805 "body vs request-parts should partition {rt:?}"
806 );
807 }
808 }
809
810 #[test]
811 fn is_collection_method_standard_and_name_heuristics() {
812 // Standard collection verbs always qualify, regardless of name.
813 assert!(is_collection_method(&RequestType::List, "ListThings"));
814 assert!(is_collection_method(&RequestType::Create, "CreateThing"));
815
816 // Custom GET named `List*` (resource-less list) qualifies; other custom GETs don't.
817 assert!(is_collection_method(
818 &custom(Pattern::Get(String::new())),
819 "ListTagAssignments"
820 ));
821 assert!(!is_collection_method(
822 &custom(Pattern::Get(String::new())),
823 "GetTagAssignment"
824 ));
825
826 // Custom POST named `Generate*` (factory RPC) qualifies; other custom POSTs don't.
827 assert!(is_collection_method(
828 &custom(Pattern::Post(String::new())),
829 "GenerateCredentials"
830 ));
831 assert!(!is_collection_method(
832 &custom(Pattern::Post(String::new())),
833 "RotateToken"
834 ));
835
836 // Instance verbs never qualify.
837 assert!(!is_collection_method(&RequestType::Get, "GetThing"));
838 assert!(!is_collection_method(&RequestType::Update, "UpdateThing"));
839 assert!(!is_collection_method(&RequestType::Delete, "DeleteThing"));
840 }
841
842 #[test]
843 fn method_shape_classification() {
844 // Resource-less service → everything Unbound, regardless of verb.
845 assert_eq!(
846 method_shape(&RequestType::List, "ListTagAssignments", false),
847 MethodShape::Unbound
848 );
849 assert_eq!(
850 method_shape(&RequestType::Get, "GetTagAssignment", false),
851 MethodShape::Unbound
852 );
853 assert_eq!(
854 method_shape(&custom(Pattern::Post(String::new())), "TouchTag", false),
855 MethodShape::Unbound
856 );
857
858 // Resource service → collection verbs are CollectionScoped, instance verbs InstanceScoped.
859 assert_eq!(
860 method_shape(&RequestType::List, "ListCatalogs", true),
861 MethodShape::CollectionScoped
862 );
863 assert_eq!(
864 method_shape(&RequestType::Create, "CreateCatalog", true),
865 MethodShape::CollectionScoped
866 );
867 assert_eq!(
868 method_shape(
869 &custom(Pattern::Post(String::new())),
870 "GenerateCredentials",
871 true
872 ),
873 MethodShape::CollectionScoped
874 );
875 assert_eq!(
876 method_shape(&RequestType::Get, "GetCatalog", true),
877 MethodShape::InstanceScoped
878 );
879 assert_eq!(
880 method_shape(&RequestType::Update, "UpdateCatalog", true),
881 MethodShape::InstanceScoped
882 );
883 assert_eq!(
884 method_shape(&RequestType::Delete, "DeleteCatalog", true),
885 MethodShape::InstanceScoped
886 );
887 // Resource-targeted custom POST (not a factory) stays instance-scoped.
888 assert_eq!(
889 method_shape(&custom(Pattern::Post(String::new())), "RotateToken", true),
890 MethodShape::InstanceScoped
891 );
892 }
893
894 #[test]
895 fn emit_shape_classification() {
896 // Standard verbs map directly.
897 assert_eq!(emit_shape(&RequestType::List, false), EmitShape::List);
898 assert_eq!(emit_shape(&RequestType::Create, false), EmitShape::Create);
899 assert_eq!(emit_shape(&RequestType::Get, false), EmitShape::GetUpdate);
900 assert_eq!(
901 emit_shape(&RequestType::Update, false),
902 EmitShape::GetUpdate
903 );
904 assert_eq!(emit_shape(&RequestType::Delete, false), EmitShape::Delete);
905
906 // A collection-style custom POST/PATCH (a factory, e.g. `Generate*`) is Create-shaped.
907 assert_eq!(
908 emit_shape(&custom(Pattern::Post(String::new())), true),
909 EmitShape::Create
910 );
911 assert_eq!(
912 emit_shape(&custom(Pattern::Patch(String::new())), true),
913 EmitShape::Create
914 );
915
916 // A resource-targeted (non-collection) custom POST/PATCH is GetUpdate-shaped.
917 assert_eq!(
918 emit_shape(&custom(Pattern::Post(String::new())), false),
919 EmitShape::GetUpdate
920 );
921
922 // A custom GET (even named `List*`, is_collection=true) is NOT List-shaped — it returns the
923 // full response message.
924 assert_eq!(
925 emit_shape(&custom(Pattern::Get(String::new())), true),
926 EmitShape::GetUpdate
927 );
928 assert_eq!(
929 emit_shape(&custom(Pattern::Get(String::new())), false),
930 EmitShape::GetUpdate
931 );
932 // A custom DELETE is GetUpdate-shaped, not Delete.
933 assert_eq!(
934 emit_shape(&custom(Pattern::Delete(String::new())), false),
935 EmitShape::GetUpdate
936 );
937 }
938
939 #[test]
940 fn scoped_verb_only_for_standard_instance_ops() {
941 assert_eq!(scoped_verb(&RequestType::Get).as_deref(), Some("get"));
942 assert_eq!(scoped_verb(&RequestType::Update).as_deref(), Some("update"));
943 assert_eq!(scoped_verb(&RequestType::Delete).as_deref(), Some("delete"));
944
945 assert_eq!(scoped_verb(&RequestType::List), None);
946 assert_eq!(scoped_verb(&RequestType::Create), None);
947 assert_eq!(scoped_verb(&custom(Pattern::Post(String::new()))), None);
948 assert_eq!(scoped_verb(&custom(Pattern::Get(String::new()))), None);
949 }
950}