olai-codegen 0.0.1

Proto-driven code generation for REST handlers, clients, and resource registries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::collections::HashSet;

use convert_case::{Case, Casing};
use quote::format_ident;
use syn::Ident;

use crate::error::{Error, Result};
use crate::google::api::{ResourceDescriptor, http_rule::Pattern};
use crate::parsing::types::UnifiedType;
use crate::parsing::{CodeGenMetadata, HttpPattern, MethodMetadata, OneofVariant};

/// The Operation a method is performing
///
/// There are standard CRUD operations, as well as custom operations.
///
/// Standard operations on collections are:
/// - List: Retrieve a list of resources
/// - Create: Create a new resource
///
/// Standard operations on individual resources are:
/// - Get: Retrieve a single resource
/// - Update: Update an existing resource
/// - Delete: Delete a resource
///
/// Custom operations are:
/// - Custom(Pattern): custom HTTP operation
#[derive(Debug, Clone, PartialEq)]
pub enum RequestType {
    List,
    Create,
    Get,
    Update,
    Delete,
    Custom(Pattern),
}

/// A method that was skipped during analysis due to incomplete metadata.
#[derive(Debug, Clone)]
pub struct SkippedMethod {
    /// Fully-qualified name of the service containing the skipped method.
    pub service_name: String,
    /// Name of the skipped method (e.g. `"GetCatalog"`).
    pub method_name: String,
    /// Human-readable reason the method was skipped (e.g. `"missing HTTP annotation"`).
    pub reason: String,
}

/// High-level plan for what code to generate
#[derive(Debug)]
pub struct GenerationPlan {
    /// Services to generate handlers for
    pub services: Vec<ServicePlan>,
    /// Methods that were excluded from the plan due to incomplete metadata.
    ///
    /// Callers can inspect this list to distinguish "service has zero methods" from "all methods
    /// were skipped due to missing HTTP annotations", and to surface actionable warnings.
    pub skipped_methods: Vec<SkippedMethod>,
}

/// Plan for generating code for a single service
#[derive(Debug, Clone)]
pub struct ServicePlan {
    /// Service name (e.g., "CatalogsService")
    pub service_name: String,
    /// Handler trait name (e.g., "CatalogHandler")
    pub handler_name: String,
    /// Base URL path for this service (e.g., "catalogs")
    pub base_path: String,
    /// Proto package name (e.g., "unitycatalog.catalogs.v1")
    pub package: String,
    /// Methods to generate for this service
    pub methods: Vec<MethodPlan>,
    /// Resources managed by this service
    pub managed_resources: Vec<ManagedResource>,
    /// Documentation from protobuf service comments
    pub documentation: Option<String>,
    /// Ancestor chain for this service's managed resource, derived cross-service from
    /// `resource_reference { child_type }` annotations.
    ///
    /// Entries are ordered **root-first** (shallowest ancestor first). For example, for
    /// a Table service this would be `[catalog_name (depth 0), schema_name (depth 1)]`.
    ///
    /// Empty when no `resource_reference` annotations are present — codegen falls back to
    /// naming heuristics in that case.
    pub hierarchy: Vec<ResourceHierarchy>,
}

/// Plan for generating code for a single method
#[derive(Debug, Clone)]
pub struct MethodPlan {
    /// Original method metadata
    pub metadata: MethodMetadata,
    /// Rust function name for the handler method
    pub handler_function_name: String,
    /// Pre-parsed HTTP URL pattern
    pub http_pattern: HttpPattern,
    /// HTTP method string for routing (e.g., "GET", "POST")
    pub http_method: String,
    /// Parameters passed to the method (path, query, and body)
    pub parameters: Vec<RequestParam>,
    /// Whether this method returns a response body
    pub has_response: bool,
    /// Request type for this method
    pub request_type: RequestType,
    /// The resource type name returned by this method (if any)
    pub output_resource_type: Option<String>,
}

impl MethodPlan {
    pub fn path_parameters(&self) -> impl Iterator<Item = &PathParam> {
        self.parameters.iter().filter_map(|param| match param {
            RequestParam::Path(path_param) => Some(path_param),
            _ => None,
        })
    }

    pub fn query_parameters(&self) -> impl Iterator<Item = &QueryParam> {
        self.parameters.iter().filter_map(|param| match param {
            RequestParam::Query(query_param) => Some(query_param),
            _ => None,
        })
    }

    pub fn body_fields(&self) -> impl Iterator<Item = &BodyField> {
        self.parameters.iter().filter_map(|param| match param {
            RequestParam::Body(body_field) => Some(body_field),
            _ => None,
        })
    }
}

#[derive(Debug, Clone)]
pub enum RequestParam {
    Path(PathParam),
    Query(QueryParam),
    Body(BodyField),
}

impl RequestParam {
    pub fn name(&self) -> &str {
        match self {
            RequestParam::Path(param) => &param.name,
            RequestParam::Query(param) => &param.name,
            RequestParam::Body(param) => &param.name,
        }
    }

    pub fn field_type(&self) -> &UnifiedType {
        match self {
            RequestParam::Path(param) => &param.field_type,
            RequestParam::Query(param) => &param.field_type,
            RequestParam::Body(param) => &param.field_type,
        }
    }

    pub fn field_ident(&self) -> Ident {
        format_ident!("{}", self.name())
    }

    pub fn is_optional(&self) -> bool {
        match self {
            RequestParam::Path(_) => false,
            RequestParam::Query(param) => param.is_optional(),
            RequestParam::Body(param) => param.is_optional(),
        }
    }

    pub fn is_path_param(&self) -> bool {
        matches!(self, RequestParam::Path(_))
    }

    pub fn documentation(&self) -> Option<&str> {
        match self {
            RequestParam::Path(param) => param.documentation.as_deref(),
            RequestParam::Query(param) => param.documentation.as_deref(),
            RequestParam::Body(param) => param.documentation.as_deref(),
        }
    }
}

/// A path parameter in a URL template
#[derive(Debug, Clone)]
pub struct PathParam {
    /// Field name in the request struct (e.g., "full_name")
    pub name: String,
    /// Parsed type of the path parameter
    pub field_type: UnifiedType,
    /// Documentation from protobuf field comments
    pub documentation: Option<String>,
}

impl From<PathParam> for RequestParam {
    fn from(param: PathParam) -> Self {
        RequestParam::Path(param)
    }
}

/// A query parameter for HTTP requests
#[derive(Debug, Clone)]
pub struct QueryParam {
    /// Parameter name
    pub name: String,
    /// Parsed type of the query parameter
    pub field_type: UnifiedType,
    /// Documentation from protobuf field comments
    pub documentation: Option<String>,
    /// Resource reference annotation, if present on the corresponding proto field.
    ///
    /// - `child_type` non-empty: this param scopes a parent of that resource type
    ///   (e.g. `catalog_name` with `child_type = "unitycatalog.io/Schema"`).
    /// - `r#type` non-empty: this param directly identifies a resource of that type.
    pub resource_reference: Option<crate::google::api::ResourceReference>,
}

impl QueryParam {
    /// Denotes if the parameter is optional
    pub fn is_optional(&self) -> bool {
        self.field_type.is_optional
    }
}

impl From<QueryParam> for RequestParam {
    fn from(param: QueryParam) -> Self {
        RequestParam::Query(param)
    }
}

/// A body field that should be extracted from the request body
#[derive(Debug, Clone)]
pub struct BodyField {
    /// Field name
    pub name: String,
    /// Parsed type of the body parameter
    pub field_type: UnifiedType,
    /// Whether this field is a repeated (Vec) type
    pub repeated: bool,
    /// For oneof fields, the variants with their names and types
    pub oneof_variants: Option<Vec<OneofVariant>>,
    /// Documentation from protobuf field comments
    pub documentation: Option<String>,
}

impl BodyField {
    /// Denotes whether this field should be treated as optional in builder APIs.
    ///
    /// A field is optional when its `UnifiedType.is_optional` flag is set, when it is
    /// repeated, or when its base type is `Map`, `Message`, or `OneOf` (complex types
    /// always have a valid default and are therefore optional constructor parameters).
    pub fn is_optional(&self) -> bool {
        use crate::parsing::types::BaseType;
        self.field_type.is_optional
            || self.repeated
            || matches!(
                self.field_type.base_type,
                BaseType::Map(_, _) | BaseType::Message(_) | BaseType::OneOf(_)
            )
    }
}

impl From<BodyField> for RequestParam {
    fn from(field: BodyField) -> Self {
        RequestParam::Body(field)
    }
}

/// Information about a resource managed by a service
#[derive(Debug, Clone)]
pub struct ManagedResource {
    /// Resource type name (e.g., "Catalog")
    pub type_name: String,
    /// Resource descriptor information
    pub descriptor: ResourceDescriptor,
}

/// Describes one ancestor step in a managed resource's parent chain, derived from
/// `google.api.resource_reference { child_type }` annotations on List request fields.
///
/// Entries in [`ServicePlan::hierarchy`] are ordered **root-first** (shallowest ancestor first),
/// so iterating them in order produces the correct param list for resource accessors (e.g.
/// `["catalog_name", "schema_name"]` for a Table, where catalog is depth 0 and schema depth 1).
///
/// Built during analysis via the cross-service global parent map and stored on [`ServicePlan`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ResourceHierarchy {
    /// The service's managed resource type string (e.g. `"unitycatalog.io/Table"`).
    ///
    /// Note: on flat APIs this equals the `child_type` annotation value, but the *actual*
    /// resource type of the ancestor is `parent_resource_type`, which may differ.
    pub child_resource_type: String,
    /// The actual resource type of the ancestor identified by `parent_field_name`
    /// (e.g. `"unitycatalog.io/Catalog"` for the `catalog_name` field on ListTablesRequest).
    ///
    /// This may differ from `child_resource_type` for grandparent fields on flat APIs
    /// (e.g. `catalog_name` on ListTablesRequest has `child_type = Table` but the field
    /// actually identifies a Catalog resource).
    pub parent_resource_type: String,
    /// The proto field name carrying the ancestor identifier (e.g. `"catalog_name"`).
    pub parent_field_name: String,
    /// The singular name of the ancestor resource (e.g. `"catalog"`), resolved by stripping
    /// `"_name"` from `parent_field_name` and matching against known resource descriptors.
    /// `None` when the singular cannot be resolved.
    pub parent_singular: Option<String>,
}

/// Classifies an RPC method as a standard CRUD operation or custom operation.
///
/// This is an internal helper used by [`super::analyze_method`]. Construct via
/// [`MethodPlanner::try_new`] and consume with [`MethodPlanner::request_type`] and
/// [`MethodPlanner::http_pattern`].
pub(crate) struct MethodPlanner<'a> {
    method: &'a MethodMetadata,
    pattern: Pattern,
    path: HttpPattern,
    metadata: &'a CodeGenMetadata,
}

impl<'a> MethodPlanner<'a> {
    pub(crate) fn try_new(
        method: &'a MethodMetadata,
        metadata: &'a CodeGenMetadata,
    ) -> Result<Self> {
        let Some(pattern) = &method.http_rule.pattern else {
            return Err(Error::MissingAnnotation {
                object: method.method_name.clone(),
                message: "Missing HTTP rule pattern".to_string(),
            });
        };
        Ok(Self {
            method,
            path: method.http_pattern.clone(),
            pattern: pattern.clone(),
            metadata,
        })
    }

    /// Consume the planner and return the pre-parsed HTTP URL pattern.
    pub(crate) fn into_http_pattern(self) -> HttpPattern {
        self.path
    }

    /// Classify the RPC as a standard CRUD operation per Google AIP 131-135.
    ///
    /// Each standard operation is identified by matching (verb, HTTP method, path shape,
    /// resource lookup). See:
    /// - [AIP-131](https://google.aip.dev/131) Get
    /// - [AIP-132](https://google.aip.dev/132) List
    /// - [AIP-133](https://google.aip.dev/133) Create
    /// - [AIP-134](https://google.aip.dev/134) Update
    /// - [AIP-135](https://google.aip.dev/135) Delete
    pub(crate) fn request_type(&self) -> RequestType {
        let snake_name = self.method.method_name.to_case(Case::Snake);
        let verb_resource = snake_name.split_once('_');

        if let Some((verb, resource)) = verb_resource {
            // Table of (verb, expected pattern, path must end with parameter?, lookup by plural?)
            #[allow(clippy::type_complexity)]
            let standard_ops: &[(
                &str,
                fn(&Pattern) -> bool,
                bool,
                bool,
                RequestType,
            )] = &[
                (
                    "get",
                    |p| matches!(p, Pattern::Get(_)),
                    true,
                    false,
                    RequestType::Get,
                ),
                (
                    "list",
                    |p| matches!(p, Pattern::Get(_)),
                    false,
                    true,
                    RequestType::List,
                ),
                (
                    "create",
                    |p| matches!(p, Pattern::Post(_)),
                    false,
                    false,
                    RequestType::Create,
                ),
                (
                    "update",
                    |p| matches!(p, Pattern::Patch(_)),
                    true,
                    false,
                    RequestType::Update,
                ),
                (
                    "delete",
                    |p| matches!(p, Pattern::Delete(_)),
                    true,
                    false,
                    RequestType::Delete,
                ),
            ];

            for &(expected_verb, pattern_check, ends_with_param, use_plural, ref result_type) in
                standard_ops
            {
                if verb != expected_verb || !pattern_check(&self.pattern) {
                    continue;
                }
                if ends_with_param && self.path.ends_with_static() {
                    continue;
                }
                if !ends_with_param && self.path.ends_with_parameter() {
                    continue;
                }
                let found = if use_plural {
                    self.metadata.resource_from_plural(resource).is_some()
                } else {
                    self.metadata.resource_from_singular(resource).is_some()
                };
                if found {
                    return result_type.clone();
                }
            }
        }

        RequestType::Custom(self.pattern.clone())
    }

    pub(crate) fn has_response(&self) -> bool {
        !self.method.output_type.is_empty() && !self.method.output_type.ends_with("Empty")
    }

    /// Extract the simple resource type name from the method's output type.
    ///
    /// Strips the package prefix (e.g., `.example.catalog.v1.Catalog` → `Catalog`).
    pub(crate) fn output_resource_type(&self) -> Option<String> {
        if self.has_response() {
            let output_type = &self.method.output_type;
            let simple = output_type
                .rfind('.')
                .map(|i| &output_type[i + 1..])
                .unwrap_or(output_type);
            Some(simple.to_string())
        } else {
            None
        }
    }
}

/// Split body fields from a `MethodPlan` into required and optional subsets.
///
/// Delegates to [`BodyField::is_optional`] for the classification. Optional fields
/// become `with_*` setter methods; required fields become constructor parameters.
pub fn split_body_fields(plan: &MethodPlan) -> (Vec<&BodyField>, Vec<&BodyField>) {
    let mut required = Vec::new();
    let mut optional = Vec::new();
    for field in plan.body_fields() {
        if field.is_optional() {
            optional.push(field);
        } else {
            required.push(field);
        }
    }
    (required, optional)
}

/// Extract managed resources from service methods, deduplicating by type name.
pub fn extract_managed_resources(
    metadata: &CodeGenMetadata,
    methods: &[MethodPlan],
) -> Vec<ManagedResource> {
    let mut resources = Vec::new();
    let mut seen_types = HashSet::<String>::new();

    for method in methods {
        if let Some(ref resource_type) = method.output_resource_type {
            if seen_types.contains(resource_type) {
                continue;
            }
            if let Some(descriptor) = metadata.get_resource_descriptor(resource_type) {
                resources.push(ManagedResource {
                    type_name: resource_type.clone(),
                    descriptor: descriptor.clone(),
                });
                seen_types.insert(resource_type.clone());
            }
        }
    }

    resources
}