grpc-forge 0.1.2

Generate typed Rust tonic gRPC servers from OpenAPI specs
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
//! OpenAPI → proto3 emitter. The faithful mapping that makes gRPC TYPED:
//! component schemas → proto messages/enums; operations → a service with one rpc
//! each, over synthesized request messages (params + body) and response messages
//! (the 200 schema). Exotic shapes (oneOf/anyOf, inline freeform objects) map to
//! `google.protobuf.Struct` — a documented fallback, not a silent wrong answer.

use std::collections::BTreeSet;

use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use sekkei::{ref_name, OpenApiSpec, Operation, Parameter, Schema};

/// Emit a complete `.proto` for `spec` under `package` (e.g. `breathe.v1`).
#[must_use]
pub fn emit(spec: &OpenApiSpec, package: &str) -> String {
    let mut imports: BTreeSet<String> = BTreeSet::new();
    let mut body = String::new();

    // 1. messages + enums from the named component schemas.
    if let Some(c) = &spec.components {
        for (name, schema) in &c.schemas {
            emit_named(name, schema, &mut body, &mut imports);
        }
    }

    // 2. the service: one rpc per operation, with synthesized request/response.
    emit_service(spec, package, &mut body, &mut imports);

    // 3. assemble: header + imports + body.
    let mut out = String::from("syntax = \"proto3\";\n\n");
    out.push_str(&format!("package {package};\n\n"));
    for imp in &imports {
        out.push_str(&format!("import \"{imp}\";\n"));
    }
    if !imports.is_empty() {
        out.push('\n');
    }
    out.push_str(&body);
    out
}

const STRUCT: &str = "google.protobuf.Struct";
const EMPTY: &str = "google.protobuf.Empty";

/// The proto field type for a schema: `(label, type)` where label is `""` or
/// `"repeated "`. Records any needed well-known imports.
fn field_type(schema: &Schema, imports: &mut BTreeSet<String>) -> (String, String) {
    if schema.is_ref() {
        return (String::new(), ref_name(schema.ref_path.as_deref().unwrap_or("")).to_upper_camel_case());
    }
    if schema.is_array() {
        let inner = schema.items.as_deref().cloned().unwrap_or_default();
        let (_, ity) = field_type(&inner, imports);
        return (String::from("repeated "), ity);
    }
    let ty = match schema.schema_type.as_deref() {
        Some("integer") => if schema.format.as_deref() == Some("int32") { "int32" } else { "int64" }.to_string(),
        Some("number") => if schema.format.as_deref() == Some("float") { "float" } else { "double" }.to_string(),
        Some("string") => match schema.format.as_deref() {
            Some("byte" | "binary") => "bytes".to_string(),
            _ => "string".to_string(),
        },
        Some("boolean") => "bool".to_string(),
        Some("object") => {
            if let Some(ap) = &schema.additional_properties {
                let (_, vty) = field_type(ap, imports);
                format!("map<string, {vty}>")
            } else {
                // inline object / freeform → Struct (documented fallback).
                imports.insert("google/protobuf/struct.proto".into());
                STRUCT.to_string()
            }
        }
        // composed (oneOf/anyOf) or untyped → Struct.
        _ => {
            imports.insert("google/protobuf/struct.proto".into());
            STRUCT.to_string()
        }
    };
    (String::new(), ty)
}

/// Emit a named component schema as a proto message or enum.
fn emit_named(name: &str, schema: &Schema, out: &mut String, imports: &mut BTreeSet<String>) {
    let msg = name.to_upper_camel_case();
    if schema.is_enum() {
        emit_enum(&msg, schema, out);
    } else if schema.is_object() || !schema.properties.is_empty() {
        emit_message(&msg, schema, out, imports);
    } else if schema.is_array() {
        let (label, ity) = field_type(schema, imports);
        out.push_str(&format!("message {msg} {{\n  {label}{ity} items = 1;\n}}\n\n"));
    } else if schema.is_primitive() {
        let (_, ity) = field_type(schema, imports);
        out.push_str(&format!("message {msg} {{\n  {ity} value = 1;\n}}\n\n"));
    } else {
        // composed / freeform → a Struct-valued wrapper.
        imports.insert("google/protobuf/struct.proto".into());
        out.push_str(&format!("message {msg} {{\n  {STRUCT} value = 1;\n}}\n\n"));
    }
}

fn emit_enum(name: &str, schema: &Schema, out: &mut String) {
    out.push_str(&format!("enum {name} {{\n"));
    let prefix = name.to_shouty_snake_case();
    out.push_str(&format!("  {prefix}_UNSPECIFIED = 0;\n"));
    if let Some(values) = &schema.enum_values {
        for (i, v) in values.iter().enumerate() {
            if let Some(s) = v.as_str() {
                out.push_str(&format!("  {prefix}_{} = {};\n", s.to_shouty_snake_case(), i + 1));
            }
        }
    }
    out.push_str("}\n\n");
}

fn emit_message(name: &str, schema: &Schema, out: &mut String, imports: &mut BTreeSet<String>) {
    out.push_str(&format!("message {name} {{\n"));
    for (i, (prop, pschema)) in schema.properties.iter().enumerate() {
        let (label, ty) = field_type(pschema, imports);
        // OpenAPI `nullable: true` → proto3 `optional` (field presence). Without
        // it a scalar field rejects a JSON `null` (pbjson: "invalid type: null,
        // expected a string"); `optional` makes the wire value Option<T>, so null
        // round-trips as None. `optional` is illegal on `repeated`, so skip there.
        let presence = if pschema.nullable && label.is_empty() { "optional " } else { "" };
        out.push_str(&format!("  {presence}{label}{ty} {} = {};\n", prop.to_snake_case(), i + 1));
    }
    out.push_str("}\n\n");
}

/// The proto service name for a package (`breathe.v1` → `Breathe`). Shared by
/// the proto emitter and the scaffold so the generated `service` and the handler
/// trait can never disagree.
#[must_use]
pub fn service_name(package: &str) -> String {
    package.split('.').next().unwrap_or("Api").to_upper_camel_case()
}

/// One rpc's typed signature — the model the proto service AND the tonic handler
/// stub both render from (solve the operation→rpc mapping once).
pub struct RpcSig {
    /// The rpc name (`BandGet`).
    pub rpc: String,
    /// The tonic method name (`band_get`).
    pub method: String,
    /// The request message type (`BandGetRequest`).
    pub req_type: String,
    /// The response type (`Band`, `BandListResponse`, or `google.protobuf.Empty`).
    pub resp_type: String,
}

/// Compute every rpc's typed signature from the spec's operations.
#[must_use]
pub fn rpc_signatures(spec: &OpenApiSpec) -> Vec<RpcSig> {
    let mut sink = String::new();
    let mut imps = BTreeSet::new();
    spec.all_operations()
        .filter_map(|(_m, _p, op)| {
            let op_id = op.operation_id.as_ref()?;
            let rpc = op_id.to_upper_camel_case();
            let resp_type = response_type(&rpc, op.success_response_schema(), &mut sink, &mut imps);
            Some(RpcSig {
                method: rpc.to_snake_case(),
                req_type: format!("{rpc}Request"),
                resp_type,
                rpc,
            })
        })
        .collect()
}

/// Path-level parameters apply to every operation under the path; operation-level
/// parameters override them on `(name, location)`. OpenAPI lets a spec declare
/// shared path params once at the path-item level (DRY); merge them so each
/// synthesized request message carries every addressing field — without this,
/// a path like `/bands/{kind}/{namespace}/{name}` whose params live at the
/// path-item level yields an EMPTY request message (the operation can't be
/// addressed). The merge is the faithful reading of the OpenAPI parameter
/// inheritance rule.
fn merged_params<'a>(spec: &'a OpenApiSpec, path: &str, op: &'a Operation) -> Vec<&'a Parameter> {
    let mut out: Vec<&Parameter> = Vec::new();
    if let Some(item) = spec.paths.get(path) {
        for p in &item.parameters {
            out.push(p);
        }
    }
    for p in &op.parameters {
        // operation-level overrides path-level on the same (name, location).
        if let Some(slot) = out.iter_mut().find(|x| x.name == p.name && x.location == p.location) {
            *slot = p;
        } else {
            out.push(p);
        }
    }
    out
}

/// Emit the service + the synthesized request/response messages for each operation.
fn emit_service(spec: &OpenApiSpec, package: &str, out: &mut String, imports: &mut BTreeSet<String>) {
    let service = service_name(package);
    let mut rpcs = String::new();
    let mut messages = String::new();

    for (_method, path, op) in spec.all_operations() {
        let Some(op_id) = &op.operation_id else { continue };
        let rpc = op_id.to_upper_camel_case();

        // request message: path/query params (path-level + operation-level) + body.
        let req_name = format!("{rpc}Request");
        let mut field_no = 0usize;
        let mut req_fields = String::new();
        for p in merged_params(spec, &path, op) {
            if matches!(p.location.as_str(), "path" | "query") {
                let sch = p.schema.clone().unwrap_or_default();
                let (label, ty) = field_type(&sch, imports);
                field_no += 1;
                req_fields.push_str(&format!("  {label}{ty} {} = {};\n", p.name.to_snake_case(), field_no));
            }
        }
        if let Some(body) = op.json_body_schema() {
            if body.is_ref() {
                field_no += 1;
                let ty = ref_name(body.ref_path.as_deref().unwrap_or("")).to_upper_camel_case();
                req_fields.push_str(&format!("  {ty} body = {field_no};\n"));
            } else if !body.properties.is_empty() {
                // inline body object → embed its properties as request fields.
                for (prop, pschema) in &body.properties {
                    let (label, ty) = field_type(pschema, imports);
                    field_no += 1;
                    req_fields.push_str(&format!("  {label}{ty} {} = {};\n", prop.to_snake_case(), field_no));
                }
            } else {
                imports.insert("google/protobuf/struct.proto".into());
                field_no += 1;
                req_fields.push_str(&format!("  {STRUCT} body = {field_no};\n"));
            }
        }
        messages.push_str(&format!("message {req_name} {{\n{req_fields}}}\n\n"));

        // response type: the 200 schema.
        let resp_ty = response_type(&rpc, op.success_response_schema(), &mut messages, imports);

        rpcs.push_str(&format!("  rpc {rpc}({req_name}) returns ({resp_ty});\n"));
    }

    out.push_str(&messages);
    out.push_str(&format!("service {service} {{\n{rpcs}}}\n"));
}

/// Resolve the rpc return type, synthesizing a `<Rpc>Response` message when the
/// 200 schema is an array or inline object.
fn response_type(
    rpc: &str,
    schema: Option<&Schema>,
    messages: &mut String,
    imports: &mut BTreeSet<String>,
) -> String {
    let Some(schema) = schema else {
        imports.insert("google/protobuf/empty.proto".into());
        return EMPTY.to_string();
    };
    if schema.is_ref() {
        return ref_name(schema.ref_path.as_deref().unwrap_or("")).to_upper_camel_case();
    }
    let resp = format!("{rpc}Response");
    if schema.is_array() {
        let (label, ity) = field_type(schema, imports);
        messages.push_str(&format!("message {resp} {{\n  {label}{ity} items = 1;\n}}\n\n"));
    } else if !schema.properties.is_empty() {
        emit_message(&resp, schema, messages, imports);
    } else {
        imports.insert("google/protobuf/struct.proto".into());
        messages.push_str(&format!("message {resp} {{\n  {STRUCT} value = 1;\n}}\n\n"));
    }
    resp
}

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

    const SPEC: &str = r##"
openapi: 3.0.3
info: { title: breathe control API, version: 0.1.0 }
paths:
  /api/v1/catalog:
    get:
      operationId: catalogList
      responses:
        "200": { content: { application/json: { schema: { $ref: "#/components/schemas/Catalog" } } } }
  /api/v1/bands/{kind}:
    get:
      operationId: bandList
      parameters:
        - { name: kind, in: path, required: true, schema: { type: string } }
        - { name: namespace, in: query, schema: { type: string } }
      responses:
        "200": { content: { application/json: { schema: { type: array, items: { $ref: "#/components/schemas/Band" } } } } }
  /api/v1/bands/{kind}/{namespace}/{name}/dry-run:
    patch:
      operationId: bandSetDryRun
      parameters:
        - { name: kind, in: path, schema: { type: string } }
        - { name: namespace, in: path, schema: { type: string } }
        - { name: name, in: path, schema: { type: string } }
      requestBody:
        content: { application/json: { schema: { type: object, properties: { dryRun: { type: boolean } } } } }
      responses:
        "200": { content: { application/json: { schema: { $ref: "#/components/schemas/Band" } } } }
components:
  schemas:
    BandKind: { type: string, enum: [memory, cpu, storage, arc, cgroup] }
    BandStatus:
      type: object
      properties:
        phase: { type: string }
        lastChangeEpoch: { type: integer }
    Band:
      type: object
      properties:
        spec: { type: object }
        status: { $ref: "#/components/schemas/BandStatus" }
    Catalog:
      type: object
      properties:
        dimensions: { type: array, items: { type: object } }
"##;

    fn proto() -> String {
        let spec: OpenApiSpec = serde_yaml_ng::from_str(SPEC).unwrap();
        emit(&spec, "breathe.v1")
    }

    #[test]
    fn header_package_and_syntax() {
        let p = proto();
        assert!(p.starts_with("syntax = \"proto3\";"));
        assert!(p.contains("package breathe.v1;"));
    }

    #[test]
    fn enum_maps_with_unspecified_zero() {
        let p = proto();
        assert!(p.contains("enum BandKind {"));
        assert!(p.contains("BAND_KIND_UNSPECIFIED = 0;"));
        assert!(p.contains("BAND_KIND_MEMORY = 1;"));
        assert!(p.contains("BAND_KIND_CGROUP = 5;"));
    }

    #[test]
    fn object_schema_becomes_typed_message_with_ref_and_scalar() {
        let p = proto();
        assert!(p.contains("message BandStatus {"));
        // fields number alphabetically (BTreeMap, deterministic): lastChangeEpoch < phase
        assert!(p.contains("int64 last_change_epoch = 1;"));
        assert!(p.contains("string phase = 2;"));
        // a $ref property keeps the typed message name
        assert!(p.contains("BandStatus status ="));
    }

    #[test]
    fn service_rpcs_with_synthesized_request_and_typed_response() {
        let p = proto();
        assert!(p.contains("service Breathe {"));
        // array response → synthesized <Rpc>Response { repeated Band items }
        assert!(p.contains("rpc BandList(BandListRequest) returns (BandListResponse);"));
        assert!(p.contains("repeated Band items = 1;"));
        // $ref response → the message directly
        assert!(p.contains("rpc CatalogList(CatalogListRequest) returns (Catalog);"));
        // inline body props embedded into the request + path params typed
        assert!(p.contains("rpc BandSetDryRun(BandSetDryRunRequest) returns (Band);"));
        assert!(p.contains("bool dry_run ="));
        assert!(p.contains("string kind ="));
    }

    #[test]
    fn struct_import_only_when_used() {
        let p = proto();
        // Band.spec is an inline object → Struct → the import is present
        assert!(p.contains("import \"google/protobuf/struct.proto\";"));
        assert!(p.contains("google.protobuf.Struct spec ="));
    }

    // A path that declares its addressing params ONCE at the path-item level
    // (DRY) — the breathe pattern. The synthesized request must carry them.
    const PATH_LEVEL_SPEC: &str = r##"
openapi: 3.0.3
info: { title: t, version: 0.1.0 }
paths:
  /api/v1/bands/{kind}/{namespace}/{name}:
    parameters:
      - { name: kind, in: path, required: true, schema: { $ref: "#/components/schemas/BandKind" } }
      - { name: namespace, in: path, required: true, schema: { type: string } }
      - { name: name, in: path, required: true, schema: { type: string } }
    get:
      operationId: bandGet
      responses:
        "200": { content: { application/json: { schema: { $ref: "#/components/schemas/Band" } } } }
    patch:
      operationId: bandPatch
      requestBody:
        content: { application/json: { schema: { $ref: "#/components/schemas/BandSpec" } } }
      responses:
        "200": { content: { application/json: { schema: { $ref: "#/components/schemas/Band" } } } }
components:
  schemas:
    BandKind: { type: string, enum: [memory, arc] }
    BandSpec: { type: object, properties: { setpoint: { type: number } } }
    Band: { type: object, properties: { kind: { type: string } } }
"##;

    #[test]
    fn nullable_field_becomes_proto3_optional() {
        let spec_src = r##"
openapi: 3.0.3
info: { title: t, version: 0.1.0 }
paths: {}
components:
  schemas:
    DimensionSpec:
      type: object
      properties:
        id: { type: string }
        upstreamMirror: { type: string, nullable: true }
        tags: { type: array, items: { type: string }, nullable: true }
"##;
        let spec: OpenApiSpec = serde_yaml_ng::from_str(spec_src).unwrap();
        let p = emit(&spec, "x.v1");
        // nullable scalar → `optional` (presence: pbjson maps JSON null → None).
        assert!(p.contains("optional string upstream_mirror ="));
        // non-nullable scalar → no `optional`.
        assert!(p.contains("string id ="));
        assert!(!p.contains("optional string id"));
        // `optional` is illegal on `repeated` → nullable array stays plain repeated.
        assert!(p.contains("repeated string tags ="));
        assert!(!p.contains("optional repeated"));
    }

    #[test]
    fn path_level_params_merge_into_request_messages() {
        let spec: OpenApiSpec = serde_yaml_ng::from_str(PATH_LEVEL_SPEC).unwrap();
        let p = emit(&spec, "breathe.v1");
        // GET: request carries the three path-level addressing fields (typed kind).
        assert!(p.contains("message BandGetRequest {"));
        assert!(p.contains("BandKind kind = 1;"));
        assert!(p.contains("string namespace = 2;"));
        assert!(p.contains("string name = 3;"));
        // PATCH: path-level params PLUS the body, numbered after the params.
        assert!(p.contains("message BandPatchRequest {"));
        assert!(p.contains("BandSpec body = 4;"));
        assert!(p.contains("rpc BandPatch(BandPatchRequest) returns (Band);"));
    }
}