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 /// Which client protocol layer(s) to emit. See [`ClientProtocols`].
307 ///
308 /// Defaults to REST only, so existing HTTP/JSON output is unchanged.
309 pub client_protocols: ClientProtocols,
310
311 /// Import path of the **connect-rust** (BSR plugin) generated client module, used only when
312 /// [`client_protocols`](Self::client_protocols) includes Connect.
313 ///
314 /// The generated Connect builder layer references the connect-rust client type as
315 /// `<connect_client_path>::{Service}Client`. The path should resolve to the module that
316 /// holds the per-service `{Service}Client<T>` structs (e.g.
317 /// `"headwaters_proto::connect_gen::headwaters::read::v1"`).
318 ///
319 /// Required (non-`None`) whenever Connect is selected and client output is enabled; ignored for
320 /// REST-only output.
321 pub connect_client_path: Option<String>,
322}
323
324/// Default transport type path: the cloud client used by native (non-WASM) generated code.
325pub const DEFAULT_TRANSPORT_TYPE_PATH: &str = "olai_http::CloudClient";
326
327impl CodeGenConfig {
328 /// Whether generated clients use the default cloud transport (`olai_http::CloudClient`).
329 ///
330 /// Controls emission of cloud-specific aggregate constructors (`new_unauthenticated`,
331 /// `new_with_token`), which only make sense for `CloudClient`. A custom transport (e.g. the
332 /// WASM/browser one) gets only the generic `new(transport, base_url)`.
333 pub fn uses_default_transport(&self) -> bool {
334 self.transport_type_path == DEFAULT_TRANSPORT_TYPE_PATH
335 }
336
337 /// Whether the generated client should carry **both** transports, selected at
338 /// compile time by `cfg(target_arch = "wasm32")` — `CloudClient` for native
339 /// targets, `olai_http_wasm::WasmClient` for the browser.
340 ///
341 /// Enabled when WASM bindings output is requested (`output.wasm`): a project
342 /// that wants a browser client needs the same client crate to build both ways
343 /// (native for server-side/tests, wasm32 for the frontend). Native-only
344 /// projects leave `output.wasm` unset and keep the single
345 /// [`transport_type_path`](Self::transport_type_path) transport with no WASM
346 /// dependency.
347 pub fn dual_transport(&self) -> bool {
348 self.output.wasm.is_some()
349 }
350
351 /// Validate this config without running code generation.
352 ///
353 /// Checks that:
354 /// - `models_path_template` and `models_path_crate_template` produce valid Rust paths after
355 /// `{service}` substitution.
356 /// - `bindings` is `Some` whenever `output.python`, `output.node`, `output.node_ts`, or
357 /// `output.wasm` is `Some`.
358 ///
359 /// Call this at construction time to surface misconfiguration early, before generation runs.
360 pub fn validate(&self) -> Result<()> {
361 ModelsPath::new(&self.models_path_template)?;
362 ModelsPath::new(&self.models_path_crate_template)?;
363 let wants_bindings = self.output.python.is_some()
364 || self.output.node.is_some()
365 || self.output.node_ts.is_some()
366 || self.output.wasm.is_some();
367 if wants_bindings && self.bindings.is_none() {
368 return Err(Error::MissingBindingsConfig);
369 }
370 // The Connect client layers over the connect-rust generated client, whose import path the
371 // emitter needs. Only required when client output is actually requested.
372 if self.client_protocols.connect
373 && self.output.client.is_some()
374 && self.connect_client_path.is_none()
375 {
376 return Err(Error::MissingConnectClientPath);
377 }
378 // Language bindings call into the REST aggregate client, so they need REST enabled.
379 if wants_bindings && !self.client_protocols.rest {
380 return Err(Error::BindingsRequireRest);
381 }
382 Ok(())
383 }
384}
385
386/// Output directory configuration for code generation.
387///
388/// Only `common` is required. All other outputs are optional — set to `None` to skip that
389/// output entirely. For example, a server-only crate can omit `client`, and a client-only
390/// crate can omit `server`.
391#[derive(Debug, Clone)]
392pub struct CodeGenOutput {
393 /// Output directory for common (shared extractor) code.
394 pub common: PathBuf,
395 /// Parent models directory (e.g. `crates/common/src/models`).
396 ///
397 /// When `Some`, the generator writes `labels.rs`, `pyo3_impls.rs`, and `mod.rs`
398 /// into a subdirectory named [`models_subdir`](CodeGenOutput::models_subdir)
399 /// inside this path. The buf proto plugin co-locates the compiled model files
400 /// (`<pkg>.rs` / `.serde.rs` / `.tonic.rs`) in that same subdirectory, so the
401 /// `mod.rs` includes them with `include!("./<pkg>.rs")`.
402 pub models: Option<PathBuf>,
403 /// Name of the generated subdirectory inside [`models`](CodeGenOutput::models).
404 ///
405 /// Defaults to `"_gen"`.
406 pub models_subdir: String,
407 /// Output directory for server-side handler and route code. Generation is skipped when `None`.
408 pub server: Option<PathBuf>,
409 /// Output directory for HTTP client code. Generation is skipped when `None`.
410 pub client: Option<PathBuf>,
411 /// Whether to also emit ergonomic resource-scoped clients (`<service>/resource.rs`) alongside
412 /// the low-level per-service client and builders.
413 ///
414 /// A scoped client (e.g. `CatalogClient` bound to a name) captures the resource's name
415 /// components and exposes `get`/`update`/`delete` (+ resource-targeted custom RPCs) returning
416 /// the matching builder. Only emitted for resource-scoped services, and only when
417 /// [`client`](CodeGenOutput::client) is `Some`. Defaults to `false`.
418 pub generate_resource_clients: bool,
419 /// Output directory for Python bindings. Generation is skipped when `None`.
420 pub python: Option<PathBuf>,
421 /// Output directory for Node.js NAPI bindings. Generation is skipped when `None`.
422 pub node: Option<PathBuf>,
423 /// Output directory for Node.js TypeScript client. Generation is skipped when `None`.
424 pub node_ts: Option<PathBuf>,
425 /// Output directory for WASM/browser `#[wasm_bindgen]` bindings + `.d.ts`. Generation is
426 /// skipped when `None`.
427 ///
428 /// Emits a `#[wasm_bindgen]` wrapper layer over the generated (WASM-transport) clients plus a
429 /// `client.d.ts` for JS/TS consumers. Request/response values cross the boundary as plain JS
430 /// objects via `serde-wasm-bindgen`, so this pairs with `runtime: Buffa` (serde-native models)
431 /// and `transport_type_path = "olai_http_wasm::WasmClient"`.
432 pub wasm: Option<PathBuf>,
433 /// Filename for the generated Python typings stub.
434 ///
435 /// Default: `"client.pyi"`
436 pub python_typings_filename: String,
437}
438
439impl CodeGenOutput {
440 /// Absolute path of the generated subdirectory (`models/models_subdir`), if `models` is set.
441 pub fn models_subdir_path(&self) -> Option<PathBuf> {
442 self.models.as_ref().map(|m| m.join(&self.models_subdir))
443 }
444}