olai-codegen 0.0.12

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
/// Represents a segment in a URL template
#[derive(Debug, Clone, PartialEq)]
pub enum UrlSegment {
    /// A static literal segment like "catalogs" or "metadata"
    Static(String),
    /// A path parameter like "{name}" or "{catalog_name}"
    Parameter(String),
}

/// Parsed representation of an HTTP rule pattern
///
/// The [`Default`] is an empty pattern (no template, no segments). It exists for client protocols
/// that carry no HTTP routing (e.g. ConnectRPC), where a `MethodPlan` still needs an `http_pattern`
/// field but the REST emitters that read it are never invoked.
#[derive(Debug, Clone, Default)]
pub struct HttpPattern {
    /// The original template string
    pub template: String,
    /// Parsed segments in order
    pub segments: Vec<UrlSegment>,
    /// Just the parameter names in order (for backward compatibility)
    pub parameters: Vec<String>,
    /// Static prefix (everything before the first parameter)
    pub static_prefix: String,
    /// Static suffix (everything after the last parameter)
    pub static_suffix: Option<String>,
    /// Parameters bound to a multi-segment pattern (`{name=catalogs/*}`, `{path=**}`), whose
    /// values keep `/` in the URL.
    pub multi_segment_parameters: Vec<String>,
}

impl HttpPattern {
    /// Parse an HTTP rule pattern template
    pub fn parse(template: &str) -> Self {
        let (segments, multi_segment_parameters) = parse_url_segments(template);
        let parameters = segments
            .iter()
            .filter_map(|seg| match seg {
                UrlSegment::Parameter(name) => Some(name.clone()),
                UrlSegment::Static(_) => None,
            })
            .collect();

        let static_prefix = extract_static_prefix(&segments);
        let static_suffix = extract_static_suffix(&segments);

        HttpPattern {
            template: template.to_string(),
            segments,
            parameters,
            static_prefix,
            static_suffix,
            multi_segment_parameters,
        }
    }

    /// Whether `name` is bound to a multi-segment pattern, so its value keeps `/`.
    pub fn is_multi_segment(&self, name: &str) -> bool {
        self.multi_segment_parameters.iter().any(|p| p == name)
    }

    pub fn ends_with_static(&self) -> bool {
        self.segments
            .last()
            .is_some_and(|seg| matches!(seg, UrlSegment::Static(_)))
    }

    pub fn ends_with_parameter(&self) -> bool {
        self.segments
            .last()
            .is_some_and(|seg| matches!(seg, UrlSegment::Parameter(_)))
    }

    /// Get the base path (static prefix without leading slash)
    pub fn base_path(&self) -> String {
        self.static_prefix
            .trim_start_matches('/')
            .trim_end_matches('/')
            .to_string()
    }

    /// Get parameter names in the order they appear in the URL
    pub fn parameter_names(&self) -> &[String] {
        &self.parameters
    }

    /// Generate a format string for URL construction
    /// Returns ("/catalogs/{}", ["name"]) for "/catalogs/{name}"
    pub fn to_format_string(&self) -> (String, Vec<String>) {
        let mut format = String::new();
        let mut format_args = Vec::new();

        for segment in &self.segments {
            match segment {
                UrlSegment::Static(literal) => format.push_str(literal),
                UrlSegment::Parameter(name) => {
                    format.push_str("{}");
                    format_args.push(name.clone());
                }
            }
        }

        (format.trim_start_matches('/').to_string(), format_args)
    }
}

/// Normalize the raw contents of a `{…}` placeholder into the single request-field name it binds.
///
/// gRPC transcoding (`google.api.http`) templates use richer placeholder syntax than a bare
/// field name:
/// - **Segment binding**: `{name=catalogs/*}` binds the `name` field to a multi-segment pattern.
///   The pattern after `=` is matched at runtime by the literal URL segments and does not change
///   which field is bound, so we keep only the field name before `=`. **Supported.**
/// - **Dotted field path**: `{table.catalog_name}` binds a *nested* request field. Supporting this
///   correctly would ripple through analysis (nested field resolution), the Rust client URL
///   builder (`request.table.catalog_name` access), and binding signatures. **Not yet supported** —
///   returns `None` so the caller preserves the placeholder verbatim instead of emitting broken
///   code. Tracked as a known limitation.
///
/// Returns the normalized flat field name, or `None` when the placeholder is degenerate
/// (e.g. `{=foo}`) or uses an unsupported shape (dotted path).
fn normalize_placeholder(raw: &str) -> Option<String> {
    let name = raw.split('=').next().unwrap_or("").trim();
    if name.is_empty() || name.contains('.') {
        return None;
    }
    Some(name.to_string())
}

/// Parse URL template into segments, plus the parameters bound to a multi-segment pattern
/// (`{name=catalogs/*}`, `{path=**}`; `{name}` and `{name=*}` match one segment).
fn parse_url_segments(template: &str) -> (Vec<UrlSegment>, Vec<String>) {
    let mut segments = Vec::new();
    let mut multi_segment = Vec::new();
    let mut chars = template.chars().peekable();
    let mut current_static = String::new();

    while let Some(ch) = chars.next() {
        if ch == '{' {
            // Save any accumulated static content
            if !current_static.is_empty() {
                segments.push(UrlSegment::Static(std::mem::take(&mut current_static)));
            }

            // Parse the raw placeholder contents (everything up to the closing `}`).
            let mut raw = String::new();
            let mut closed = false;
            for next_ch in chars.by_ref() {
                if next_ch == '}' {
                    closed = true;
                    break;
                }
                raw.push(next_ch);
            }

            // An unclosed brace (e.g. `{name` with no `}`) is malformed — skip it rather
            // than emitting a parameter with a truncated or empty name.
            match (!raw.is_empty() && closed)
                .then(|| normalize_placeholder(&raw))
                .flatten()
            {
                Some(param_name) => {
                    if raw
                        .split_once('=')
                        .is_some_and(|(_, pattern)| pattern.contains('/') || pattern.contains("**"))
                    {
                        multi_segment.push(param_name.clone());
                    }
                    segments.push(UrlSegment::Parameter(param_name));
                }
                // Unsupported placeholder shape (e.g. a dotted nested path like
                // `{table.catalog_name}`). Preserve it verbatim as a literal so the URL template
                // stays intact and no invalid Rust identifier is ever generated from it. A flat
                // binding for the nested field is a known gap (see `normalize_placeholder`).
                None if closed && !raw.is_empty() => {
                    segments.push(UrlSegment::Static(format!("{{{raw}}}")));
                }
                None => {}
            }
        } else {
            current_static.push(ch);
        }
    }

    // Add any remaining static content
    if !current_static.is_empty() {
        segments.push(UrlSegment::Static(current_static));
    }

    (segments, multi_segment)
}

/// Extract static prefix (everything before first parameter)
fn extract_static_prefix(segments: &[UrlSegment]) -> String {
    let mut prefix = String::new();
    for segment in segments {
        match segment {
            UrlSegment::Static(literal) => prefix.push_str(literal),
            UrlSegment::Parameter(_) => break,
        }
    }
    prefix
}

/// Extract static suffix (everything after last parameter)
fn extract_static_suffix(segments: &[UrlSegment]) -> Option<String> {
    let last_param_index = segments
        .iter()
        .rposition(|segment| matches!(segment, UrlSegment::Parameter(_)))?;
    let suffix: String = segments[last_param_index + 1..]
        .iter()
        .filter_map(|segment| match segment {
            UrlSegment::Static(literal) => Some(literal.as_str()),
            UrlSegment::Parameter(_) => None,
        })
        .collect();

    (!suffix.is_empty()).then_some(suffix)
}

/// Extract path parameter names from URL template like "/catalogs/{name}"
/// (Kept for backward compatibility)
pub fn extract_path_parameters(path_template: &str) -> Vec<String> {
    HttpPattern::parse(path_template).parameters
}

/// Extract pattern information from an HttpRule
pub fn extract_http_rule_pattern(http_rule: &crate::google::api::HttpRule) -> Option<HttpPattern> {
    use crate::google::api::http_rule::Pattern;

    let template = match http_rule.pattern.as_ref()? {
        Pattern::Get(path)
        | Pattern::Post(path)
        | Pattern::Put(path)
        | Pattern::Delete(path)
        | Pattern::Patch(path) => path,
        Pattern::Custom(custom) => &custom.path,
    };

    Some(HttpPattern::parse(template))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_path_parameters() {
        assert_eq!(extract_path_parameters("/catalogs/{name}"), vec!["name"]);
        assert_eq!(
            extract_path_parameters("/shares/{share}/schemas/{schema}/tables/{name}"),
            vec!["share", "schema", "name"]
        );
        assert_eq!(extract_path_parameters("/catalogs"), Vec::<String>::new());
    }

    #[test]
    fn test_http_pattern_parsing() {
        // Test simple static path
        let pattern = HttpPattern::parse("/catalogs");
        assert_eq!(pattern.parameters, Vec::<String>::new());
        assert_eq!(pattern.static_prefix, "/catalogs");
        assert_eq!(pattern.static_suffix, None);

        // Test single parameter
        let pattern = HttpPattern::parse("/catalogs/{name}");
        assert_eq!(pattern.parameters, vec!["name"]);
        assert_eq!(pattern.static_prefix, "/catalogs/");
        assert_eq!(pattern.static_suffix, None);

        // Test multiple parameters
        let pattern = HttpPattern::parse("/shares/{share}/schemas/{schema}/tables/{name}");
        assert_eq!(pattern.parameters, vec!["share", "schema", "name"]);
        assert_eq!(pattern.static_prefix, "/shares/");
        assert_eq!(pattern.static_suffix, None);

        // Test parameter with suffix
        let pattern = HttpPattern::parse("/catalogs/{name}/metadata");
        assert_eq!(pattern.parameters, vec!["name"]);
        assert_eq!(pattern.static_prefix, "/catalogs/");
        assert_eq!(pattern.static_suffix.as_deref(), Some("/metadata"));
    }

    #[test]
    fn test_http_pattern_segments() {
        let pattern = HttpPattern::parse("/shares/{share}/schemas/{schema}");

        use UrlSegment;
        assert_eq!(
            pattern.segments,
            vec![
                UrlSegment::Static("/shares/".to_string()),
                UrlSegment::Parameter("share".to_string()),
                UrlSegment::Static("/schemas/".to_string()),
                UrlSegment::Parameter("schema".to_string()),
            ]
        );
    }

    #[test]
    fn test_http_pattern_to_format_string() {
        let pattern = HttpPattern::parse("/catalogs/{name}");
        let (format_str, args) = pattern.to_format_string();
        assert_eq!(format_str, "catalogs/{}");
        assert_eq!(args, vec!["name"]);

        let pattern = HttpPattern::parse("/shares/{share}/schemas/{schema}");
        let (format_str, args) = pattern.to_format_string();
        assert_eq!(format_str, "shares/{}/schemas/{}");
        assert_eq!(args, vec!["share", "schema"]);
    }

    #[test]
    fn test_http_pattern_base_path() {
        let pattern = HttpPattern::parse("/catalogs/{name}");
        assert_eq!(pattern.base_path(), "catalogs");

        let pattern = HttpPattern::parse("/shares/{share}/schemas");
        assert_eq!(pattern.base_path(), "shares");
    }

    #[test]
    fn test_unclosed_brace_is_ignored() {
        // A malformed template like `/catalogs/{name` (missing closing brace)
        // should not produce a parameter — the unclosed segment is discarded.
        let pattern = HttpPattern::parse("/catalogs/{name");
        assert!(
            pattern.parameters.is_empty(),
            "unclosed brace must not produce a parameter"
        );
        assert_eq!(pattern.static_prefix, "/catalogs/");
    }

    #[test]
    fn test_segment_binding_placeholder() {
        // `{name=catalogs/*}` binds the `name` field; the `=pattern` suffix is stripped.
        let pattern = HttpPattern::parse("/v1/{name=catalogs/*}");
        assert_eq!(pattern.parameters, vec!["name"]);

        let (format_str, args) = pattern.to_format_string();
        assert_eq!(args, vec!["name"]);
        // The format string must not contain the `=catalogs/*` pattern text.
        assert!(!format_str.contains('='), "got: {format_str}");
    }

    #[test]
    fn test_dotted_placeholder_is_preserved_not_a_param() {
        // Dotted nested paths are not yet supported: the placeholder is kept verbatim as a literal
        // (so the URL stays intact) and is NOT surfaced as a parameter (so no invalid ident is
        // generated downstream).
        let pattern = HttpPattern::parse("/v1/tables/{table.catalog_name}/x");
        assert!(
            pattern.parameters.is_empty(),
            "dotted placeholder must not become a parameter: {:?}",
            pattern.parameters
        );
        assert!(
            pattern.template.contains("{table.catalog_name}"),
            "original template text is retained"
        );
    }

    #[test]
    fn test_degenerate_placeholder_is_ignored() {
        // `{=foo}` has no field name before `=` — not a parameter.
        let pattern = HttpPattern::parse("/v1/{=foo}");
        assert!(pattern.parameters.is_empty());
    }

    #[test]
    fn test_extract_http_rule_pattern() {
        use crate::google::api::{HttpRule, http_rule::Pattern};

        // Test GET pattern
        let http_rule = HttpRule {
            pattern: Some(Pattern::Get("/catalogs/{name}".to_string())),
            ..Default::default()
        };

        let pattern = extract_http_rule_pattern(&http_rule).unwrap();
        assert_eq!(pattern.parameters, vec!["name"]);
        assert_eq!(pattern.template, "/catalogs/{name}");

        // Test POST pattern
        let http_rule = HttpRule {
            pattern: Some(Pattern::Post("/catalogs".to_string())),
            ..Default::default()
        };

        let pattern = extract_http_rule_pattern(&http_rule).unwrap();
        assert_eq!(pattern.parameters, Vec::<String>::new());
        assert_eq!(pattern.template, "/catalogs");

        // Test None pattern
        let http_rule = HttpRule {
            pattern: None,
            ..Default::default()
        };

        assert!(extract_http_rule_pattern(&http_rule).is_none());
    }

    #[test]
    fn test_multi_segment_parameters() {
        let pattern = HttpPattern::parse("/v1/{name=catalogs/*}/schemas/{schema}");
        assert_eq!(pattern.multi_segment_parameters, vec!["name"]);
        assert!(pattern.is_multi_segment("name"));
        assert!(!pattern.is_multi_segment("schema"));

        let pattern = HttpPattern::parse("/files/{path=**}");
        assert!(pattern.is_multi_segment("path"));

        // `{name=*}` matches one segment, like `{name}`.
        let pattern = HttpPattern::parse("/catalogs/{name=*}");
        assert!(!pattern.is_multi_segment("name"));
        let pattern = HttpPattern::parse("/catalogs/{name}");
        assert!(pattern.multi_segment_parameters.is_empty());
    }
}