Skip to main content

olai_codegen/codegen/
config.rs

1//! Configuration types for code generation.
2//!
3//! Split out of [`super`] so the parent module focuses on generation orchestration.
4//! Re-exported from [`super`] (and `crate`) so the public API path is unchanged.
5
6use std::path::PathBuf;
7
8use crate::error::{Error, Result};
9
10/// Wire protocol a *generated* client speaks.
11///
12/// A single client layer. The set of layers to emit is [`ClientProtocols`]; a server that exposes
13/// both REST and ConnectRPC for the same proto can emit both from one generation run.
14///
15/// - [`ClientProtocol::Rest`]: the HTTP/JSON low-level client ([`super::client`]) plus fluent
16///   builders. Methods are routed from `google.api.http`; a method without an annotation has no
17///   route and is skipped by the REST emitter.
18/// - [`ClientProtocol::Connect`]: fluent builders over the **connect-rust** (BSR plugin) generated
19///   `{Service}Client<T>`, dispatched via [`connectrpc`](https://docs.rs/connectrpc). No
20///   `google.api.http` annotation is required — the whole request message is the body, and
21///   required-vs-optional partitioning comes purely from `google.api.field_behavior`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum ClientProtocol {
24    /// HTTP/JSON client routed from `google.api.http` (the historical default).
25    #[default]
26    Rest,
27    /// ConnectRPC client layered over the connect-rust generated service client.
28    Connect,
29}
30
31impl ClientProtocol {
32    /// The convention subdirectory name for this protocol's client when both are emitted side by
33    /// side (`<service>/rest/`, `<service>/connect/`).
34    pub(crate) fn subdir(self) -> &'static str {
35        match self {
36            ClientProtocol::Rest => "rest",
37            ClientProtocol::Connect => "connect",
38        }
39    }
40}
41
42/// Which client protocol layer(s) to emit.
43///
44/// Analysis is protocol-agnostic (REST analysis is a superset of what ConnectRPC needs), so this is
45/// purely an *emit-time* selection. Emitting both is supported: a server fronting the same proto
46/// over REST and ConnectRPC can hand out either client.
47///
48/// File layout:
49/// - exactly one protocol: emitted **flat** under `<service>/` (`<service>/client.rs`,
50///   `<service>/builders.rs`) — unchanged from single-protocol output.
51/// - both: each protocol gets its own convention subdir (`<service>/rest/`, `<service>/connect/`),
52///   re-exported from `<service>/mod.rs`.
53///
54/// Defaults to REST only, so existing output is unchanged.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct ClientProtocols {
57    /// Emit the REST (HTTP/JSON) client.
58    pub rest: bool,
59    /// Emit the ConnectRPC client.
60    pub connect: bool,
61}
62
63impl Default for ClientProtocols {
64    fn default() -> Self {
65        Self {
66            rest: true,
67            connect: false,
68        }
69    }
70}
71
72impl ClientProtocols {
73    /// Whether more than one protocol is selected (drives the subdir-vs-flat layout decision).
74    pub(crate) fn is_multi(self) -> bool {
75        self.rest && self.connect
76    }
77
78    /// The selected protocols, in deterministic order (REST before Connect).
79    pub(crate) fn selected(self) -> Vec<ClientProtocol> {
80        let mut v = Vec::new();
81        if self.rest {
82            v.push(ClientProtocol::Rest);
83        }
84        if self.connect {
85            v.push(ClientProtocol::Connect);
86        }
87        v
88    }
89}
90
91/// Protobuf runtime that the *generated* code is expected to consume.
92///
93/// This selects the ABI that emitted clients, handlers, and builders are shaped for —
94/// i.e. how generated code reads and writes the consuming project's model types. It does
95/// **not** affect how `olai-codegen` itself parses descriptors.
96///
97/// - [`Runtime::Prost`] (default): models are [prost](https://docs.rs/prost)-generated —
98///   open enums are bare `i32`, singular message fields are `Option<Box<T>>`.
99/// - [`Runtime::Buffa`]: models are [buffa](https://github.com/anthropics/buffa)-generated —
100///   open enums are `EnumValue<E>`, singular message fields are `MessageField<T>`, and the
101///   runtime provides native serde JSON (no separate `pbjson` layer).
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103pub enum Runtime {
104    /// prost-generated models (the historical default).
105    #[default]
106    Prost,
107    /// buffa-generated models.
108    Buffa,
109}
110
111/// Validated model import path derived from a `{service}` template string.
112///
113/// Constructed once from [`CodeGenConfig`] template fields. `resolve` performs the
114/// `{service}` substitution and parses the result as a [`syn::Path`], catching
115/// malformed templates at construction time rather than at code-generation time.
116#[derive(Debug, Clone)]
117pub struct ModelsPath {
118    template: String,
119}
120
121impl ModelsPath {
122    /// Build a `ModelsPath` from a template string containing `{service}` and,
123    /// optionally, `{version}`.
124    ///
125    /// Performs a test substitution at construction to validate the template.
126    pub fn new(template: &str) -> Result<Self> {
127        let test = template
128            .replace("{service}", "test")
129            .replace("{version}", "v1");
130        syn::parse_str::<syn::Path>(&test).map_err(|e| Error::InvalidModelsPathTemplate {
131            template: template.to_string(),
132            source: e,
133        })?;
134        Ok(Self::from_template(template))
135    }
136
137    /// Wrap a template without the construction-time validation done by [`ModelsPath::new`].
138    ///
139    /// For callers that already validated the template (e.g. `generate_code` validates both
140    /// templates up front, so per-service handlers needn't re-parse on every `models_path()`
141    /// call). `resolve`/`try_resolve` still parse the final substituted path.
142    pub(crate) fn from_template(template: &str) -> Self {
143        Self {
144            template: template.to_string(),
145        }
146    }
147
148    /// Replace `{service}` with `service` and return the parsed [`syn::Path`], erroring if the
149    /// substitution does not parse.
150    ///
151    /// `new` only proves the template parses for the literal `test`; a real service segment that
152    /// isn't a valid path component (leading digit, hyphen, reserved word) can still fail here.
153    /// Call this once per service up front (see [`ModelsPath::validate_for`]) so failures surface
154    /// as a clean [`Error::InvalidModelsPathTemplate`] before generation rather than panicking.
155    pub fn try_resolve(&self, service: &str, version: &str) -> Result<syn::Path> {
156        let path = self.substitute(service, version);
157        syn::parse_str(&path).map_err(|source| Error::InvalidModelsPathTemplate {
158            template: path,
159            source,
160        })
161    }
162
163    /// Validate that `service` substitutes into a parseable path. Used up front, per service.
164    ///
165    /// Validates against the conventional `v1` version; the actual version segment is a plain
166    /// path component derived from the proto package, so it cannot make a `{service}`-valid
167    /// template fail to parse.
168    pub fn validate_for(&self, service: &str) -> Result<()> {
169        self.try_resolve(service, "v1").map(|_| ())
170    }
171
172    /// Replace `{service}`/`{version}` and return the parsed [`syn::Path`].
173    ///
174    /// # Panics
175    ///
176    /// Panics if the substituted path doesn't parse. Generation validates every service segment
177    /// up front via [`ModelsPath::validate_for`], so this is unreachable on the generation path;
178    /// prefer [`ModelsPath::try_resolve`] anywhere that hasn't already validated.
179    pub fn resolve(&self, service: &str, version: &str) -> syn::Path {
180        let path = self.substitute(service, version);
181        syn::parse_str(&path)
182            .unwrap_or_else(|e| panic!("Invalid models path `{path}` after substitution: {e}"))
183    }
184
185    /// Substitute the `{service}` and `{version}` placeholders. A template without `{version}`
186    /// is left as-is for that placeholder, preserving any literal version it already encodes.
187    fn substitute(&self, service: &str, version: &str) -> String {
188        self.template
189            .replace("{service}", service)
190            .replace("{version}", version)
191    }
192}
193
194/// Configuration for language-binding code generation (Python / Node.js).
195#[derive(Debug, Clone)]
196pub struct BindingsConfig {
197    /// Name of the aggregate client struct (e.g. `"MyServiceClient"`).
198    pub aggregate_client_name: String,
199    /// Rust crate name used in `use` statements for the client crate
200    /// (e.g. `"my_service_client"`).
201    ///
202    /// This must be set explicitly because the crate name may not match the
203    /// snake_case form of `aggregate_client_name` (e.g. `"MyServiceClient"`
204    /// snake_cases to `"my_service_client"`).
205    pub client_crate_name: String,
206    /// Fully-qualified Python error type (e.g. `"PyMyServiceError"`).
207    pub py_error_type: String,
208    /// Fully-qualified Python result alias (e.g. `"PyMyServiceResult"`).
209    pub py_result_type: String,
210    /// Name of the NAPI error extension trait (e.g. `"NapiErrorExt"`).
211    pub napi_error_ext_trait: String,
212    /// Optional substring filter for the Python typings package.
213    ///
214    /// When `Some(s)`, only messages/enums whose fully-qualified name contains
215    /// `s` are included in the generated `.pyi` file.  When `None`, all
216    /// reachable types are included.
217    pub typings_package_filter: Option<String>,
218    /// Base class name for TypeScript errors (e.g. `"MyServiceError"`).
219    pub ts_error_base_class: String,
220    /// Prefix used in native NAPI error messages (e.g. `"UC"`).
221    pub ts_error_code_prefix: String,
222}
223
224/// Configuration for code generation, including import paths and output directories.
225///
226/// Construct this struct directly and set the fields you need.
227#[derive(Debug, Clone)]
228pub struct CodeGenConfig {
229    /// Fully-qualified path to the request context type used in handler methods.
230    ///
231    /// Default: `"crate::api::RequestContext"`
232    pub context_type_path: String,
233
234    /// Fully-qualified path to the `Result` alias used in generated handler and client code.
235    ///
236    /// Default: `"crate::Result"`
237    pub result_type_path: String,
238
239    /// Template for the external model import path. `{service}` is replaced with the service's
240    /// base path (e.g. `"catalogs"`).
241    ///
242    /// Example: `"my_common::models::{service}::v1"`
243    pub models_path_template: String,
244
245    /// Template for crate-local model import path. `{service}` is replaced with the service's
246    /// base path.
247    ///
248    /// Default: `"crate::models::{service}::v1"`
249    pub models_path_crate_template: String,
250
251    /// Output directory configuration.
252    pub output: CodeGenOutput,
253
254    /// When `true`, generate `labels.rs` with `Resource` / `ObjectLabel` enums derived
255    /// from `google.api.resource` annotations. Requires `output.models` to be `Some`.
256    ///
257    /// Store-specific output (`Label` impl, `RESOURCE_DESCRIPTORS`) is only emitted when
258    /// `generate_store_integration` is also `true`.
259    pub generate_resource_enum: bool,
260
261    /// When `true` (and `generate_resource_enum` is set), emit the `olai_store` integration
262    /// code in `labels.rs`:
263    /// - `impl olai_store::Label for ObjectLabel`
264    /// - `pub static RESOURCE_DESCRIPTORS: &[olai_store::ResourceTypeDescriptor<ObjectLabel>]`
265    ///
266    /// Set to `false` for crates that use the enums without a store dependency.
267    pub generate_store_integration: bool,
268
269    /// Fully-qualified path to the `Error` type used in generated `TryFrom<Resource>` impls.
270    ///
271    /// E.g. `"crate::Error"`. When `None`, `TryFrom` impls are not generated.
272    pub error_type_path: Option<String>,
273
274    /// When `true` and `generate_resource_enum` is set, emit `TryFrom<Object>`/`TryFrom<T>`
275    /// and `ResourceExt` impl blocks in `labels.rs` for all resource types that have an
276    /// `IDENTIFIER`-annotated field, plus a `qualified_name()` inherent method on each
277    /// resource type.
278    pub generate_object_conversions: bool,
279
280    /// Configuration for language-binding generation. Required when `output.python`,
281    /// `output.node`, or `output.node_ts` is `Some`.
282    pub bindings: Option<BindingsConfig>,
283
284    /// Crate name for the resource store types used in generated `RESOURCE_DESCRIPTORS`.
285    ///
286    /// Default: `"olai_store"`
287    pub resource_store_crate_name: String,
288
289    /// Protobuf runtime the generated code is shaped for. See [`Runtime`].
290    ///
291    /// Defaults to [`Runtime::Prost`] for backward compatibility.
292    pub runtime: Runtime,
293
294    /// Fully-qualified path to the HTTP transport type that generated clients store and call.
295    ///
296    /// The transport must expose the surface generated client bodies use: per-verb builder
297    /// methods (`get`/`post`/`patch`/`delete`/`put`) returning a request builder with
298    /// `.json(..)`/`.query(..)`/`.send()`, whose response has `.status()`/`.bytes()`.
299    /// [`olai_http::CloudClient`](https://docs.rs/olai-http) satisfies this.
300    ///
301    /// Defaults to `"olai_http::CloudClient"`, so native output is unchanged. A WASM/browser
302    /// client points this at a lightweight reqwest-Fetch transport that has no `ring`/`tokio`
303    /// dependency and lets the browser attach the session.
304    pub transport_type_path: String,
305
306    /// Force dual-transport client emission (the `cfg`-gated `CloudClient`/`WasmClient`
307    /// `Transport` alias) even when no WASM `#[wasm_bindgen]` bindings output is
308    /// configured. See [`dual_transport`](Self::dual_transport).
309    ///
310    /// Defaults to `false`. Setting `output.wasm` also turns dual-transport on;
311    /// this flag exists so a project can build the same client crate for native
312    /// and `wasm32` *without* pulling in the JS binding layer.
313    pub dual_transport: bool,
314
315    /// Which client protocol layer(s) to emit. See [`ClientProtocols`].
316    ///
317    /// Defaults to REST only, so existing HTTP/JSON output is unchanged.
318    pub client_protocols: ClientProtocols,
319
320    /// Import path of the **connect-rust** (BSR plugin) generated client module, used only when
321    /// [`client_protocols`](Self::client_protocols) includes Connect.
322    ///
323    /// The generated Connect builder layer references the connect-rust client type as
324    /// `<connect_client_path>::{Service}Client`. The path should resolve to the module that
325    /// holds the per-service `{Service}Client<T>` structs (e.g.
326    /// `"headwaters_proto::connect_gen::headwaters::read::v1"`).
327    ///
328    /// Required (non-`None`) whenever Connect is selected and client output is enabled; ignored for
329    /// REST-only output.
330    pub connect_client_path: Option<String>,
331}
332
333/// Default transport type path: the cloud client used by native (non-WASM) generated code.
334pub const DEFAULT_TRANSPORT_TYPE_PATH: &str = "olai_http::CloudClient";
335
336impl CodeGenConfig {
337    /// Whether generated clients use the default cloud transport (`olai_http::CloudClient`).
338    ///
339    /// Controls emission of cloud-specific aggregate constructors (`new_unauthenticated`,
340    /// `new_with_token`), which only make sense for `CloudClient`. A custom transport (e.g. the
341    /// WASM/browser one) gets only the generic `new(transport, base_url)`.
342    pub fn uses_default_transport(&self) -> bool {
343        self.transport_type_path == DEFAULT_TRANSPORT_TYPE_PATH
344    }
345
346    /// Whether the generated client should carry **both** transports, selected at
347    /// compile time by `cfg(target_arch = "wasm32")` — `CloudClient` for native
348    /// targets, `olai_http_wasm::WasmClient` for the browser.
349    ///
350    /// Enabled when WASM bindings output is requested (`output.wasm`), or when
351    /// [`dual_transport`](Self::dual_transport) is set explicitly: a project that
352    /// wants a browser client needs the same client crate to build both ways
353    /// (native for server-side/tests, wasm32 for the frontend). Native-only
354    /// projects leave both unset and keep the single
355    /// [`transport_type_path`](Self::transport_type_path) transport with no WASM
356    /// dependency.
357    ///
358    /// The explicit flag decouples the transport alias from the JS binding layer:
359    /// `output.wasm` additionally emits `#[wasm_bindgen]` bindings, whereas
360    /// `dual_transport = true` alone emits only the `cfg`-gated `Transport` alias.
361    pub fn dual_transport(&self) -> bool {
362        self.output.wasm.is_some() || self.dual_transport
363    }
364
365    /// Validate this config without running code generation.
366    ///
367    /// Checks that:
368    /// - `models_path_template` and `models_path_crate_template` produce valid Rust paths after
369    ///   `{service}` substitution.
370    /// - `bindings` is `Some` whenever `output.python`, `output.node`, `output.node_ts`, or
371    ///   `output.wasm` is `Some`.
372    ///
373    /// Call this at construction time to surface misconfiguration early, before generation runs.
374    pub fn validate(&self) -> Result<()> {
375        ModelsPath::new(&self.models_path_template)?;
376        ModelsPath::new(&self.models_path_crate_template)?;
377        let wants_bindings = self.output.python.is_some()
378            || self.output.node.is_some()
379            || self.output.node_ts.is_some()
380            || self.output.wasm.is_some();
381        if wants_bindings && self.bindings.is_none() {
382            return Err(Error::MissingBindingsConfig);
383        }
384        // The Connect client layers over the connect-rust generated client, whose import path the
385        // emitter needs. Only required when client output is actually requested.
386        if self.client_protocols.connect
387            && self.output.client.is_some()
388            && self.connect_client_path.is_none()
389        {
390            return Err(Error::MissingConnectClientPath);
391        }
392        // Language bindings call into the REST aggregate client, so they need REST enabled.
393        if wants_bindings && !self.client_protocols.rest {
394            return Err(Error::BindingsRequireRest);
395        }
396        Ok(())
397    }
398}
399
400/// Output directory configuration for code generation.
401///
402/// Only `common` is required. All other outputs are optional — set to `None` to skip that
403/// output entirely. For example, a server-only crate can omit `client`, and a client-only
404/// crate can omit `server`.
405#[derive(Debug, Clone)]
406pub struct CodeGenOutput {
407    /// Output directory for common (shared extractor) code.
408    pub common: PathBuf,
409    /// Parent models directory (e.g. `crates/common/src/models`).
410    ///
411    /// When `Some`, the generator writes `labels.rs`, `pyo3_impls.rs`, and `mod.rs`
412    /// into a subdirectory named [`models_subdir`](CodeGenOutput::models_subdir)
413    /// inside this path. The buf proto plugin co-locates the compiled model files
414    /// (`<pkg>.rs` / `.serde.rs` / `.tonic.rs`) in that same subdirectory, so the
415    /// `mod.rs` includes them with `include!("./<pkg>.rs")`.
416    pub models: Option<PathBuf>,
417    /// Name of the generated subdirectory inside [`models`](CodeGenOutput::models).
418    ///
419    /// Defaults to `"_gen"`.
420    pub models_subdir: String,
421    /// Output directory for server-side handler and route code. Generation is skipped when `None`.
422    pub server: Option<PathBuf>,
423    /// Output directory for HTTP client code. Generation is skipped when `None`.
424    pub client: Option<PathBuf>,
425    /// Whether to also emit ergonomic resource-scoped clients (`<service>/resource.rs`) alongside
426    /// the low-level per-service client and builders.
427    ///
428    /// A scoped client (e.g. `CatalogClient` bound to a name) captures the resource's name
429    /// components and exposes `get`/`update`/`delete` (+ resource-targeted custom RPCs) returning
430    /// the matching builder. Only emitted for resource-scoped services, and only when
431    /// [`client`](CodeGenOutput::client) is `Some`. Defaults to `false`.
432    pub generate_resource_clients: bool,
433    /// Output directory for Python bindings. Generation is skipped when `None`.
434    pub python: Option<PathBuf>,
435    /// Output directory for Node.js NAPI bindings. Generation is skipped when `None`.
436    pub node: Option<PathBuf>,
437    /// Output directory for Node.js TypeScript client. Generation is skipped when `None`.
438    pub node_ts: Option<PathBuf>,
439    /// Output directory for WASM/browser `#[wasm_bindgen]` bindings + `.d.ts`. Generation is
440    /// skipped when `None`.
441    ///
442    /// Emits a `#[wasm_bindgen]` wrapper layer over the generated (WASM-transport) clients plus a
443    /// `client.d.ts` for JS/TS consumers. Request/response values cross the boundary as plain JS
444    /// objects via `serde-wasm-bindgen`, so this pairs with `runtime: Buffa` (serde-native models)
445    /// and `transport_type_path = "olai_http_wasm::WasmClient"`.
446    pub wasm: Option<PathBuf>,
447    /// Filename for the generated Python typings stub.
448    ///
449    /// Default: `"client.pyi"`
450    pub python_typings_filename: String,
451}
452
453impl CodeGenOutput {
454    /// Absolute path of the generated subdirectory (`models/models_subdir`), if `models` is set.
455    pub fn models_subdir_path(&self) -> Option<PathBuf> {
456        self.models.as_ref().map(|m| m.join(&self.models_subdir))
457    }
458}